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 | CounterTester | 76 | 77 | ['import junit.framework.TestCase;', 'import java.io.*;', 'import java.util.HashMap;', 'import java.util.TreeMap;', 'import java.util.ArrayList;', '', '/**', ' * This silly little class wraps String, int pairs so they can be sorted.', ' * Used by the WordCounter class.', ' */', 'class WordWrapper implements Comparable <WordWrapper> {', '', ' private String myWord;', ' private int myCount;', ' private int mySlot;', '', ' /**', ' * Creates a new WordWrapper with string "XXX" and count zero.', ' */', ' public WordWrapper (String myWordIn, int myCountIn, int mySlotIn) {', ' myWord = myWordIn;', ' myCount = myCountIn;', ' mySlot = mySlotIn;', ' }', ' /**', ' * Returns a copy of the string in the WordWrapper.', ' *', ' * @return The word contained in this object. Is copied out: no aliasing.', ' */', ' public String extractWord () {', ' return new String (myWord);', ' }', '', ' /**', ' * Returns the count in this WordWrapper.', ' *', ' * @return The count contained in the object.', ' */', ' public int extractCount () {', ' return myCount;', ' }', '', ' public void incCount () {', ' myCount++;', ' }', '', ' public int getCount () {', ' return myCount;', ' }', '', ' public int getPos () {', ' return mySlot;', ' }', '', ' public void setPos (int toWhat) {', ' ', ' mySlot = toWhat;', ' }', '', ' public String toString () {', ' return myWord + " " + mySlot;', ' }', '', ' /**', ' * Comparison operator so we implement the Comparable interface.', ' *', ' * @param w The word wrapper to compare to', ' * @return a positive, zero, or negative value depending upon whether this', ' * word wrapper is less then, equal to, or greater than param w. The', ' * relationship is determied by looking at the counts.', ' */', ' public int compareTo (WordWrapper w) {', " // Check if the count of the current word (myCount) is equal to the count of the word 'w'", ' // If the counts are equal, compare the words lexicographically', ' if (w.myCount == myCount) {'] | [' return myWord.compareTo(w.myWord);', ' }'] | [" // If the counts are not equal, subtract the count of the current word from the count of the word 'w'", ' return w.myCount - myCount;', ' }', '}', '', '', '/**', ' * This class is used to count occurences of words (strings) in a corpus. Used by', ' * the IndexedDocumentCollection class to find the most frequent words in the corpus.', ' */', '', 'class WordCounter {', ' ', " // this is the map that holds (for each word) the number of times we've seen it", ' // note that Integer is a wrapper for the buitin Java int type', ' private HashMap <String, WordWrapper> wordsIHaveSeen = new HashMap <String, WordWrapper> ();', ' private TreeMap <String, String> ones = new TreeMap <String, String> ();', ' ', ' // the set of words that have been extracted', ' private ArrayList<WordWrapper> extractedWords = new ArrayList <WordWrapper> ();', '', ' /**', ' * Accepts a word and increments the count of the number of times we have seen it.', ' * Note that a deep copy of the param is done (no aliasing).', ' *', ' * @param addMe The string to count', ' */', ' public void insert (String addMe) {', ' if (ones.containsKey (addMe)) {', ' ones.remove (addMe);', ' WordWrapper temp = new WordWrapper (addMe, 1, extractedWords.size ());', ' wordsIHaveSeen.put(addMe, temp);', ' extractedWords.add (temp);', ' }', '', ' // first check to see if the word is alredy in wordsIHaveSeen', ' if (wordsIHaveSeen.containsKey (addMe)) {', ' // if it is, then remove and increment its count', ' WordWrapper temp = wordsIHaveSeen.get (addMe);', ' temp.incCount ();', '', ' // find the slot that we go to in the extractedWords list', " // by sorting the 'extractedWords' list in ascending order", ' for (int i = temp.getPos () - 1; i >= 0 && ', ' extractedWords.get (i).compareTo (extractedWords.get (i + 1)) > 0; i--) {', ' temp = extractedWords.get (i + 1);', ' temp.setPos (i);', ' ', ' WordWrapper temp2 = extractedWords.get (i);', ' temp2.setPos (i + 1);', ' ', ' extractedWords.set (i + 1, temp2);', ' extractedWords.set (i, temp);', ' }', '', ' // in this case it is not there, so just add it', ' } else {', ' ones.put (addMe, addMe);', ' }', ' }', '', ' /**', ' * Returns the kth most frequent word in the corpus so far. A deep copy is returned,', ' * so no aliasing is possible. Returns null if there are not enough words.', ' *', ' * @param k Note that the most frequent word is at k = 0', ' * @return The kth most frequent word in the corpus to date', ' */', ' public String getKthMostFrequent (int k) {', '', ' // if we got here, then the array is all set up, so just return the kth most frequent word', ' if (k >= extractedWords.size ()) {', ' int which = extractedWords.size ();', ' for (String s : ones.navigableKeySet ()) {', ' if (which == k)', ' return s;', ' which++;', ' }', ' return null;', ' } else {', ' // If k is less than the size of the extractedWords list,', ' // return the kth most frequent word from extractedWords', ' return extractedWords.get (k).extractWord ();', ' }', ' }', '}', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class CounterTester extends TestCase {', '', ' /**', ' * File object to read words from, with buffering.', ' */', ' private FileReader file = null;', ' private BufferedReader reader = null;', '', ' /**', ' * Close file readers.', ' */', ' private void closeFiles() {', ' try {', ' if (file != null) {', ' file.close();', ' file = null;', ' }', ' if (reader != null) {', ' reader.close();', ' reader = null;', ' }', ' } catch (Exception e) {', ' System.err.println("Problem closing file");', ' System.err.println(e);', ' e.printStackTrace();', ' }', ' }', '', ' /**', ' * Close files no matter what happens in the test.', ' */', ' protected void tearDown () {', ' closeFiles();', ' }', '', ' /**', ' * Open file and set up readers.', ' *', ' * @param fileName name of file to open', ' * */', ' private void openFile(String fileName) {', ' try {', ' file = new FileReader(fileName);', ' reader = new BufferedReader(file);', ' } catch (Exception e) {', ' System.err.format("Problem opening %s file\\n", fileName);', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Read the next numWords from the file.', ' *', ' * @param counter word counter to update', ' * @param numWords number of words to read.', ' */', ' private void readWords(WordCounter counter, int numWords) {', ' try {', ' for (int i=0; i<numWords; i++) {', ' if (i % 100000 == 0)', ' System.out.print (".");', ' String word = reader.readLine();', ' if (word == null) {', ' return;', ' }', " // Insert 'word' into the counter.", ' counter.insert(word);', ' }', ' } catch (Exception e) {', ' System.err.println("Problem reading file");', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Read the next numWords from the file, mixing with queries', ' *', ' * @param counter word counter to update', ' * @param numWords number of words to read.', ' */', ' private void readWordsMixed (WordCounter counter, int numWords) {', ' try {', ' int j = 0;', ' for (int i=0; i<numWords; i++) {', ' String word = reader.readLine();', " // If 'word' is null, it means we've reached the end of the file. So, return from the method.", ' if (word == null) {', ' return;', ' }', ' counter.insert(word);', '', ' // If the current iteration number is a multiple of 10 and greater than 100,000, perform a query of the kth most frequent word.', ' if (i % 10 == 0 && i > 100000) {', ' String myStr = counter.getKthMostFrequent(j++);', ' }', '', ' // rest j once we get to 100', ' if (j == 100)', ' j = 0;', ' }', ' } catch (Exception e) {', ' System.err.println("Problem reading file");', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Check that a sequence of words starts at the "start"th most', ' * frequent word.', ' *', ' * @param counter word counter to lookup', ' * @param start frequency index to start checking at', ' * @param expected array of expected words that start at that frequency', ' */', ' private void checkExpected(WordCounter counter, int start, String [] expected) {', ' for (int i = 0; i<expected.length; i++) {', ' String actual = counter.getKthMostFrequent(start);', ' System.out.format("k: %d, expected: %s, actual: %s\\n",', ' start, expected[i], actual);', ' assertEquals(expected[i], actual);', ' start++;', ' }', ' }', '', ' /**', ' * A test method.', ' * (Replace "X" with a name describing the test. You may write as', ' * many "testSomething" methods in this class as you wish, and each', ' * one will be called when running JUnit over this class.)', ' */', ' public void testSimple() {', ' System.out.println("\\nChecking insert");', ' WordCounter counter = new WordCounter();', ' counter.insert("pizzaz");', ' // Insert the word "pizza" into the counter twice', ' counter.insert("pizza");', ' counter.insert("pizza");', ' String [] expected = {"pizza"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void testTie() {', ' System.out.println("\\nChecking tie for 2nd place");', ' WordCounter counter = new WordCounter();', ' counter.insert("panache");', ' counter.insert("pizzaz");', ' counter.insert("pizza");', ' counter.insert("zebra");', ' counter.insert("pizza");', ' counter.insert("lion");', ' counter.insert("pizzaz");', ' counter.insert("panache");', ' counter.insert("panache");', ' counter.insert("camel");', ' // order is important here', ' String [] expected = {"pizza", "pizzaz"};', ' checkExpected(counter, 1, expected);', ' }', '', '', ' public void testPastTheEnd() {', ' System.out.println("\\nChecking past the end");', ' WordCounter counter = new WordCounter();', ' counter.insert("hi");', ' counter.insert("hello");', ' counter.insert("greetings");', ' counter.insert("salutations");', ' counter.insert("hi");', ' counter.insert("welcome");', ' counter.insert("goodbye");', ' counter.insert("later");', ' counter.insert("hello");', ' counter.insert("when");', ' counter.insert("hi");', ' assertNull(counter.getKthMostFrequent(8));', ' }', '', ' public void test100Top5() {', ' System.out.println("\\nChecking top 5 of 100 words");', ' WordCounter counter = new WordCounter();', ' // Open the file "allWordsBig"', ' openFile("allWordsBig");', ' // Read the next 100 words', ' readWords(counter, 100);', ' String [] expected = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void test300Top5() {', ' System.out.println("\\nChecking top 5 of first 100 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 100);', ' String [] expected1 = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter, 0, expected1);', '', ' System.out.println("Adding 100 more words and rechecking top 5");', ' readWords(counter, 100);', ' String [] expected2 = {"edu", "cmu", "comp", "cs", "state"};', ' checkExpected(counter, 0, expected2);', '', ' System.out.println("Adding 100 more words and rechecking top 5");', ' readWords(counter, 100);', ' String [] expected3 = {"edu", "cmu", "comp", "ohio", "state"};', ' checkExpected(counter, 0, expected3);', ' }', '', ' public void test300Words14Thru19() {', ' System.out.println("\\nChecking rank 14 through 19 of 300 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' // Read the next 300 words', ' readWords(counter, 300);', ' String [] expected = {"cantaloupe", "from", "ksu", "okstate", "on", "srv"};', ' checkExpected(counter, 14, expected);', ' }', '', ' public void test300CorrectNumber() {', ' System.out.println("\\nChecking correct number of unique words in 300 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 300);', ' /* check the 122th, 123th, and 124th most frequent word in the corpus so far ', ' * and check if the result is not null.', ' */', ' assertNotNull(counter.getKthMostFrequent(122));', ' assertNotNull(counter.getKthMostFrequent(123));', ' assertNotNull(counter.getKthMostFrequent(124));', ' // check the 125th most frequent word in the corpus so far', ' // and check if the result is null.', ' assertNull(counter.getKthMostFrequent(125));', ' }', '', ' public void test300and100() {', ' System.out.println("\\nChecking top 5 of 100 and 300 words with two counters");', ' WordCounter counter1 = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter1, 300);', ' closeFiles();', '', ' WordCounter counter2 = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter2, 100);', '', ' String [] expected1 = {"edu", "cmu", "comp", "ohio", "state"};', ' checkExpected(counter1, 0, expected1);', '', ' String [] expected2 = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter2, 0, expected2);', ' }', '', ' public void testAllTop15() {', ' System.out.println("\\nChecking top 15 of all words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' // Read the next 6000000 words', ' readWords(counter, 6000000);', ' String [] expected = {"the", "edu", "to", "of", "and",', ' "in", "is", "ax", "that", "it",', ' "cmu", "for", "com", "you", "cs"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void testAllTop10000() {', ' System.out.println("\\nChecking time to get top 10000 of all words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 6000000);', '', ' for (int i=0; i<10000; i++) {', ' counter.getKthMostFrequent(i);', ' }', ' }', '', ' public void testSpeed() {', ' System.out.println("\\nMixing adding data with finding top k");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWordsMixed (counter, 6000000);', ' String [] expected = {"the", "edu", "to", "of", "and",', ' "in", "is", "ax", "that", "it",', ' "cmu", "for", "com", "you", "cs"};', ' checkExpected(counter, 0, expected);', ' }', '', '}'] | [{'reason_category': 'If Body', 'usage_line': 76}, {'reason_category': 'If Body', 'usage_line': 77}] | Global_Variable 'myWord' used at line 76 is defined at line 13 and has a Long-Range dependency.
Variable 'w' used at line 76 is defined at line 72 and has a Short-Range dependency. | {'If Body': 2} | {'Global_Variable Long-Range': 1, 'Variable Short-Range': 1} |
infilling_java | CounterTester | 79 | 80 | ['import junit.framework.TestCase;', 'import java.io.*;', 'import java.util.HashMap;', 'import java.util.TreeMap;', 'import java.util.ArrayList;', '', '/**', ' * This silly little class wraps String, int pairs so they can be sorted.', ' * Used by the WordCounter class.', ' */', 'class WordWrapper implements Comparable <WordWrapper> {', '', ' private String myWord;', ' private int myCount;', ' private int mySlot;', '', ' /**', ' * Creates a new WordWrapper with string "XXX" and count zero.', ' */', ' public WordWrapper (String myWordIn, int myCountIn, int mySlotIn) {', ' myWord = myWordIn;', ' myCount = myCountIn;', ' mySlot = mySlotIn;', ' }', ' /**', ' * Returns a copy of the string in the WordWrapper.', ' *', ' * @return The word contained in this object. Is copied out: no aliasing.', ' */', ' public String extractWord () {', ' return new String (myWord);', ' }', '', ' /**', ' * Returns the count in this WordWrapper.', ' *', ' * @return The count contained in the object.', ' */', ' public int extractCount () {', ' return myCount;', ' }', '', ' public void incCount () {', ' myCount++;', ' }', '', ' public int getCount () {', ' return myCount;', ' }', '', ' public int getPos () {', ' return mySlot;', ' }', '', ' public void setPos (int toWhat) {', ' ', ' mySlot = toWhat;', ' }', '', ' public String toString () {', ' return myWord + " " + mySlot;', ' }', '', ' /**', ' * Comparison operator so we implement the Comparable interface.', ' *', ' * @param w The word wrapper to compare to', ' * @return a positive, zero, or negative value depending upon whether this', ' * word wrapper is less then, equal to, or greater than param w. The', ' * relationship is determied by looking at the counts.', ' */', ' public int compareTo (WordWrapper w) {', " // Check if the count of the current word (myCount) is equal to the count of the word 'w'", ' // If the counts are equal, compare the words lexicographically', ' if (w.myCount == myCount) {', ' return myWord.compareTo(w.myWord);', ' }', " // If the counts are not equal, subtract the count of the current word from the count of the word 'w'"] | [' return w.myCount - myCount;', ' }'] | ['}', '', '', '/**', ' * This class is used to count occurences of words (strings) in a corpus. Used by', ' * the IndexedDocumentCollection class to find the most frequent words in the corpus.', ' */', '', 'class WordCounter {', ' ', " // this is the map that holds (for each word) the number of times we've seen it", ' // note that Integer is a wrapper for the buitin Java int type', ' private HashMap <String, WordWrapper> wordsIHaveSeen = new HashMap <String, WordWrapper> ();', ' private TreeMap <String, String> ones = new TreeMap <String, String> ();', ' ', ' // the set of words that have been extracted', ' private ArrayList<WordWrapper> extractedWords = new ArrayList <WordWrapper> ();', '', ' /**', ' * Accepts a word and increments the count of the number of times we have seen it.', ' * Note that a deep copy of the param is done (no aliasing).', ' *', ' * @param addMe The string to count', ' */', ' public void insert (String addMe) {', ' if (ones.containsKey (addMe)) {', ' ones.remove (addMe);', ' WordWrapper temp = new WordWrapper (addMe, 1, extractedWords.size ());', ' wordsIHaveSeen.put(addMe, temp);', ' extractedWords.add (temp);', ' }', '', ' // first check to see if the word is alredy in wordsIHaveSeen', ' if (wordsIHaveSeen.containsKey (addMe)) {', ' // if it is, then remove and increment its count', ' WordWrapper temp = wordsIHaveSeen.get (addMe);', ' temp.incCount ();', '', ' // find the slot that we go to in the extractedWords list', " // by sorting the 'extractedWords' list in ascending order", ' for (int i = temp.getPos () - 1; i >= 0 && ', ' extractedWords.get (i).compareTo (extractedWords.get (i + 1)) > 0; i--) {', ' temp = extractedWords.get (i + 1);', ' temp.setPos (i);', ' ', ' WordWrapper temp2 = extractedWords.get (i);', ' temp2.setPos (i + 1);', ' ', ' extractedWords.set (i + 1, temp2);', ' extractedWords.set (i, temp);', ' }', '', ' // in this case it is not there, so just add it', ' } else {', ' ones.put (addMe, addMe);', ' }', ' }', '', ' /**', ' * Returns the kth most frequent word in the corpus so far. A deep copy is returned,', ' * so no aliasing is possible. Returns null if there are not enough words.', ' *', ' * @param k Note that the most frequent word is at k = 0', ' * @return The kth most frequent word in the corpus to date', ' */', ' public String getKthMostFrequent (int k) {', '', ' // if we got here, then the array is all set up, so just return the kth most frequent word', ' if (k >= extractedWords.size ()) {', ' int which = extractedWords.size ();', ' for (String s : ones.navigableKeySet ()) {', ' if (which == k)', ' return s;', ' which++;', ' }', ' return null;', ' } else {', ' // If k is less than the size of the extractedWords list,', ' // return the kth most frequent word from extractedWords', ' return extractedWords.get (k).extractWord ();', ' }', ' }', '}', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class CounterTester extends TestCase {', '', ' /**', ' * File object to read words from, with buffering.', ' */', ' private FileReader file = null;', ' private BufferedReader reader = null;', '', ' /**', ' * Close file readers.', ' */', ' private void closeFiles() {', ' try {', ' if (file != null) {', ' file.close();', ' file = null;', ' }', ' if (reader != null) {', ' reader.close();', ' reader = null;', ' }', ' } catch (Exception e) {', ' System.err.println("Problem closing file");', ' System.err.println(e);', ' e.printStackTrace();', ' }', ' }', '', ' /**', ' * Close files no matter what happens in the test.', ' */', ' protected void tearDown () {', ' closeFiles();', ' }', '', ' /**', ' * Open file and set up readers.', ' *', ' * @param fileName name of file to open', ' * */', ' private void openFile(String fileName) {', ' try {', ' file = new FileReader(fileName);', ' reader = new BufferedReader(file);', ' } catch (Exception e) {', ' System.err.format("Problem opening %s file\\n", fileName);', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Read the next numWords from the file.', ' *', ' * @param counter word counter to update', ' * @param numWords number of words to read.', ' */', ' private void readWords(WordCounter counter, int numWords) {', ' try {', ' for (int i=0; i<numWords; i++) {', ' if (i % 100000 == 0)', ' System.out.print (".");', ' String word = reader.readLine();', ' if (word == null) {', ' return;', ' }', " // Insert 'word' into the counter.", ' counter.insert(word);', ' }', ' } catch (Exception e) {', ' System.err.println("Problem reading file");', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Read the next numWords from the file, mixing with queries', ' *', ' * @param counter word counter to update', ' * @param numWords number of words to read.', ' */', ' private void readWordsMixed (WordCounter counter, int numWords) {', ' try {', ' int j = 0;', ' for (int i=0; i<numWords; i++) {', ' String word = reader.readLine();', " // If 'word' is null, it means we've reached the end of the file. So, return from the method.", ' if (word == null) {', ' return;', ' }', ' counter.insert(word);', '', ' // If the current iteration number is a multiple of 10 and greater than 100,000, perform a query of the kth most frequent word.', ' if (i % 10 == 0 && i > 100000) {', ' String myStr = counter.getKthMostFrequent(j++);', ' }', '', ' // rest j once we get to 100', ' if (j == 100)', ' j = 0;', ' }', ' } catch (Exception e) {', ' System.err.println("Problem reading file");', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Check that a sequence of words starts at the "start"th most', ' * frequent word.', ' *', ' * @param counter word counter to lookup', ' * @param start frequency index to start checking at', ' * @param expected array of expected words that start at that frequency', ' */', ' private void checkExpected(WordCounter counter, int start, String [] expected) {', ' for (int i = 0; i<expected.length; i++) {', ' String actual = counter.getKthMostFrequent(start);', ' System.out.format("k: %d, expected: %s, actual: %s\\n",', ' start, expected[i], actual);', ' assertEquals(expected[i], actual);', ' start++;', ' }', ' }', '', ' /**', ' * A test method.', ' * (Replace "X" with a name describing the test. You may write as', ' * many "testSomething" methods in this class as you wish, and each', ' * one will be called when running JUnit over this class.)', ' */', ' public void testSimple() {', ' System.out.println("\\nChecking insert");', ' WordCounter counter = new WordCounter();', ' counter.insert("pizzaz");', ' // Insert the word "pizza" into the counter twice', ' counter.insert("pizza");', ' counter.insert("pizza");', ' String [] expected = {"pizza"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void testTie() {', ' System.out.println("\\nChecking tie for 2nd place");', ' WordCounter counter = new WordCounter();', ' counter.insert("panache");', ' counter.insert("pizzaz");', ' counter.insert("pizza");', ' counter.insert("zebra");', ' counter.insert("pizza");', ' counter.insert("lion");', ' counter.insert("pizzaz");', ' counter.insert("panache");', ' counter.insert("panache");', ' counter.insert("camel");', ' // order is important here', ' String [] expected = {"pizza", "pizzaz"};', ' checkExpected(counter, 1, expected);', ' }', '', '', ' public void testPastTheEnd() {', ' System.out.println("\\nChecking past the end");', ' WordCounter counter = new WordCounter();', ' counter.insert("hi");', ' counter.insert("hello");', ' counter.insert("greetings");', ' counter.insert("salutations");', ' counter.insert("hi");', ' counter.insert("welcome");', ' counter.insert("goodbye");', ' counter.insert("later");', ' counter.insert("hello");', ' counter.insert("when");', ' counter.insert("hi");', ' assertNull(counter.getKthMostFrequent(8));', ' }', '', ' public void test100Top5() {', ' System.out.println("\\nChecking top 5 of 100 words");', ' WordCounter counter = new WordCounter();', ' // Open the file "allWordsBig"', ' openFile("allWordsBig");', ' // Read the next 100 words', ' readWords(counter, 100);', ' String [] expected = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void test300Top5() {', ' System.out.println("\\nChecking top 5 of first 100 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 100);', ' String [] expected1 = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter, 0, expected1);', '', ' System.out.println("Adding 100 more words and rechecking top 5");', ' readWords(counter, 100);', ' String [] expected2 = {"edu", "cmu", "comp", "cs", "state"};', ' checkExpected(counter, 0, expected2);', '', ' System.out.println("Adding 100 more words and rechecking top 5");', ' readWords(counter, 100);', ' String [] expected3 = {"edu", "cmu", "comp", "ohio", "state"};', ' checkExpected(counter, 0, expected3);', ' }', '', ' public void test300Words14Thru19() {', ' System.out.println("\\nChecking rank 14 through 19 of 300 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' // Read the next 300 words', ' readWords(counter, 300);', ' String [] expected = {"cantaloupe", "from", "ksu", "okstate", "on", "srv"};', ' checkExpected(counter, 14, expected);', ' }', '', ' public void test300CorrectNumber() {', ' System.out.println("\\nChecking correct number of unique words in 300 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 300);', ' /* check the 122th, 123th, and 124th most frequent word in the corpus so far ', ' * and check if the result is not null.', ' */', ' assertNotNull(counter.getKthMostFrequent(122));', ' assertNotNull(counter.getKthMostFrequent(123));', ' assertNotNull(counter.getKthMostFrequent(124));', ' // check the 125th most frequent word in the corpus so far', ' // and check if the result is null.', ' assertNull(counter.getKthMostFrequent(125));', ' }', '', ' public void test300and100() {', ' System.out.println("\\nChecking top 5 of 100 and 300 words with two counters");', ' WordCounter counter1 = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter1, 300);', ' closeFiles();', '', ' WordCounter counter2 = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter2, 100);', '', ' String [] expected1 = {"edu", "cmu", "comp", "ohio", "state"};', ' checkExpected(counter1, 0, expected1);', '', ' String [] expected2 = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter2, 0, expected2);', ' }', '', ' public void testAllTop15() {', ' System.out.println("\\nChecking top 15 of all words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' // Read the next 6000000 words', ' readWords(counter, 6000000);', ' String [] expected = {"the", "edu", "to", "of", "and",', ' "in", "is", "ax", "that", "it",', ' "cmu", "for", "com", "you", "cs"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void testAllTop10000() {', ' System.out.println("\\nChecking time to get top 10000 of all words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 6000000);', '', ' for (int i=0; i<10000; i++) {', ' counter.getKthMostFrequent(i);', ' }', ' }', '', ' public void testSpeed() {', ' System.out.println("\\nMixing adding data with finding top k");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWordsMixed (counter, 6000000);', ' String [] expected = {"the", "edu", "to", "of", "and",', ' "in", "is", "ax", "that", "it",', ' "cmu", "for", "com", "you", "cs"};', ' checkExpected(counter, 0, expected);', ' }', '', '}'] | [] | Variable 'w' used at line 79 is defined at line 72 and has a Short-Range dependency.
Global_Variable 'myCount' used at line 79 is defined at line 14 and has a Long-Range dependency. | {} | {'Variable Short-Range': 1, 'Global_Variable Long-Range': 1} |
infilling_java | CounterTester | 107 | 111 | ['import junit.framework.TestCase;', 'import java.io.*;', 'import java.util.HashMap;', 'import java.util.TreeMap;', 'import java.util.ArrayList;', '', '/**', ' * This silly little class wraps String, int pairs so they can be sorted.', ' * Used by the WordCounter class.', ' */', 'class WordWrapper implements Comparable <WordWrapper> {', '', ' private String myWord;', ' private int myCount;', ' private int mySlot;', '', ' /**', ' * Creates a new WordWrapper with string "XXX" and count zero.', ' */', ' public WordWrapper (String myWordIn, int myCountIn, int mySlotIn) {', ' myWord = myWordIn;', ' myCount = myCountIn;', ' mySlot = mySlotIn;', ' }', ' /**', ' * Returns a copy of the string in the WordWrapper.', ' *', ' * @return The word contained in this object. Is copied out: no aliasing.', ' */', ' public String extractWord () {', ' return new String (myWord);', ' }', '', ' /**', ' * Returns the count in this WordWrapper.', ' *', ' * @return The count contained in the object.', ' */', ' public int extractCount () {', ' return myCount;', ' }', '', ' public void incCount () {', ' myCount++;', ' }', '', ' public int getCount () {', ' return myCount;', ' }', '', ' public int getPos () {', ' return mySlot;', ' }', '', ' public void setPos (int toWhat) {', ' ', ' mySlot = toWhat;', ' }', '', ' public String toString () {', ' return myWord + " " + mySlot;', ' }', '', ' /**', ' * Comparison operator so we implement the Comparable interface.', ' *', ' * @param w The word wrapper to compare to', ' * @return a positive, zero, or negative value depending upon whether this', ' * word wrapper is less then, equal to, or greater than param w. The', ' * relationship is determied by looking at the counts.', ' */', ' public int compareTo (WordWrapper w) {', " // Check if the count of the current word (myCount) is equal to the count of the word 'w'", ' // If the counts are equal, compare the words lexicographically', ' if (w.myCount == myCount) {', ' return myWord.compareTo(w.myWord);', ' }', " // If the counts are not equal, subtract the count of the current word from the count of the word 'w'", ' return w.myCount - myCount;', ' }', '}', '', '', '/**', ' * This class is used to count occurences of words (strings) in a corpus. Used by', ' * the IndexedDocumentCollection class to find the most frequent words in the corpus.', ' */', '', 'class WordCounter {', ' ', " // this is the map that holds (for each word) the number of times we've seen it", ' // note that Integer is a wrapper for the buitin Java int type', ' private HashMap <String, WordWrapper> wordsIHaveSeen = new HashMap <String, WordWrapper> ();', ' private TreeMap <String, String> ones = new TreeMap <String, String> ();', ' ', ' // the set of words that have been extracted', ' private ArrayList<WordWrapper> extractedWords = new ArrayList <WordWrapper> ();', '', ' /**', ' * Accepts a word and increments the count of the number of times we have seen it.', ' * Note that a deep copy of the param is done (no aliasing).', ' *', ' * @param addMe The string to count', ' */', ' public void insert (String addMe) {', ' if (ones.containsKey (addMe)) {'] | [' ones.remove (addMe);', ' WordWrapper temp = new WordWrapper (addMe, 1, extractedWords.size ());', ' wordsIHaveSeen.put(addMe, temp);', ' extractedWords.add (temp);', ' }'] | ['', ' // first check to see if the word is alredy in wordsIHaveSeen', ' if (wordsIHaveSeen.containsKey (addMe)) {', ' // if it is, then remove and increment its count', ' WordWrapper temp = wordsIHaveSeen.get (addMe);', ' temp.incCount ();', '', ' // find the slot that we go to in the extractedWords list', " // by sorting the 'extractedWords' list in ascending order", ' for (int i = temp.getPos () - 1; i >= 0 && ', ' extractedWords.get (i).compareTo (extractedWords.get (i + 1)) > 0; i--) {', ' temp = extractedWords.get (i + 1);', ' temp.setPos (i);', ' ', ' WordWrapper temp2 = extractedWords.get (i);', ' temp2.setPos (i + 1);', ' ', ' extractedWords.set (i + 1, temp2);', ' extractedWords.set (i, temp);', ' }', '', ' // in this case it is not there, so just add it', ' } else {', ' ones.put (addMe, addMe);', ' }', ' }', '', ' /**', ' * Returns the kth most frequent word in the corpus so far. A deep copy is returned,', ' * so no aliasing is possible. Returns null if there are not enough words.', ' *', ' * @param k Note that the most frequent word is at k = 0', ' * @return The kth most frequent word in the corpus to date', ' */', ' public String getKthMostFrequent (int k) {', '', ' // if we got here, then the array is all set up, so just return the kth most frequent word', ' if (k >= extractedWords.size ()) {', ' int which = extractedWords.size ();', ' for (String s : ones.navigableKeySet ()) {', ' if (which == k)', ' return s;', ' which++;', ' }', ' return null;', ' } else {', ' // If k is less than the size of the extractedWords list,', ' // return the kth most frequent word from extractedWords', ' return extractedWords.get (k).extractWord ();', ' }', ' }', '}', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class CounterTester extends TestCase {', '', ' /**', ' * File object to read words from, with buffering.', ' */', ' private FileReader file = null;', ' private BufferedReader reader = null;', '', ' /**', ' * Close file readers.', ' */', ' private void closeFiles() {', ' try {', ' if (file != null) {', ' file.close();', ' file = null;', ' }', ' if (reader != null) {', ' reader.close();', ' reader = null;', ' }', ' } catch (Exception e) {', ' System.err.println("Problem closing file");', ' System.err.println(e);', ' e.printStackTrace();', ' }', ' }', '', ' /**', ' * Close files no matter what happens in the test.', ' */', ' protected void tearDown () {', ' closeFiles();', ' }', '', ' /**', ' * Open file and set up readers.', ' *', ' * @param fileName name of file to open', ' * */', ' private void openFile(String fileName) {', ' try {', ' file = new FileReader(fileName);', ' reader = new BufferedReader(file);', ' } catch (Exception e) {', ' System.err.format("Problem opening %s file\\n", fileName);', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Read the next numWords from the file.', ' *', ' * @param counter word counter to update', ' * @param numWords number of words to read.', ' */', ' private void readWords(WordCounter counter, int numWords) {', ' try {', ' for (int i=0; i<numWords; i++) {', ' if (i % 100000 == 0)', ' System.out.print (".");', ' String word = reader.readLine();', ' if (word == null) {', ' return;', ' }', " // Insert 'word' into the counter.", ' counter.insert(word);', ' }', ' } catch (Exception e) {', ' System.err.println("Problem reading file");', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Read the next numWords from the file, mixing with queries', ' *', ' * @param counter word counter to update', ' * @param numWords number of words to read.', ' */', ' private void readWordsMixed (WordCounter counter, int numWords) {', ' try {', ' int j = 0;', ' for (int i=0; i<numWords; i++) {', ' String word = reader.readLine();', " // If 'word' is null, it means we've reached the end of the file. So, return from the method.", ' if (word == null) {', ' return;', ' }', ' counter.insert(word);', '', ' // If the current iteration number is a multiple of 10 and greater than 100,000, perform a query of the kth most frequent word.', ' if (i % 10 == 0 && i > 100000) {', ' String myStr = counter.getKthMostFrequent(j++);', ' }', '', ' // rest j once we get to 100', ' if (j == 100)', ' j = 0;', ' }', ' } catch (Exception e) {', ' System.err.println("Problem reading file");', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Check that a sequence of words starts at the "start"th most', ' * frequent word.', ' *', ' * @param counter word counter to lookup', ' * @param start frequency index to start checking at', ' * @param expected array of expected words that start at that frequency', ' */', ' private void checkExpected(WordCounter counter, int start, String [] expected) {', ' for (int i = 0; i<expected.length; i++) {', ' String actual = counter.getKthMostFrequent(start);', ' System.out.format("k: %d, expected: %s, actual: %s\\n",', ' start, expected[i], actual);', ' assertEquals(expected[i], actual);', ' start++;', ' }', ' }', '', ' /**', ' * A test method.', ' * (Replace "X" with a name describing the test. You may write as', ' * many "testSomething" methods in this class as you wish, and each', ' * one will be called when running JUnit over this class.)', ' */', ' public void testSimple() {', ' System.out.println("\\nChecking insert");', ' WordCounter counter = new WordCounter();', ' counter.insert("pizzaz");', ' // Insert the word "pizza" into the counter twice', ' counter.insert("pizza");', ' counter.insert("pizza");', ' String [] expected = {"pizza"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void testTie() {', ' System.out.println("\\nChecking tie for 2nd place");', ' WordCounter counter = new WordCounter();', ' counter.insert("panache");', ' counter.insert("pizzaz");', ' counter.insert("pizza");', ' counter.insert("zebra");', ' counter.insert("pizza");', ' counter.insert("lion");', ' counter.insert("pizzaz");', ' counter.insert("panache");', ' counter.insert("panache");', ' counter.insert("camel");', ' // order is important here', ' String [] expected = {"pizza", "pizzaz"};', ' checkExpected(counter, 1, expected);', ' }', '', '', ' public void testPastTheEnd() {', ' System.out.println("\\nChecking past the end");', ' WordCounter counter = new WordCounter();', ' counter.insert("hi");', ' counter.insert("hello");', ' counter.insert("greetings");', ' counter.insert("salutations");', ' counter.insert("hi");', ' counter.insert("welcome");', ' counter.insert("goodbye");', ' counter.insert("later");', ' counter.insert("hello");', ' counter.insert("when");', ' counter.insert("hi");', ' assertNull(counter.getKthMostFrequent(8));', ' }', '', ' public void test100Top5() {', ' System.out.println("\\nChecking top 5 of 100 words");', ' WordCounter counter = new WordCounter();', ' // Open the file "allWordsBig"', ' openFile("allWordsBig");', ' // Read the next 100 words', ' readWords(counter, 100);', ' String [] expected = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void test300Top5() {', ' System.out.println("\\nChecking top 5 of first 100 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 100);', ' String [] expected1 = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter, 0, expected1);', '', ' System.out.println("Adding 100 more words and rechecking top 5");', ' readWords(counter, 100);', ' String [] expected2 = {"edu", "cmu", "comp", "cs", "state"};', ' checkExpected(counter, 0, expected2);', '', ' System.out.println("Adding 100 more words and rechecking top 5");', ' readWords(counter, 100);', ' String [] expected3 = {"edu", "cmu", "comp", "ohio", "state"};', ' checkExpected(counter, 0, expected3);', ' }', '', ' public void test300Words14Thru19() {', ' System.out.println("\\nChecking rank 14 through 19 of 300 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' // Read the next 300 words', ' readWords(counter, 300);', ' String [] expected = {"cantaloupe", "from", "ksu", "okstate", "on", "srv"};', ' checkExpected(counter, 14, expected);', ' }', '', ' public void test300CorrectNumber() {', ' System.out.println("\\nChecking correct number of unique words in 300 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 300);', ' /* check the 122th, 123th, and 124th most frequent word in the corpus so far ', ' * and check if the result is not null.', ' */', ' assertNotNull(counter.getKthMostFrequent(122));', ' assertNotNull(counter.getKthMostFrequent(123));', ' assertNotNull(counter.getKthMostFrequent(124));', ' // check the 125th most frequent word in the corpus so far', ' // and check if the result is null.', ' assertNull(counter.getKthMostFrequent(125));', ' }', '', ' public void test300and100() {', ' System.out.println("\\nChecking top 5 of 100 and 300 words with two counters");', ' WordCounter counter1 = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter1, 300);', ' closeFiles();', '', ' WordCounter counter2 = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter2, 100);', '', ' String [] expected1 = {"edu", "cmu", "comp", "ohio", "state"};', ' checkExpected(counter1, 0, expected1);', '', ' String [] expected2 = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter2, 0, expected2);', ' }', '', ' public void testAllTop15() {', ' System.out.println("\\nChecking top 15 of all words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' // Read the next 6000000 words', ' readWords(counter, 6000000);', ' String [] expected = {"the", "edu", "to", "of", "and",', ' "in", "is", "ax", "that", "it",', ' "cmu", "for", "com", "you", "cs"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void testAllTop10000() {', ' System.out.println("\\nChecking time to get top 10000 of all words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 6000000);', '', ' for (int i=0; i<10000; i++) {', ' counter.getKthMostFrequent(i);', ' }', ' }', '', ' public void testSpeed() {', ' System.out.println("\\nMixing adding data with finding top k");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWordsMixed (counter, 6000000);', ' String [] expected = {"the", "edu", "to", "of", "and",', ' "in", "is", "ax", "that", "it",', ' "cmu", "for", "com", "you", "cs"};', ' checkExpected(counter, 0, expected);', ' }', '', '}'] | [{'reason_category': 'If Body', 'usage_line': 107}, {'reason_category': 'If Body', 'usage_line': 108}, {'reason_category': 'If Body', 'usage_line': 109}, {'reason_category': 'If Body', 'usage_line': 110}, {'reason_category': 'If Body', 'usage_line': 111}] | Global_Variable 'ones' used at line 107 is defined at line 94 and has a Medium-Range dependency.
Variable 'addMe' used at line 107 is defined at line 105 and has a Short-Range dependency.
Class 'WordWrapper' used at line 108 is defined at line 11 and has a Long-Range dependency.
Variable 'addMe' used at line 108 is defined at line 105 and has a Short-Range dependency.
Global_Variable 'extractedWords' used at line 108 is defined at line 97 and has a Medium-Range dependency.
Global_Variable 'wordsIHaveSeen' used at line 109 is defined at line 93 and has a Medium-Range dependency.
Variable 'addMe' used at line 109 is defined at line 105 and has a Short-Range dependency.
Variable 'temp' used at line 109 is defined at line 108 and has a Short-Range dependency.
Global_Variable 'extractedWords' used at line 110 is defined at line 97 and has a Medium-Range dependency.
Variable 'temp' used at line 110 is defined at line 108 and has a Short-Range dependency. | {'If Body': 5} | {'Global_Variable Medium-Range': 4, 'Variable Short-Range': 5, 'Class Long-Range': 1} |
infilling_java | CounterTester | 116 | 117 | ['import junit.framework.TestCase;', 'import java.io.*;', 'import java.util.HashMap;', 'import java.util.TreeMap;', 'import java.util.ArrayList;', '', '/**', ' * This silly little class wraps String, int pairs so they can be sorted.', ' * Used by the WordCounter class.', ' */', 'class WordWrapper implements Comparable <WordWrapper> {', '', ' private String myWord;', ' private int myCount;', ' private int mySlot;', '', ' /**', ' * Creates a new WordWrapper with string "XXX" and count zero.', ' */', ' public WordWrapper (String myWordIn, int myCountIn, int mySlotIn) {', ' myWord = myWordIn;', ' myCount = myCountIn;', ' mySlot = mySlotIn;', ' }', ' /**', ' * Returns a copy of the string in the WordWrapper.', ' *', ' * @return The word contained in this object. Is copied out: no aliasing.', ' */', ' public String extractWord () {', ' return new String (myWord);', ' }', '', ' /**', ' * Returns the count in this WordWrapper.', ' *', ' * @return The count contained in the object.', ' */', ' public int extractCount () {', ' return myCount;', ' }', '', ' public void incCount () {', ' myCount++;', ' }', '', ' public int getCount () {', ' return myCount;', ' }', '', ' public int getPos () {', ' return mySlot;', ' }', '', ' public void setPos (int toWhat) {', ' ', ' mySlot = toWhat;', ' }', '', ' public String toString () {', ' return myWord + " " + mySlot;', ' }', '', ' /**', ' * Comparison operator so we implement the Comparable interface.', ' *', ' * @param w The word wrapper to compare to', ' * @return a positive, zero, or negative value depending upon whether this', ' * word wrapper is less then, equal to, or greater than param w. The', ' * relationship is determied by looking at the counts.', ' */', ' public int compareTo (WordWrapper w) {', " // Check if the count of the current word (myCount) is equal to the count of the word 'w'", ' // If the counts are equal, compare the words lexicographically', ' if (w.myCount == myCount) {', ' return myWord.compareTo(w.myWord);', ' }', " // If the counts are not equal, subtract the count of the current word from the count of the word 'w'", ' return w.myCount - myCount;', ' }', '}', '', '', '/**', ' * This class is used to count occurences of words (strings) in a corpus. Used by', ' * the IndexedDocumentCollection class to find the most frequent words in the corpus.', ' */', '', 'class WordCounter {', ' ', " // this is the map that holds (for each word) the number of times we've seen it", ' // note that Integer is a wrapper for the buitin Java int type', ' private HashMap <String, WordWrapper> wordsIHaveSeen = new HashMap <String, WordWrapper> ();', ' private TreeMap <String, String> ones = new TreeMap <String, String> ();', ' ', ' // the set of words that have been extracted', ' private ArrayList<WordWrapper> extractedWords = new ArrayList <WordWrapper> ();', '', ' /**', ' * Accepts a word and increments the count of the number of times we have seen it.', ' * Note that a deep copy of the param is done (no aliasing).', ' *', ' * @param addMe The string to count', ' */', ' public void insert (String addMe) {', ' if (ones.containsKey (addMe)) {', ' ones.remove (addMe);', ' WordWrapper temp = new WordWrapper (addMe, 1, extractedWords.size ());', ' wordsIHaveSeen.put(addMe, temp);', ' extractedWords.add (temp);', ' }', '', ' // first check to see if the word is alredy in wordsIHaveSeen', ' if (wordsIHaveSeen.containsKey (addMe)) {', ' // if it is, then remove and increment its count'] | [' WordWrapper temp = wordsIHaveSeen.get (addMe);', ' temp.incCount ();'] | ['', ' // find the slot that we go to in the extractedWords list', " // by sorting the 'extractedWords' list in ascending order", ' for (int i = temp.getPos () - 1; i >= 0 && ', ' extractedWords.get (i).compareTo (extractedWords.get (i + 1)) > 0; i--) {', ' temp = extractedWords.get (i + 1);', ' temp.setPos (i);', ' ', ' WordWrapper temp2 = extractedWords.get (i);', ' temp2.setPos (i + 1);', ' ', ' extractedWords.set (i + 1, temp2);', ' extractedWords.set (i, temp);', ' }', '', ' // in this case it is not there, so just add it', ' } else {', ' ones.put (addMe, addMe);', ' }', ' }', '', ' /**', ' * Returns the kth most frequent word in the corpus so far. A deep copy is returned,', ' * so no aliasing is possible. Returns null if there are not enough words.', ' *', ' * @param k Note that the most frequent word is at k = 0', ' * @return The kth most frequent word in the corpus to date', ' */', ' public String getKthMostFrequent (int k) {', '', ' // if we got here, then the array is all set up, so just return the kth most frequent word', ' if (k >= extractedWords.size ()) {', ' int which = extractedWords.size ();', ' for (String s : ones.navigableKeySet ()) {', ' if (which == k)', ' return s;', ' which++;', ' }', ' return null;', ' } else {', ' // If k is less than the size of the extractedWords list,', ' // return the kth most frequent word from extractedWords', ' return extractedWords.get (k).extractWord ();', ' }', ' }', '}', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class CounterTester extends TestCase {', '', ' /**', ' * File object to read words from, with buffering.', ' */', ' private FileReader file = null;', ' private BufferedReader reader = null;', '', ' /**', ' * Close file readers.', ' */', ' private void closeFiles() {', ' try {', ' if (file != null) {', ' file.close();', ' file = null;', ' }', ' if (reader != null) {', ' reader.close();', ' reader = null;', ' }', ' } catch (Exception e) {', ' System.err.println("Problem closing file");', ' System.err.println(e);', ' e.printStackTrace();', ' }', ' }', '', ' /**', ' * Close files no matter what happens in the test.', ' */', ' protected void tearDown () {', ' closeFiles();', ' }', '', ' /**', ' * Open file and set up readers.', ' *', ' * @param fileName name of file to open', ' * */', ' private void openFile(String fileName) {', ' try {', ' file = new FileReader(fileName);', ' reader = new BufferedReader(file);', ' } catch (Exception e) {', ' System.err.format("Problem opening %s file\\n", fileName);', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Read the next numWords from the file.', ' *', ' * @param counter word counter to update', ' * @param numWords number of words to read.', ' */', ' private void readWords(WordCounter counter, int numWords) {', ' try {', ' for (int i=0; i<numWords; i++) {', ' if (i % 100000 == 0)', ' System.out.print (".");', ' String word = reader.readLine();', ' if (word == null) {', ' return;', ' }', " // Insert 'word' into the counter.", ' counter.insert(word);', ' }', ' } catch (Exception e) {', ' System.err.println("Problem reading file");', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Read the next numWords from the file, mixing with queries', ' *', ' * @param counter word counter to update', ' * @param numWords number of words to read.', ' */', ' private void readWordsMixed (WordCounter counter, int numWords) {', ' try {', ' int j = 0;', ' for (int i=0; i<numWords; i++) {', ' String word = reader.readLine();', " // If 'word' is null, it means we've reached the end of the file. So, return from the method.", ' if (word == null) {', ' return;', ' }', ' counter.insert(word);', '', ' // If the current iteration number is a multiple of 10 and greater than 100,000, perform a query of the kth most frequent word.', ' if (i % 10 == 0 && i > 100000) {', ' String myStr = counter.getKthMostFrequent(j++);', ' }', '', ' // rest j once we get to 100', ' if (j == 100)', ' j = 0;', ' }', ' } catch (Exception e) {', ' System.err.println("Problem reading file");', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Check that a sequence of words starts at the "start"th most', ' * frequent word.', ' *', ' * @param counter word counter to lookup', ' * @param start frequency index to start checking at', ' * @param expected array of expected words that start at that frequency', ' */', ' private void checkExpected(WordCounter counter, int start, String [] expected) {', ' for (int i = 0; i<expected.length; i++) {', ' String actual = counter.getKthMostFrequent(start);', ' System.out.format("k: %d, expected: %s, actual: %s\\n",', ' start, expected[i], actual);', ' assertEquals(expected[i], actual);', ' start++;', ' }', ' }', '', ' /**', ' * A test method.', ' * (Replace "X" with a name describing the test. You may write as', ' * many "testSomething" methods in this class as you wish, and each', ' * one will be called when running JUnit over this class.)', ' */', ' public void testSimple() {', ' System.out.println("\\nChecking insert");', ' WordCounter counter = new WordCounter();', ' counter.insert("pizzaz");', ' // Insert the word "pizza" into the counter twice', ' counter.insert("pizza");', ' counter.insert("pizza");', ' String [] expected = {"pizza"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void testTie() {', ' System.out.println("\\nChecking tie for 2nd place");', ' WordCounter counter = new WordCounter();', ' counter.insert("panache");', ' counter.insert("pizzaz");', ' counter.insert("pizza");', ' counter.insert("zebra");', ' counter.insert("pizza");', ' counter.insert("lion");', ' counter.insert("pizzaz");', ' counter.insert("panache");', ' counter.insert("panache");', ' counter.insert("camel");', ' // order is important here', ' String [] expected = {"pizza", "pizzaz"};', ' checkExpected(counter, 1, expected);', ' }', '', '', ' public void testPastTheEnd() {', ' System.out.println("\\nChecking past the end");', ' WordCounter counter = new WordCounter();', ' counter.insert("hi");', ' counter.insert("hello");', ' counter.insert("greetings");', ' counter.insert("salutations");', ' counter.insert("hi");', ' counter.insert("welcome");', ' counter.insert("goodbye");', ' counter.insert("later");', ' counter.insert("hello");', ' counter.insert("when");', ' counter.insert("hi");', ' assertNull(counter.getKthMostFrequent(8));', ' }', '', ' public void test100Top5() {', ' System.out.println("\\nChecking top 5 of 100 words");', ' WordCounter counter = new WordCounter();', ' // Open the file "allWordsBig"', ' openFile("allWordsBig");', ' // Read the next 100 words', ' readWords(counter, 100);', ' String [] expected = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void test300Top5() {', ' System.out.println("\\nChecking top 5 of first 100 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 100);', ' String [] expected1 = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter, 0, expected1);', '', ' System.out.println("Adding 100 more words and rechecking top 5");', ' readWords(counter, 100);', ' String [] expected2 = {"edu", "cmu", "comp", "cs", "state"};', ' checkExpected(counter, 0, expected2);', '', ' System.out.println("Adding 100 more words and rechecking top 5");', ' readWords(counter, 100);', ' String [] expected3 = {"edu", "cmu", "comp", "ohio", "state"};', ' checkExpected(counter, 0, expected3);', ' }', '', ' public void test300Words14Thru19() {', ' System.out.println("\\nChecking rank 14 through 19 of 300 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' // Read the next 300 words', ' readWords(counter, 300);', ' String [] expected = {"cantaloupe", "from", "ksu", "okstate", "on", "srv"};', ' checkExpected(counter, 14, expected);', ' }', '', ' public void test300CorrectNumber() {', ' System.out.println("\\nChecking correct number of unique words in 300 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 300);', ' /* check the 122th, 123th, and 124th most frequent word in the corpus so far ', ' * and check if the result is not null.', ' */', ' assertNotNull(counter.getKthMostFrequent(122));', ' assertNotNull(counter.getKthMostFrequent(123));', ' assertNotNull(counter.getKthMostFrequent(124));', ' // check the 125th most frequent word in the corpus so far', ' // and check if the result is null.', ' assertNull(counter.getKthMostFrequent(125));', ' }', '', ' public void test300and100() {', ' System.out.println("\\nChecking top 5 of 100 and 300 words with two counters");', ' WordCounter counter1 = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter1, 300);', ' closeFiles();', '', ' WordCounter counter2 = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter2, 100);', '', ' String [] expected1 = {"edu", "cmu", "comp", "ohio", "state"};', ' checkExpected(counter1, 0, expected1);', '', ' String [] expected2 = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter2, 0, expected2);', ' }', '', ' public void testAllTop15() {', ' System.out.println("\\nChecking top 15 of all words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' // Read the next 6000000 words', ' readWords(counter, 6000000);', ' String [] expected = {"the", "edu", "to", "of", "and",', ' "in", "is", "ax", "that", "it",', ' "cmu", "for", "com", "you", "cs"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void testAllTop10000() {', ' System.out.println("\\nChecking time to get top 10000 of all words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 6000000);', '', ' for (int i=0; i<10000; i++) {', ' counter.getKthMostFrequent(i);', ' }', ' }', '', ' public void testSpeed() {', ' System.out.println("\\nMixing adding data with finding top k");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWordsMixed (counter, 6000000);', ' String [] expected = {"the", "edu", "to", "of", "and",', ' "in", "is", "ax", "that", "it",', ' "cmu", "for", "com", "you", "cs"};', ' checkExpected(counter, 0, expected);', ' }', '', '}'] | [{'reason_category': 'If Body', 'usage_line': 116}, {'reason_category': 'If Body', 'usage_line': 117}] | Class 'WordWrapper' used at line 116 is defined at line 11 and has a Long-Range dependency.
Global_Variable 'wordsIHaveSeen' used at line 116 is defined at line 93 and has a Medium-Range dependency.
Variable 'addMe' used at line 116 is defined at line 105 and has a Medium-Range dependency.
Variable 'temp' used at line 117 is defined at line 116 and has a Short-Range dependency. | {'If Body': 2} | {'Class Long-Range': 1, 'Global_Variable Medium-Range': 1, 'Variable Medium-Range': 1, 'Variable Short-Range': 1} |
infilling_java | CounterTester | 153 | 153 | ['import junit.framework.TestCase;', 'import java.io.*;', 'import java.util.HashMap;', 'import java.util.TreeMap;', 'import java.util.ArrayList;', '', '/**', ' * This silly little class wraps String, int pairs so they can be sorted.', ' * Used by the WordCounter class.', ' */', 'class WordWrapper implements Comparable <WordWrapper> {', '', ' private String myWord;', ' private int myCount;', ' private int mySlot;', '', ' /**', ' * Creates a new WordWrapper with string "XXX" and count zero.', ' */', ' public WordWrapper (String myWordIn, int myCountIn, int mySlotIn) {', ' myWord = myWordIn;', ' myCount = myCountIn;', ' mySlot = mySlotIn;', ' }', ' /**', ' * Returns a copy of the string in the WordWrapper.', ' *', ' * @return The word contained in this object. Is copied out: no aliasing.', ' */', ' public String extractWord () {', ' return new String (myWord);', ' }', '', ' /**', ' * Returns the count in this WordWrapper.', ' *', ' * @return The count contained in the object.', ' */', ' public int extractCount () {', ' return myCount;', ' }', '', ' public void incCount () {', ' myCount++;', ' }', '', ' public int getCount () {', ' return myCount;', ' }', '', ' public int getPos () {', ' return mySlot;', ' }', '', ' public void setPos (int toWhat) {', ' ', ' mySlot = toWhat;', ' }', '', ' public String toString () {', ' return myWord + " " + mySlot;', ' }', '', ' /**', ' * Comparison operator so we implement the Comparable interface.', ' *', ' * @param w The word wrapper to compare to', ' * @return a positive, zero, or negative value depending upon whether this', ' * word wrapper is less then, equal to, or greater than param w. The', ' * relationship is determied by looking at the counts.', ' */', ' public int compareTo (WordWrapper w) {', " // Check if the count of the current word (myCount) is equal to the count of the word 'w'", ' // If the counts are equal, compare the words lexicographically', ' if (w.myCount == myCount) {', ' return myWord.compareTo(w.myWord);', ' }', " // If the counts are not equal, subtract the count of the current word from the count of the word 'w'", ' return w.myCount - myCount;', ' }', '}', '', '', '/**', ' * This class is used to count occurences of words (strings) in a corpus. Used by', ' * the IndexedDocumentCollection class to find the most frequent words in the corpus.', ' */', '', 'class WordCounter {', ' ', " // this is the map that holds (for each word) the number of times we've seen it", ' // note that Integer is a wrapper for the buitin Java int type', ' private HashMap <String, WordWrapper> wordsIHaveSeen = new HashMap <String, WordWrapper> ();', ' private TreeMap <String, String> ones = new TreeMap <String, String> ();', ' ', ' // the set of words that have been extracted', ' private ArrayList<WordWrapper> extractedWords = new ArrayList <WordWrapper> ();', '', ' /**', ' * Accepts a word and increments the count of the number of times we have seen it.', ' * Note that a deep copy of the param is done (no aliasing).', ' *', ' * @param addMe The string to count', ' */', ' public void insert (String addMe) {', ' if (ones.containsKey (addMe)) {', ' ones.remove (addMe);', ' WordWrapper temp = new WordWrapper (addMe, 1, extractedWords.size ());', ' wordsIHaveSeen.put(addMe, temp);', ' extractedWords.add (temp);', ' }', '', ' // first check to see if the word is alredy in wordsIHaveSeen', ' if (wordsIHaveSeen.containsKey (addMe)) {', ' // if it is, then remove and increment its count', ' WordWrapper temp = wordsIHaveSeen.get (addMe);', ' temp.incCount ();', '', ' // find the slot that we go to in the extractedWords list', " // by sorting the 'extractedWords' list in ascending order", ' for (int i = temp.getPos () - 1; i >= 0 && ', ' extractedWords.get (i).compareTo (extractedWords.get (i + 1)) > 0; i--) {', ' temp = extractedWords.get (i + 1);', ' temp.setPos (i);', ' ', ' WordWrapper temp2 = extractedWords.get (i);', ' temp2.setPos (i + 1);', ' ', ' extractedWords.set (i + 1, temp2);', ' extractedWords.set (i, temp);', ' }', '', ' // in this case it is not there, so just add it', ' } else {', ' ones.put (addMe, addMe);', ' }', ' }', '', ' /**', ' * Returns the kth most frequent word in the corpus so far. A deep copy is returned,', ' * so no aliasing is possible. Returns null if there are not enough words.', ' *', ' * @param k Note that the most frequent word is at k = 0', ' * @return The kth most frequent word in the corpus to date', ' */', ' public String getKthMostFrequent (int k) {', '', ' // if we got here, then the array is all set up, so just return the kth most frequent word', ' if (k >= extractedWords.size ()) {', ' int which = extractedWords.size ();', ' for (String s : ones.navigableKeySet ()) {', ' if (which == k)'] | [' return s;'] | [' which++;', ' }', ' return null;', ' } else {', ' // If k is less than the size of the extractedWords list,', ' // return the kth most frequent word from extractedWords', ' return extractedWords.get (k).extractWord ();', ' }', ' }', '}', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class CounterTester extends TestCase {', '', ' /**', ' * File object to read words from, with buffering.', ' */', ' private FileReader file = null;', ' private BufferedReader reader = null;', '', ' /**', ' * Close file readers.', ' */', ' private void closeFiles() {', ' try {', ' if (file != null) {', ' file.close();', ' file = null;', ' }', ' if (reader != null) {', ' reader.close();', ' reader = null;', ' }', ' } catch (Exception e) {', ' System.err.println("Problem closing file");', ' System.err.println(e);', ' e.printStackTrace();', ' }', ' }', '', ' /**', ' * Close files no matter what happens in the test.', ' */', ' protected void tearDown () {', ' closeFiles();', ' }', '', ' /**', ' * Open file and set up readers.', ' *', ' * @param fileName name of file to open', ' * */', ' private void openFile(String fileName) {', ' try {', ' file = new FileReader(fileName);', ' reader = new BufferedReader(file);', ' } catch (Exception e) {', ' System.err.format("Problem opening %s file\\n", fileName);', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Read the next numWords from the file.', ' *', ' * @param counter word counter to update', ' * @param numWords number of words to read.', ' */', ' private void readWords(WordCounter counter, int numWords) {', ' try {', ' for (int i=0; i<numWords; i++) {', ' if (i % 100000 == 0)', ' System.out.print (".");', ' String word = reader.readLine();', ' if (word == null) {', ' return;', ' }', " // Insert 'word' into the counter.", ' counter.insert(word);', ' }', ' } catch (Exception e) {', ' System.err.println("Problem reading file");', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Read the next numWords from the file, mixing with queries', ' *', ' * @param counter word counter to update', ' * @param numWords number of words to read.', ' */', ' private void readWordsMixed (WordCounter counter, int numWords) {', ' try {', ' int j = 0;', ' for (int i=0; i<numWords; i++) {', ' String word = reader.readLine();', " // If 'word' is null, it means we've reached the end of the file. So, return from the method.", ' if (word == null) {', ' return;', ' }', ' counter.insert(word);', '', ' // If the current iteration number is a multiple of 10 and greater than 100,000, perform a query of the kth most frequent word.', ' if (i % 10 == 0 && i > 100000) {', ' String myStr = counter.getKthMostFrequent(j++);', ' }', '', ' // rest j once we get to 100', ' if (j == 100)', ' j = 0;', ' }', ' } catch (Exception e) {', ' System.err.println("Problem reading file");', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Check that a sequence of words starts at the "start"th most', ' * frequent word.', ' *', ' * @param counter word counter to lookup', ' * @param start frequency index to start checking at', ' * @param expected array of expected words that start at that frequency', ' */', ' private void checkExpected(WordCounter counter, int start, String [] expected) {', ' for (int i = 0; i<expected.length; i++) {', ' String actual = counter.getKthMostFrequent(start);', ' System.out.format("k: %d, expected: %s, actual: %s\\n",', ' start, expected[i], actual);', ' assertEquals(expected[i], actual);', ' start++;', ' }', ' }', '', ' /**', ' * A test method.', ' * (Replace "X" with a name describing the test. You may write as', ' * many "testSomething" methods in this class as you wish, and each', ' * one will be called when running JUnit over this class.)', ' */', ' public void testSimple() {', ' System.out.println("\\nChecking insert");', ' WordCounter counter = new WordCounter();', ' counter.insert("pizzaz");', ' // Insert the word "pizza" into the counter twice', ' counter.insert("pizza");', ' counter.insert("pizza");', ' String [] expected = {"pizza"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void testTie() {', ' System.out.println("\\nChecking tie for 2nd place");', ' WordCounter counter = new WordCounter();', ' counter.insert("panache");', ' counter.insert("pizzaz");', ' counter.insert("pizza");', ' counter.insert("zebra");', ' counter.insert("pizza");', ' counter.insert("lion");', ' counter.insert("pizzaz");', ' counter.insert("panache");', ' counter.insert("panache");', ' counter.insert("camel");', ' // order is important here', ' String [] expected = {"pizza", "pizzaz"};', ' checkExpected(counter, 1, expected);', ' }', '', '', ' public void testPastTheEnd() {', ' System.out.println("\\nChecking past the end");', ' WordCounter counter = new WordCounter();', ' counter.insert("hi");', ' counter.insert("hello");', ' counter.insert("greetings");', ' counter.insert("salutations");', ' counter.insert("hi");', ' counter.insert("welcome");', ' counter.insert("goodbye");', ' counter.insert("later");', ' counter.insert("hello");', ' counter.insert("when");', ' counter.insert("hi");', ' assertNull(counter.getKthMostFrequent(8));', ' }', '', ' public void test100Top5() {', ' System.out.println("\\nChecking top 5 of 100 words");', ' WordCounter counter = new WordCounter();', ' // Open the file "allWordsBig"', ' openFile("allWordsBig");', ' // Read the next 100 words', ' readWords(counter, 100);', ' String [] expected = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void test300Top5() {', ' System.out.println("\\nChecking top 5 of first 100 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 100);', ' String [] expected1 = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter, 0, expected1);', '', ' System.out.println("Adding 100 more words and rechecking top 5");', ' readWords(counter, 100);', ' String [] expected2 = {"edu", "cmu", "comp", "cs", "state"};', ' checkExpected(counter, 0, expected2);', '', ' System.out.println("Adding 100 more words and rechecking top 5");', ' readWords(counter, 100);', ' String [] expected3 = {"edu", "cmu", "comp", "ohio", "state"};', ' checkExpected(counter, 0, expected3);', ' }', '', ' public void test300Words14Thru19() {', ' System.out.println("\\nChecking rank 14 through 19 of 300 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' // Read the next 300 words', ' readWords(counter, 300);', ' String [] expected = {"cantaloupe", "from", "ksu", "okstate", "on", "srv"};', ' checkExpected(counter, 14, expected);', ' }', '', ' public void test300CorrectNumber() {', ' System.out.println("\\nChecking correct number of unique words in 300 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 300);', ' /* check the 122th, 123th, and 124th most frequent word in the corpus so far ', ' * and check if the result is not null.', ' */', ' assertNotNull(counter.getKthMostFrequent(122));', ' assertNotNull(counter.getKthMostFrequent(123));', ' assertNotNull(counter.getKthMostFrequent(124));', ' // check the 125th most frequent word in the corpus so far', ' // and check if the result is null.', ' assertNull(counter.getKthMostFrequent(125));', ' }', '', ' public void test300and100() {', ' System.out.println("\\nChecking top 5 of 100 and 300 words with two counters");', ' WordCounter counter1 = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter1, 300);', ' closeFiles();', '', ' WordCounter counter2 = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter2, 100);', '', ' String [] expected1 = {"edu", "cmu", "comp", "ohio", "state"};', ' checkExpected(counter1, 0, expected1);', '', ' String [] expected2 = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter2, 0, expected2);', ' }', '', ' public void testAllTop15() {', ' System.out.println("\\nChecking top 15 of all words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' // Read the next 6000000 words', ' readWords(counter, 6000000);', ' String [] expected = {"the", "edu", "to", "of", "and",', ' "in", "is", "ax", "that", "it",', ' "cmu", "for", "com", "you", "cs"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void testAllTop10000() {', ' System.out.println("\\nChecking time to get top 10000 of all words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 6000000);', '', ' for (int i=0; i<10000; i++) {', ' counter.getKthMostFrequent(i);', ' }', ' }', '', ' public void testSpeed() {', ' System.out.println("\\nMixing adding data with finding top k");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWordsMixed (counter, 6000000);', ' String [] expected = {"the", "edu", "to", "of", "and",', ' "in", "is", "ax", "that", "it",', ' "cmu", "for", "com", "you", "cs"};', ' checkExpected(counter, 0, expected);', ' }', '', '}'] | [{'reason_category': 'If Body', 'usage_line': 153}, {'reason_category': 'Loop Body', 'usage_line': 153}] | Variable 's' used at line 153 is defined at line 151 and has a Short-Range dependency. | {'If Body': 1, 'Loop Body': 1} | {'Variable Short-Range': 1} |
infilling_java | CounterTester | 152 | 155 | ['import junit.framework.TestCase;', 'import java.io.*;', 'import java.util.HashMap;', 'import java.util.TreeMap;', 'import java.util.ArrayList;', '', '/**', ' * This silly little class wraps String, int pairs so they can be sorted.', ' * Used by the WordCounter class.', ' */', 'class WordWrapper implements Comparable <WordWrapper> {', '', ' private String myWord;', ' private int myCount;', ' private int mySlot;', '', ' /**', ' * Creates a new WordWrapper with string "XXX" and count zero.', ' */', ' public WordWrapper (String myWordIn, int myCountIn, int mySlotIn) {', ' myWord = myWordIn;', ' myCount = myCountIn;', ' mySlot = mySlotIn;', ' }', ' /**', ' * Returns a copy of the string in the WordWrapper.', ' *', ' * @return The word contained in this object. Is copied out: no aliasing.', ' */', ' public String extractWord () {', ' return new String (myWord);', ' }', '', ' /**', ' * Returns the count in this WordWrapper.', ' *', ' * @return The count contained in the object.', ' */', ' public int extractCount () {', ' return myCount;', ' }', '', ' public void incCount () {', ' myCount++;', ' }', '', ' public int getCount () {', ' return myCount;', ' }', '', ' public int getPos () {', ' return mySlot;', ' }', '', ' public void setPos (int toWhat) {', ' ', ' mySlot = toWhat;', ' }', '', ' public String toString () {', ' return myWord + " " + mySlot;', ' }', '', ' /**', ' * Comparison operator so we implement the Comparable interface.', ' *', ' * @param w The word wrapper to compare to', ' * @return a positive, zero, or negative value depending upon whether this', ' * word wrapper is less then, equal to, or greater than param w. The', ' * relationship is determied by looking at the counts.', ' */', ' public int compareTo (WordWrapper w) {', " // Check if the count of the current word (myCount) is equal to the count of the word 'w'", ' // If the counts are equal, compare the words lexicographically', ' if (w.myCount == myCount) {', ' return myWord.compareTo(w.myWord);', ' }', " // If the counts are not equal, subtract the count of the current word from the count of the word 'w'", ' return w.myCount - myCount;', ' }', '}', '', '', '/**', ' * This class is used to count occurences of words (strings) in a corpus. Used by', ' * the IndexedDocumentCollection class to find the most frequent words in the corpus.', ' */', '', 'class WordCounter {', ' ', " // this is the map that holds (for each word) the number of times we've seen it", ' // note that Integer is a wrapper for the buitin Java int type', ' private HashMap <String, WordWrapper> wordsIHaveSeen = new HashMap <String, WordWrapper> ();', ' private TreeMap <String, String> ones = new TreeMap <String, String> ();', ' ', ' // the set of words that have been extracted', ' private ArrayList<WordWrapper> extractedWords = new ArrayList <WordWrapper> ();', '', ' /**', ' * Accepts a word and increments the count of the number of times we have seen it.', ' * Note that a deep copy of the param is done (no aliasing).', ' *', ' * @param addMe The string to count', ' */', ' public void insert (String addMe) {', ' if (ones.containsKey (addMe)) {', ' ones.remove (addMe);', ' WordWrapper temp = new WordWrapper (addMe, 1, extractedWords.size ());', ' wordsIHaveSeen.put(addMe, temp);', ' extractedWords.add (temp);', ' }', '', ' // first check to see if the word is alredy in wordsIHaveSeen', ' if (wordsIHaveSeen.containsKey (addMe)) {', ' // if it is, then remove and increment its count', ' WordWrapper temp = wordsIHaveSeen.get (addMe);', ' temp.incCount ();', '', ' // find the slot that we go to in the extractedWords list', " // by sorting the 'extractedWords' list in ascending order", ' for (int i = temp.getPos () - 1; i >= 0 && ', ' extractedWords.get (i).compareTo (extractedWords.get (i + 1)) > 0; i--) {', ' temp = extractedWords.get (i + 1);', ' temp.setPos (i);', ' ', ' WordWrapper temp2 = extractedWords.get (i);', ' temp2.setPos (i + 1);', ' ', ' extractedWords.set (i + 1, temp2);', ' extractedWords.set (i, temp);', ' }', '', ' // in this case it is not there, so just add it', ' } else {', ' ones.put (addMe, addMe);', ' }', ' }', '', ' /**', ' * Returns the kth most frequent word in the corpus so far. A deep copy is returned,', ' * so no aliasing is possible. Returns null if there are not enough words.', ' *', ' * @param k Note that the most frequent word is at k = 0', ' * @return The kth most frequent word in the corpus to date', ' */', ' public String getKthMostFrequent (int k) {', '', ' // if we got here, then the array is all set up, so just return the kth most frequent word', ' if (k >= extractedWords.size ()) {', ' int which = extractedWords.size ();', ' for (String s : ones.navigableKeySet ()) {'] | [' if (which == k)', ' return s;', ' which++;', ' }'] | [' return null;', ' } else {', ' // If k is less than the size of the extractedWords list,', ' // return the kth most frequent word from extractedWords', ' return extractedWords.get (k).extractWord ();', ' }', ' }', '}', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class CounterTester extends TestCase {', '', ' /**', ' * File object to read words from, with buffering.', ' */', ' private FileReader file = null;', ' private BufferedReader reader = null;', '', ' /**', ' * Close file readers.', ' */', ' private void closeFiles() {', ' try {', ' if (file != null) {', ' file.close();', ' file = null;', ' }', ' if (reader != null) {', ' reader.close();', ' reader = null;', ' }', ' } catch (Exception e) {', ' System.err.println("Problem closing file");', ' System.err.println(e);', ' e.printStackTrace();', ' }', ' }', '', ' /**', ' * Close files no matter what happens in the test.', ' */', ' protected void tearDown () {', ' closeFiles();', ' }', '', ' /**', ' * Open file and set up readers.', ' *', ' * @param fileName name of file to open', ' * */', ' private void openFile(String fileName) {', ' try {', ' file = new FileReader(fileName);', ' reader = new BufferedReader(file);', ' } catch (Exception e) {', ' System.err.format("Problem opening %s file\\n", fileName);', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Read the next numWords from the file.', ' *', ' * @param counter word counter to update', ' * @param numWords number of words to read.', ' */', ' private void readWords(WordCounter counter, int numWords) {', ' try {', ' for (int i=0; i<numWords; i++) {', ' if (i % 100000 == 0)', ' System.out.print (".");', ' String word = reader.readLine();', ' if (word == null) {', ' return;', ' }', " // Insert 'word' into the counter.", ' counter.insert(word);', ' }', ' } catch (Exception e) {', ' System.err.println("Problem reading file");', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Read the next numWords from the file, mixing with queries', ' *', ' * @param counter word counter to update', ' * @param numWords number of words to read.', ' */', ' private void readWordsMixed (WordCounter counter, int numWords) {', ' try {', ' int j = 0;', ' for (int i=0; i<numWords; i++) {', ' String word = reader.readLine();', " // If 'word' is null, it means we've reached the end of the file. So, return from the method.", ' if (word == null) {', ' return;', ' }', ' counter.insert(word);', '', ' // If the current iteration number is a multiple of 10 and greater than 100,000, perform a query of the kth most frequent word.', ' if (i % 10 == 0 && i > 100000) {', ' String myStr = counter.getKthMostFrequent(j++);', ' }', '', ' // rest j once we get to 100', ' if (j == 100)', ' j = 0;', ' }', ' } catch (Exception e) {', ' System.err.println("Problem reading file");', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Check that a sequence of words starts at the "start"th most', ' * frequent word.', ' *', ' * @param counter word counter to lookup', ' * @param start frequency index to start checking at', ' * @param expected array of expected words that start at that frequency', ' */', ' private void checkExpected(WordCounter counter, int start, String [] expected) {', ' for (int i = 0; i<expected.length; i++) {', ' String actual = counter.getKthMostFrequent(start);', ' System.out.format("k: %d, expected: %s, actual: %s\\n",', ' start, expected[i], actual);', ' assertEquals(expected[i], actual);', ' start++;', ' }', ' }', '', ' /**', ' * A test method.', ' * (Replace "X" with a name describing the test. You may write as', ' * many "testSomething" methods in this class as you wish, and each', ' * one will be called when running JUnit over this class.)', ' */', ' public void testSimple() {', ' System.out.println("\\nChecking insert");', ' WordCounter counter = new WordCounter();', ' counter.insert("pizzaz");', ' // Insert the word "pizza" into the counter twice', ' counter.insert("pizza");', ' counter.insert("pizza");', ' String [] expected = {"pizza"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void testTie() {', ' System.out.println("\\nChecking tie for 2nd place");', ' WordCounter counter = new WordCounter();', ' counter.insert("panache");', ' counter.insert("pizzaz");', ' counter.insert("pizza");', ' counter.insert("zebra");', ' counter.insert("pizza");', ' counter.insert("lion");', ' counter.insert("pizzaz");', ' counter.insert("panache");', ' counter.insert("panache");', ' counter.insert("camel");', ' // order is important here', ' String [] expected = {"pizza", "pizzaz"};', ' checkExpected(counter, 1, expected);', ' }', '', '', ' public void testPastTheEnd() {', ' System.out.println("\\nChecking past the end");', ' WordCounter counter = new WordCounter();', ' counter.insert("hi");', ' counter.insert("hello");', ' counter.insert("greetings");', ' counter.insert("salutations");', ' counter.insert("hi");', ' counter.insert("welcome");', ' counter.insert("goodbye");', ' counter.insert("later");', ' counter.insert("hello");', ' counter.insert("when");', ' counter.insert("hi");', ' assertNull(counter.getKthMostFrequent(8));', ' }', '', ' public void test100Top5() {', ' System.out.println("\\nChecking top 5 of 100 words");', ' WordCounter counter = new WordCounter();', ' // Open the file "allWordsBig"', ' openFile("allWordsBig");', ' // Read the next 100 words', ' readWords(counter, 100);', ' String [] expected = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void test300Top5() {', ' System.out.println("\\nChecking top 5 of first 100 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 100);', ' String [] expected1 = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter, 0, expected1);', '', ' System.out.println("Adding 100 more words and rechecking top 5");', ' readWords(counter, 100);', ' String [] expected2 = {"edu", "cmu", "comp", "cs", "state"};', ' checkExpected(counter, 0, expected2);', '', ' System.out.println("Adding 100 more words and rechecking top 5");', ' readWords(counter, 100);', ' String [] expected3 = {"edu", "cmu", "comp", "ohio", "state"};', ' checkExpected(counter, 0, expected3);', ' }', '', ' public void test300Words14Thru19() {', ' System.out.println("\\nChecking rank 14 through 19 of 300 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' // Read the next 300 words', ' readWords(counter, 300);', ' String [] expected = {"cantaloupe", "from", "ksu", "okstate", "on", "srv"};', ' checkExpected(counter, 14, expected);', ' }', '', ' public void test300CorrectNumber() {', ' System.out.println("\\nChecking correct number of unique words in 300 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 300);', ' /* check the 122th, 123th, and 124th most frequent word in the corpus so far ', ' * and check if the result is not null.', ' */', ' assertNotNull(counter.getKthMostFrequent(122));', ' assertNotNull(counter.getKthMostFrequent(123));', ' assertNotNull(counter.getKthMostFrequent(124));', ' // check the 125th most frequent word in the corpus so far', ' // and check if the result is null.', ' assertNull(counter.getKthMostFrequent(125));', ' }', '', ' public void test300and100() {', ' System.out.println("\\nChecking top 5 of 100 and 300 words with two counters");', ' WordCounter counter1 = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter1, 300);', ' closeFiles();', '', ' WordCounter counter2 = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter2, 100);', '', ' String [] expected1 = {"edu", "cmu", "comp", "ohio", "state"};', ' checkExpected(counter1, 0, expected1);', '', ' String [] expected2 = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter2, 0, expected2);', ' }', '', ' public void testAllTop15() {', ' System.out.println("\\nChecking top 15 of all words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' // Read the next 6000000 words', ' readWords(counter, 6000000);', ' String [] expected = {"the", "edu", "to", "of", "and",', ' "in", "is", "ax", "that", "it",', ' "cmu", "for", "com", "you", "cs"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void testAllTop10000() {', ' System.out.println("\\nChecking time to get top 10000 of all words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 6000000);', '', ' for (int i=0; i<10000; i++) {', ' counter.getKthMostFrequent(i);', ' }', ' }', '', ' public void testSpeed() {', ' System.out.println("\\nMixing adding data with finding top k");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWordsMixed (counter, 6000000);', ' String [] expected = {"the", "edu", "to", "of", "and",', ' "in", "is", "ax", "that", "it",', ' "cmu", "for", "com", "you", "cs"};', ' checkExpected(counter, 0, expected);', ' }', '', '}'] | [{'reason_category': 'Loop Body', 'usage_line': 152}, {'reason_category': 'If Body', 'usage_line': 152}, {'reason_category': 'If Condition', 'usage_line': 152}, {'reason_category': 'If Body', 'usage_line': 153}, {'reason_category': 'Loop Body', 'usage_line': 153}, {'reason_category': 'If Body', 'usage_line': 154}, {'reason_category': 'Loop Body', 'usage_line': 154}, {'reason_category': 'If Body', 'usage_line': 155}, {'reason_category': 'Loop Body', 'usage_line': 155}] | Variable 'which' used at line 152 is defined at line 150 and has a Short-Range dependency.
Variable 'k' used at line 152 is defined at line 146 and has a Short-Range dependency.
Variable 's' used at line 153 is defined at line 151 and has a Short-Range dependency.
Variable 'which' used at line 154 is defined at line 150 and has a Short-Range dependency. | {'Loop Body': 4, 'If Body': 4, 'If Condition': 1} | {'Variable Short-Range': 4} |
infilling_java | CounterTester | 150 | 156 | ['import junit.framework.TestCase;', 'import java.io.*;', 'import java.util.HashMap;', 'import java.util.TreeMap;', 'import java.util.ArrayList;', '', '/**', ' * This silly little class wraps String, int pairs so they can be sorted.', ' * Used by the WordCounter class.', ' */', 'class WordWrapper implements Comparable <WordWrapper> {', '', ' private String myWord;', ' private int myCount;', ' private int mySlot;', '', ' /**', ' * Creates a new WordWrapper with string "XXX" and count zero.', ' */', ' public WordWrapper (String myWordIn, int myCountIn, int mySlotIn) {', ' myWord = myWordIn;', ' myCount = myCountIn;', ' mySlot = mySlotIn;', ' }', ' /**', ' * Returns a copy of the string in the WordWrapper.', ' *', ' * @return The word contained in this object. Is copied out: no aliasing.', ' */', ' public String extractWord () {', ' return new String (myWord);', ' }', '', ' /**', ' * Returns the count in this WordWrapper.', ' *', ' * @return The count contained in the object.', ' */', ' public int extractCount () {', ' return myCount;', ' }', '', ' public void incCount () {', ' myCount++;', ' }', '', ' public int getCount () {', ' return myCount;', ' }', '', ' public int getPos () {', ' return mySlot;', ' }', '', ' public void setPos (int toWhat) {', ' ', ' mySlot = toWhat;', ' }', '', ' public String toString () {', ' return myWord + " " + mySlot;', ' }', '', ' /**', ' * Comparison operator so we implement the Comparable interface.', ' *', ' * @param w The word wrapper to compare to', ' * @return a positive, zero, or negative value depending upon whether this', ' * word wrapper is less then, equal to, or greater than param w. The', ' * relationship is determied by looking at the counts.', ' */', ' public int compareTo (WordWrapper w) {', " // Check if the count of the current word (myCount) is equal to the count of the word 'w'", ' // If the counts are equal, compare the words lexicographically', ' if (w.myCount == myCount) {', ' return myWord.compareTo(w.myWord);', ' }', " // If the counts are not equal, subtract the count of the current word from the count of the word 'w'", ' return w.myCount - myCount;', ' }', '}', '', '', '/**', ' * This class is used to count occurences of words (strings) in a corpus. Used by', ' * the IndexedDocumentCollection class to find the most frequent words in the corpus.', ' */', '', 'class WordCounter {', ' ', " // this is the map that holds (for each word) the number of times we've seen it", ' // note that Integer is a wrapper for the buitin Java int type', ' private HashMap <String, WordWrapper> wordsIHaveSeen = new HashMap <String, WordWrapper> ();', ' private TreeMap <String, String> ones = new TreeMap <String, String> ();', ' ', ' // the set of words that have been extracted', ' private ArrayList<WordWrapper> extractedWords = new ArrayList <WordWrapper> ();', '', ' /**', ' * Accepts a word and increments the count of the number of times we have seen it.', ' * Note that a deep copy of the param is done (no aliasing).', ' *', ' * @param addMe The string to count', ' */', ' public void insert (String addMe) {', ' if (ones.containsKey (addMe)) {', ' ones.remove (addMe);', ' WordWrapper temp = new WordWrapper (addMe, 1, extractedWords.size ());', ' wordsIHaveSeen.put(addMe, temp);', ' extractedWords.add (temp);', ' }', '', ' // first check to see if the word is alredy in wordsIHaveSeen', ' if (wordsIHaveSeen.containsKey (addMe)) {', ' // if it is, then remove and increment its count', ' WordWrapper temp = wordsIHaveSeen.get (addMe);', ' temp.incCount ();', '', ' // find the slot that we go to in the extractedWords list', " // by sorting the 'extractedWords' list in ascending order", ' for (int i = temp.getPos () - 1; i >= 0 && ', ' extractedWords.get (i).compareTo (extractedWords.get (i + 1)) > 0; i--) {', ' temp = extractedWords.get (i + 1);', ' temp.setPos (i);', ' ', ' WordWrapper temp2 = extractedWords.get (i);', ' temp2.setPos (i + 1);', ' ', ' extractedWords.set (i + 1, temp2);', ' extractedWords.set (i, temp);', ' }', '', ' // in this case it is not there, so just add it', ' } else {', ' ones.put (addMe, addMe);', ' }', ' }', '', ' /**', ' * Returns the kth most frequent word in the corpus so far. A deep copy is returned,', ' * so no aliasing is possible. Returns null if there are not enough words.', ' *', ' * @param k Note that the most frequent word is at k = 0', ' * @return The kth most frequent word in the corpus to date', ' */', ' public String getKthMostFrequent (int k) {', '', ' // if we got here, then the array is all set up, so just return the kth most frequent word', ' if (k >= extractedWords.size ()) {'] | [' int which = extractedWords.size ();', ' for (String s : ones.navigableKeySet ()) {', ' if (which == k)', ' return s;', ' which++;', ' }', ' return null;'] | [' } else {', ' // If k is less than the size of the extractedWords list,', ' // return the kth most frequent word from extractedWords', ' return extractedWords.get (k).extractWord ();', ' }', ' }', '}', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class CounterTester extends TestCase {', '', ' /**', ' * File object to read words from, with buffering.', ' */', ' private FileReader file = null;', ' private BufferedReader reader = null;', '', ' /**', ' * Close file readers.', ' */', ' private void closeFiles() {', ' try {', ' if (file != null) {', ' file.close();', ' file = null;', ' }', ' if (reader != null) {', ' reader.close();', ' reader = null;', ' }', ' } catch (Exception e) {', ' System.err.println("Problem closing file");', ' System.err.println(e);', ' e.printStackTrace();', ' }', ' }', '', ' /**', ' * Close files no matter what happens in the test.', ' */', ' protected void tearDown () {', ' closeFiles();', ' }', '', ' /**', ' * Open file and set up readers.', ' *', ' * @param fileName name of file to open', ' * */', ' private void openFile(String fileName) {', ' try {', ' file = new FileReader(fileName);', ' reader = new BufferedReader(file);', ' } catch (Exception e) {', ' System.err.format("Problem opening %s file\\n", fileName);', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Read the next numWords from the file.', ' *', ' * @param counter word counter to update', ' * @param numWords number of words to read.', ' */', ' private void readWords(WordCounter counter, int numWords) {', ' try {', ' for (int i=0; i<numWords; i++) {', ' if (i % 100000 == 0)', ' System.out.print (".");', ' String word = reader.readLine();', ' if (word == null) {', ' return;', ' }', " // Insert 'word' into the counter.", ' counter.insert(word);', ' }', ' } catch (Exception e) {', ' System.err.println("Problem reading file");', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Read the next numWords from the file, mixing with queries', ' *', ' * @param counter word counter to update', ' * @param numWords number of words to read.', ' */', ' private void readWordsMixed (WordCounter counter, int numWords) {', ' try {', ' int j = 0;', ' for (int i=0; i<numWords; i++) {', ' String word = reader.readLine();', " // If 'word' is null, it means we've reached the end of the file. So, return from the method.", ' if (word == null) {', ' return;', ' }', ' counter.insert(word);', '', ' // If the current iteration number is a multiple of 10 and greater than 100,000, perform a query of the kth most frequent word.', ' if (i % 10 == 0 && i > 100000) {', ' String myStr = counter.getKthMostFrequent(j++);', ' }', '', ' // rest j once we get to 100', ' if (j == 100)', ' j = 0;', ' }', ' } catch (Exception e) {', ' System.err.println("Problem reading file");', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Check that a sequence of words starts at the "start"th most', ' * frequent word.', ' *', ' * @param counter word counter to lookup', ' * @param start frequency index to start checking at', ' * @param expected array of expected words that start at that frequency', ' */', ' private void checkExpected(WordCounter counter, int start, String [] expected) {', ' for (int i = 0; i<expected.length; i++) {', ' String actual = counter.getKthMostFrequent(start);', ' System.out.format("k: %d, expected: %s, actual: %s\\n",', ' start, expected[i], actual);', ' assertEquals(expected[i], actual);', ' start++;', ' }', ' }', '', ' /**', ' * A test method.', ' * (Replace "X" with a name describing the test. You may write as', ' * many "testSomething" methods in this class as you wish, and each', ' * one will be called when running JUnit over this class.)', ' */', ' public void testSimple() {', ' System.out.println("\\nChecking insert");', ' WordCounter counter = new WordCounter();', ' counter.insert("pizzaz");', ' // Insert the word "pizza" into the counter twice', ' counter.insert("pizza");', ' counter.insert("pizza");', ' String [] expected = {"pizza"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void testTie() {', ' System.out.println("\\nChecking tie for 2nd place");', ' WordCounter counter = new WordCounter();', ' counter.insert("panache");', ' counter.insert("pizzaz");', ' counter.insert("pizza");', ' counter.insert("zebra");', ' counter.insert("pizza");', ' counter.insert("lion");', ' counter.insert("pizzaz");', ' counter.insert("panache");', ' counter.insert("panache");', ' counter.insert("camel");', ' // order is important here', ' String [] expected = {"pizza", "pizzaz"};', ' checkExpected(counter, 1, expected);', ' }', '', '', ' public void testPastTheEnd() {', ' System.out.println("\\nChecking past the end");', ' WordCounter counter = new WordCounter();', ' counter.insert("hi");', ' counter.insert("hello");', ' counter.insert("greetings");', ' counter.insert("salutations");', ' counter.insert("hi");', ' counter.insert("welcome");', ' counter.insert("goodbye");', ' counter.insert("later");', ' counter.insert("hello");', ' counter.insert("when");', ' counter.insert("hi");', ' assertNull(counter.getKthMostFrequent(8));', ' }', '', ' public void test100Top5() {', ' System.out.println("\\nChecking top 5 of 100 words");', ' WordCounter counter = new WordCounter();', ' // Open the file "allWordsBig"', ' openFile("allWordsBig");', ' // Read the next 100 words', ' readWords(counter, 100);', ' String [] expected = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void test300Top5() {', ' System.out.println("\\nChecking top 5 of first 100 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 100);', ' String [] expected1 = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter, 0, expected1);', '', ' System.out.println("Adding 100 more words and rechecking top 5");', ' readWords(counter, 100);', ' String [] expected2 = {"edu", "cmu", "comp", "cs", "state"};', ' checkExpected(counter, 0, expected2);', '', ' System.out.println("Adding 100 more words and rechecking top 5");', ' readWords(counter, 100);', ' String [] expected3 = {"edu", "cmu", "comp", "ohio", "state"};', ' checkExpected(counter, 0, expected3);', ' }', '', ' public void test300Words14Thru19() {', ' System.out.println("\\nChecking rank 14 through 19 of 300 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' // Read the next 300 words', ' readWords(counter, 300);', ' String [] expected = {"cantaloupe", "from", "ksu", "okstate", "on", "srv"};', ' checkExpected(counter, 14, expected);', ' }', '', ' public void test300CorrectNumber() {', ' System.out.println("\\nChecking correct number of unique words in 300 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 300);', ' /* check the 122th, 123th, and 124th most frequent word in the corpus so far ', ' * and check if the result is not null.', ' */', ' assertNotNull(counter.getKthMostFrequent(122));', ' assertNotNull(counter.getKthMostFrequent(123));', ' assertNotNull(counter.getKthMostFrequent(124));', ' // check the 125th most frequent word in the corpus so far', ' // and check if the result is null.', ' assertNull(counter.getKthMostFrequent(125));', ' }', '', ' public void test300and100() {', ' System.out.println("\\nChecking top 5 of 100 and 300 words with two counters");', ' WordCounter counter1 = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter1, 300);', ' closeFiles();', '', ' WordCounter counter2 = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter2, 100);', '', ' String [] expected1 = {"edu", "cmu", "comp", "ohio", "state"};', ' checkExpected(counter1, 0, expected1);', '', ' String [] expected2 = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter2, 0, expected2);', ' }', '', ' public void testAllTop15() {', ' System.out.println("\\nChecking top 15 of all words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' // Read the next 6000000 words', ' readWords(counter, 6000000);', ' String [] expected = {"the", "edu", "to", "of", "and",', ' "in", "is", "ax", "that", "it",', ' "cmu", "for", "com", "you", "cs"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void testAllTop10000() {', ' System.out.println("\\nChecking time to get top 10000 of all words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 6000000);', '', ' for (int i=0; i<10000; i++) {', ' counter.getKthMostFrequent(i);', ' }', ' }', '', ' public void testSpeed() {', ' System.out.println("\\nMixing adding data with finding top k");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWordsMixed (counter, 6000000);', ' String [] expected = {"the", "edu", "to", "of", "and",', ' "in", "is", "ax", "that", "it",', ' "cmu", "for", "com", "you", "cs"};', ' checkExpected(counter, 0, expected);', ' }', '', '}'] | [{'reason_category': 'If Body', 'usage_line': 150}, {'reason_category': 'If Body', 'usage_line': 151}, {'reason_category': 'Define Stop Criteria', 'usage_line': 151}, {'reason_category': 'Loop Body', 'usage_line': 152}, {'reason_category': 'If Body', 'usage_line': 152}, {'reason_category': 'If Condition', 'usage_line': 152}, {'reason_category': 'If Body', 'usage_line': 153}, {'reason_category': 'Loop Body', 'usage_line': 153}, {'reason_category': 'If Body', 'usage_line': 154}, {'reason_category': 'Loop Body', 'usage_line': 154}, {'reason_category': 'If Body', 'usage_line': 155}, {'reason_category': 'Loop Body', 'usage_line': 155}, {'reason_category': 'If Body', 'usage_line': 156}] | Global_Variable 'extractedWords' used at line 150 is defined at line 97 and has a Long-Range dependency.
Global_Variable 'ones' used at line 151 is defined at line 94 and has a Long-Range dependency.
Variable 'which' used at line 152 is defined at line 150 and has a Short-Range dependency.
Variable 'k' used at line 152 is defined at line 146 and has a Short-Range dependency.
Variable 's' used at line 153 is defined at line 151 and has a Short-Range dependency.
Variable 'which' used at line 154 is defined at line 150 and has a Short-Range dependency. | {'If Body': 7, 'Define Stop Criteria': 1, 'Loop Body': 4, 'If Condition': 1} | {'Global_Variable Long-Range': 2, 'Variable Short-Range': 4} |
infilling_java | CounterTester | 160 | 161 | ['import junit.framework.TestCase;', 'import java.io.*;', 'import java.util.HashMap;', 'import java.util.TreeMap;', 'import java.util.ArrayList;', '', '/**', ' * This silly little class wraps String, int pairs so they can be sorted.', ' * Used by the WordCounter class.', ' */', 'class WordWrapper implements Comparable <WordWrapper> {', '', ' private String myWord;', ' private int myCount;', ' private int mySlot;', '', ' /**', ' * Creates a new WordWrapper with string "XXX" and count zero.', ' */', ' public WordWrapper (String myWordIn, int myCountIn, int mySlotIn) {', ' myWord = myWordIn;', ' myCount = myCountIn;', ' mySlot = mySlotIn;', ' }', ' /**', ' * Returns a copy of the string in the WordWrapper.', ' *', ' * @return The word contained in this object. Is copied out: no aliasing.', ' */', ' public String extractWord () {', ' return new String (myWord);', ' }', '', ' /**', ' * Returns the count in this WordWrapper.', ' *', ' * @return The count contained in the object.', ' */', ' public int extractCount () {', ' return myCount;', ' }', '', ' public void incCount () {', ' myCount++;', ' }', '', ' public int getCount () {', ' return myCount;', ' }', '', ' public int getPos () {', ' return mySlot;', ' }', '', ' public void setPos (int toWhat) {', ' ', ' mySlot = toWhat;', ' }', '', ' public String toString () {', ' return myWord + " " + mySlot;', ' }', '', ' /**', ' * Comparison operator so we implement the Comparable interface.', ' *', ' * @param w The word wrapper to compare to', ' * @return a positive, zero, or negative value depending upon whether this', ' * word wrapper is less then, equal to, or greater than param w. The', ' * relationship is determied by looking at the counts.', ' */', ' public int compareTo (WordWrapper w) {', " // Check if the count of the current word (myCount) is equal to the count of the word 'w'", ' // If the counts are equal, compare the words lexicographically', ' if (w.myCount == myCount) {', ' return myWord.compareTo(w.myWord);', ' }', " // If the counts are not equal, subtract the count of the current word from the count of the word 'w'", ' return w.myCount - myCount;', ' }', '}', '', '', '/**', ' * This class is used to count occurences of words (strings) in a corpus. Used by', ' * the IndexedDocumentCollection class to find the most frequent words in the corpus.', ' */', '', 'class WordCounter {', ' ', " // this is the map that holds (for each word) the number of times we've seen it", ' // note that Integer is a wrapper for the buitin Java int type', ' private HashMap <String, WordWrapper> wordsIHaveSeen = new HashMap <String, WordWrapper> ();', ' private TreeMap <String, String> ones = new TreeMap <String, String> ();', ' ', ' // the set of words that have been extracted', ' private ArrayList<WordWrapper> extractedWords = new ArrayList <WordWrapper> ();', '', ' /**', ' * Accepts a word and increments the count of the number of times we have seen it.', ' * Note that a deep copy of the param is done (no aliasing).', ' *', ' * @param addMe The string to count', ' */', ' public void insert (String addMe) {', ' if (ones.containsKey (addMe)) {', ' ones.remove (addMe);', ' WordWrapper temp = new WordWrapper (addMe, 1, extractedWords.size ());', ' wordsIHaveSeen.put(addMe, temp);', ' extractedWords.add (temp);', ' }', '', ' // first check to see if the word is alredy in wordsIHaveSeen', ' if (wordsIHaveSeen.containsKey (addMe)) {', ' // if it is, then remove and increment its count', ' WordWrapper temp = wordsIHaveSeen.get (addMe);', ' temp.incCount ();', '', ' // find the slot that we go to in the extractedWords list', " // by sorting the 'extractedWords' list in ascending order", ' for (int i = temp.getPos () - 1; i >= 0 && ', ' extractedWords.get (i).compareTo (extractedWords.get (i + 1)) > 0; i--) {', ' temp = extractedWords.get (i + 1);', ' temp.setPos (i);', ' ', ' WordWrapper temp2 = extractedWords.get (i);', ' temp2.setPos (i + 1);', ' ', ' extractedWords.set (i + 1, temp2);', ' extractedWords.set (i, temp);', ' }', '', ' // in this case it is not there, so just add it', ' } else {', ' ones.put (addMe, addMe);', ' }', ' }', '', ' /**', ' * Returns the kth most frequent word in the corpus so far. A deep copy is returned,', ' * so no aliasing is possible. Returns null if there are not enough words.', ' *', ' * @param k Note that the most frequent word is at k = 0', ' * @return The kth most frequent word in the corpus to date', ' */', ' public String getKthMostFrequent (int k) {', '', ' // if we got here, then the array is all set up, so just return the kth most frequent word', ' if (k >= extractedWords.size ()) {', ' int which = extractedWords.size ();', ' for (String s : ones.navigableKeySet ()) {', ' if (which == k)', ' return s;', ' which++;', ' }', ' return null;', ' } else {', ' // If k is less than the size of the extractedWords list,', ' // return the kth most frequent word from extractedWords'] | [' return extractedWords.get (k).extractWord ();', ' }'] | [' }', '}', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class CounterTester extends TestCase {', '', ' /**', ' * File object to read words from, with buffering.', ' */', ' private FileReader file = null;', ' private BufferedReader reader = null;', '', ' /**', ' * Close file readers.', ' */', ' private void closeFiles() {', ' try {', ' if (file != null) {', ' file.close();', ' file = null;', ' }', ' if (reader != null) {', ' reader.close();', ' reader = null;', ' }', ' } catch (Exception e) {', ' System.err.println("Problem closing file");', ' System.err.println(e);', ' e.printStackTrace();', ' }', ' }', '', ' /**', ' * Close files no matter what happens in the test.', ' */', ' protected void tearDown () {', ' closeFiles();', ' }', '', ' /**', ' * Open file and set up readers.', ' *', ' * @param fileName name of file to open', ' * */', ' private void openFile(String fileName) {', ' try {', ' file = new FileReader(fileName);', ' reader = new BufferedReader(file);', ' } catch (Exception e) {', ' System.err.format("Problem opening %s file\\n", fileName);', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Read the next numWords from the file.', ' *', ' * @param counter word counter to update', ' * @param numWords number of words to read.', ' */', ' private void readWords(WordCounter counter, int numWords) {', ' try {', ' for (int i=0; i<numWords; i++) {', ' if (i % 100000 == 0)', ' System.out.print (".");', ' String word = reader.readLine();', ' if (word == null) {', ' return;', ' }', " // Insert 'word' into the counter.", ' counter.insert(word);', ' }', ' } catch (Exception e) {', ' System.err.println("Problem reading file");', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Read the next numWords from the file, mixing with queries', ' *', ' * @param counter word counter to update', ' * @param numWords number of words to read.', ' */', ' private void readWordsMixed (WordCounter counter, int numWords) {', ' try {', ' int j = 0;', ' for (int i=0; i<numWords; i++) {', ' String word = reader.readLine();', " // If 'word' is null, it means we've reached the end of the file. So, return from the method.", ' if (word == null) {', ' return;', ' }', ' counter.insert(word);', '', ' // If the current iteration number is a multiple of 10 and greater than 100,000, perform a query of the kth most frequent word.', ' if (i % 10 == 0 && i > 100000) {', ' String myStr = counter.getKthMostFrequent(j++);', ' }', '', ' // rest j once we get to 100', ' if (j == 100)', ' j = 0;', ' }', ' } catch (Exception e) {', ' System.err.println("Problem reading file");', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Check that a sequence of words starts at the "start"th most', ' * frequent word.', ' *', ' * @param counter word counter to lookup', ' * @param start frequency index to start checking at', ' * @param expected array of expected words that start at that frequency', ' */', ' private void checkExpected(WordCounter counter, int start, String [] expected) {', ' for (int i = 0; i<expected.length; i++) {', ' String actual = counter.getKthMostFrequent(start);', ' System.out.format("k: %d, expected: %s, actual: %s\\n",', ' start, expected[i], actual);', ' assertEquals(expected[i], actual);', ' start++;', ' }', ' }', '', ' /**', ' * A test method.', ' * (Replace "X" with a name describing the test. You may write as', ' * many "testSomething" methods in this class as you wish, and each', ' * one will be called when running JUnit over this class.)', ' */', ' public void testSimple() {', ' System.out.println("\\nChecking insert");', ' WordCounter counter = new WordCounter();', ' counter.insert("pizzaz");', ' // Insert the word "pizza" into the counter twice', ' counter.insert("pizza");', ' counter.insert("pizza");', ' String [] expected = {"pizza"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void testTie() {', ' System.out.println("\\nChecking tie for 2nd place");', ' WordCounter counter = new WordCounter();', ' counter.insert("panache");', ' counter.insert("pizzaz");', ' counter.insert("pizza");', ' counter.insert("zebra");', ' counter.insert("pizza");', ' counter.insert("lion");', ' counter.insert("pizzaz");', ' counter.insert("panache");', ' counter.insert("panache");', ' counter.insert("camel");', ' // order is important here', ' String [] expected = {"pizza", "pizzaz"};', ' checkExpected(counter, 1, expected);', ' }', '', '', ' public void testPastTheEnd() {', ' System.out.println("\\nChecking past the end");', ' WordCounter counter = new WordCounter();', ' counter.insert("hi");', ' counter.insert("hello");', ' counter.insert("greetings");', ' counter.insert("salutations");', ' counter.insert("hi");', ' counter.insert("welcome");', ' counter.insert("goodbye");', ' counter.insert("later");', ' counter.insert("hello");', ' counter.insert("when");', ' counter.insert("hi");', ' assertNull(counter.getKthMostFrequent(8));', ' }', '', ' public void test100Top5() {', ' System.out.println("\\nChecking top 5 of 100 words");', ' WordCounter counter = new WordCounter();', ' // Open the file "allWordsBig"', ' openFile("allWordsBig");', ' // Read the next 100 words', ' readWords(counter, 100);', ' String [] expected = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void test300Top5() {', ' System.out.println("\\nChecking top 5 of first 100 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 100);', ' String [] expected1 = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter, 0, expected1);', '', ' System.out.println("Adding 100 more words and rechecking top 5");', ' readWords(counter, 100);', ' String [] expected2 = {"edu", "cmu", "comp", "cs", "state"};', ' checkExpected(counter, 0, expected2);', '', ' System.out.println("Adding 100 more words and rechecking top 5");', ' readWords(counter, 100);', ' String [] expected3 = {"edu", "cmu", "comp", "ohio", "state"};', ' checkExpected(counter, 0, expected3);', ' }', '', ' public void test300Words14Thru19() {', ' System.out.println("\\nChecking rank 14 through 19 of 300 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' // Read the next 300 words', ' readWords(counter, 300);', ' String [] expected = {"cantaloupe", "from", "ksu", "okstate", "on", "srv"};', ' checkExpected(counter, 14, expected);', ' }', '', ' public void test300CorrectNumber() {', ' System.out.println("\\nChecking correct number of unique words in 300 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 300);', ' /* check the 122th, 123th, and 124th most frequent word in the corpus so far ', ' * and check if the result is not null.', ' */', ' assertNotNull(counter.getKthMostFrequent(122));', ' assertNotNull(counter.getKthMostFrequent(123));', ' assertNotNull(counter.getKthMostFrequent(124));', ' // check the 125th most frequent word in the corpus so far', ' // and check if the result is null.', ' assertNull(counter.getKthMostFrequent(125));', ' }', '', ' public void test300and100() {', ' System.out.println("\\nChecking top 5 of 100 and 300 words with two counters");', ' WordCounter counter1 = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter1, 300);', ' closeFiles();', '', ' WordCounter counter2 = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter2, 100);', '', ' String [] expected1 = {"edu", "cmu", "comp", "ohio", "state"};', ' checkExpected(counter1, 0, expected1);', '', ' String [] expected2 = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter2, 0, expected2);', ' }', '', ' public void testAllTop15() {', ' System.out.println("\\nChecking top 15 of all words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' // Read the next 6000000 words', ' readWords(counter, 6000000);', ' String [] expected = {"the", "edu", "to", "of", "and",', ' "in", "is", "ax", "that", "it",', ' "cmu", "for", "com", "you", "cs"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void testAllTop10000() {', ' System.out.println("\\nChecking time to get top 10000 of all words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 6000000);', '', ' for (int i=0; i<10000; i++) {', ' counter.getKthMostFrequent(i);', ' }', ' }', '', ' public void testSpeed() {', ' System.out.println("\\nMixing adding data with finding top k");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWordsMixed (counter, 6000000);', ' String [] expected = {"the", "edu", "to", "of", "and",', ' "in", "is", "ax", "that", "it",', ' "cmu", "for", "com", "you", "cs"};', ' checkExpected(counter, 0, expected);', ' }', '', '}'] | [{'reason_category': 'Else Reasoning', 'usage_line': 160}, {'reason_category': 'Else Reasoning', 'usage_line': 161}] | Global_Variable 'extractedWords' used at line 160 is defined at line 97 and has a Long-Range dependency.
Variable 'k' used at line 160 is defined at line 146 and has a Medium-Range dependency.
Function 'extractWord' used at line 160 is defined at line 30 and has a Long-Range dependency. | {'Else Reasoning': 2} | {'Global_Variable Long-Range': 1, 'Variable Medium-Range': 1, 'Function Long-Range': 1} |
infilling_java | CounterTester | 183 | 185 | ['import junit.framework.TestCase;', 'import java.io.*;', 'import java.util.HashMap;', 'import java.util.TreeMap;', 'import java.util.ArrayList;', '', '/**', ' * This silly little class wraps String, int pairs so they can be sorted.', ' * Used by the WordCounter class.', ' */', 'class WordWrapper implements Comparable <WordWrapper> {', '', ' private String myWord;', ' private int myCount;', ' private int mySlot;', '', ' /**', ' * Creates a new WordWrapper with string "XXX" and count zero.', ' */', ' public WordWrapper (String myWordIn, int myCountIn, int mySlotIn) {', ' myWord = myWordIn;', ' myCount = myCountIn;', ' mySlot = mySlotIn;', ' }', ' /**', ' * Returns a copy of the string in the WordWrapper.', ' *', ' * @return The word contained in this object. Is copied out: no aliasing.', ' */', ' public String extractWord () {', ' return new String (myWord);', ' }', '', ' /**', ' * Returns the count in this WordWrapper.', ' *', ' * @return The count contained in the object.', ' */', ' public int extractCount () {', ' return myCount;', ' }', '', ' public void incCount () {', ' myCount++;', ' }', '', ' public int getCount () {', ' return myCount;', ' }', '', ' public int getPos () {', ' return mySlot;', ' }', '', ' public void setPos (int toWhat) {', ' ', ' mySlot = toWhat;', ' }', '', ' public String toString () {', ' return myWord + " " + mySlot;', ' }', '', ' /**', ' * Comparison operator so we implement the Comparable interface.', ' *', ' * @param w The word wrapper to compare to', ' * @return a positive, zero, or negative value depending upon whether this', ' * word wrapper is less then, equal to, or greater than param w. The', ' * relationship is determied by looking at the counts.', ' */', ' public int compareTo (WordWrapper w) {', " // Check if the count of the current word (myCount) is equal to the count of the word 'w'", ' // If the counts are equal, compare the words lexicographically', ' if (w.myCount == myCount) {', ' return myWord.compareTo(w.myWord);', ' }', " // If the counts are not equal, subtract the count of the current word from the count of the word 'w'", ' return w.myCount - myCount;', ' }', '}', '', '', '/**', ' * This class is used to count occurences of words (strings) in a corpus. Used by', ' * the IndexedDocumentCollection class to find the most frequent words in the corpus.', ' */', '', 'class WordCounter {', ' ', " // this is the map that holds (for each word) the number of times we've seen it", ' // note that Integer is a wrapper for the buitin Java int type', ' private HashMap <String, WordWrapper> wordsIHaveSeen = new HashMap <String, WordWrapper> ();', ' private TreeMap <String, String> ones = new TreeMap <String, String> ();', ' ', ' // the set of words that have been extracted', ' private ArrayList<WordWrapper> extractedWords = new ArrayList <WordWrapper> ();', '', ' /**', ' * Accepts a word and increments the count of the number of times we have seen it.', ' * Note that a deep copy of the param is done (no aliasing).', ' *', ' * @param addMe The string to count', ' */', ' public void insert (String addMe) {', ' if (ones.containsKey (addMe)) {', ' ones.remove (addMe);', ' WordWrapper temp = new WordWrapper (addMe, 1, extractedWords.size ());', ' wordsIHaveSeen.put(addMe, temp);', ' extractedWords.add (temp);', ' }', '', ' // first check to see if the word is alredy in wordsIHaveSeen', ' if (wordsIHaveSeen.containsKey (addMe)) {', ' // if it is, then remove and increment its count', ' WordWrapper temp = wordsIHaveSeen.get (addMe);', ' temp.incCount ();', '', ' // find the slot that we go to in the extractedWords list', " // by sorting the 'extractedWords' list in ascending order", ' for (int i = temp.getPos () - 1; i >= 0 && ', ' extractedWords.get (i).compareTo (extractedWords.get (i + 1)) > 0; i--) {', ' temp = extractedWords.get (i + 1);', ' temp.setPos (i);', ' ', ' WordWrapper temp2 = extractedWords.get (i);', ' temp2.setPos (i + 1);', ' ', ' extractedWords.set (i + 1, temp2);', ' extractedWords.set (i, temp);', ' }', '', ' // in this case it is not there, so just add it', ' } else {', ' ones.put (addMe, addMe);', ' }', ' }', '', ' /**', ' * Returns the kth most frequent word in the corpus so far. A deep copy is returned,', ' * so no aliasing is possible. Returns null if there are not enough words.', ' *', ' * @param k Note that the most frequent word is at k = 0', ' * @return The kth most frequent word in the corpus to date', ' */', ' public String getKthMostFrequent (int k) {', '', ' // if we got here, then the array is all set up, so just return the kth most frequent word', ' if (k >= extractedWords.size ()) {', ' int which = extractedWords.size ();', ' for (String s : ones.navigableKeySet ()) {', ' if (which == k)', ' return s;', ' which++;', ' }', ' return null;', ' } else {', ' // If k is less than the size of the extractedWords list,', ' // return the kth most frequent word from extractedWords', ' return extractedWords.get (k).extractWord ();', ' }', ' }', '}', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class CounterTester extends TestCase {', '', ' /**', ' * File object to read words from, with buffering.', ' */', ' private FileReader file = null;', ' private BufferedReader reader = null;', '', ' /**', ' * Close file readers.', ' */', ' private void closeFiles() {', ' try {', ' if (file != null) {'] | [' file.close();', ' file = null;', ' }'] | [' if (reader != null) {', ' reader.close();', ' reader = null;', ' }', ' } catch (Exception e) {', ' System.err.println("Problem closing file");', ' System.err.println(e);', ' e.printStackTrace();', ' }', ' }', '', ' /**', ' * Close files no matter what happens in the test.', ' */', ' protected void tearDown () {', ' closeFiles();', ' }', '', ' /**', ' * Open file and set up readers.', ' *', ' * @param fileName name of file to open', ' * */', ' private void openFile(String fileName) {', ' try {', ' file = new FileReader(fileName);', ' reader = new BufferedReader(file);', ' } catch (Exception e) {', ' System.err.format("Problem opening %s file\\n", fileName);', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Read the next numWords from the file.', ' *', ' * @param counter word counter to update', ' * @param numWords number of words to read.', ' */', ' private void readWords(WordCounter counter, int numWords) {', ' try {', ' for (int i=0; i<numWords; i++) {', ' if (i % 100000 == 0)', ' System.out.print (".");', ' String word = reader.readLine();', ' if (word == null) {', ' return;', ' }', " // Insert 'word' into the counter.", ' counter.insert(word);', ' }', ' } catch (Exception e) {', ' System.err.println("Problem reading file");', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Read the next numWords from the file, mixing with queries', ' *', ' * @param counter word counter to update', ' * @param numWords number of words to read.', ' */', ' private void readWordsMixed (WordCounter counter, int numWords) {', ' try {', ' int j = 0;', ' for (int i=0; i<numWords; i++) {', ' String word = reader.readLine();', " // If 'word' is null, it means we've reached the end of the file. So, return from the method.", ' if (word == null) {', ' return;', ' }', ' counter.insert(word);', '', ' // If the current iteration number is a multiple of 10 and greater than 100,000, perform a query of the kth most frequent word.', ' if (i % 10 == 0 && i > 100000) {', ' String myStr = counter.getKthMostFrequent(j++);', ' }', '', ' // rest j once we get to 100', ' if (j == 100)', ' j = 0;', ' }', ' } catch (Exception e) {', ' System.err.println("Problem reading file");', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Check that a sequence of words starts at the "start"th most', ' * frequent word.', ' *', ' * @param counter word counter to lookup', ' * @param start frequency index to start checking at', ' * @param expected array of expected words that start at that frequency', ' */', ' private void checkExpected(WordCounter counter, int start, String [] expected) {', ' for (int i = 0; i<expected.length; i++) {', ' String actual = counter.getKthMostFrequent(start);', ' System.out.format("k: %d, expected: %s, actual: %s\\n",', ' start, expected[i], actual);', ' assertEquals(expected[i], actual);', ' start++;', ' }', ' }', '', ' /**', ' * A test method.', ' * (Replace "X" with a name describing the test. You may write as', ' * many "testSomething" methods in this class as you wish, and each', ' * one will be called when running JUnit over this class.)', ' */', ' public void testSimple() {', ' System.out.println("\\nChecking insert");', ' WordCounter counter = new WordCounter();', ' counter.insert("pizzaz");', ' // Insert the word "pizza" into the counter twice', ' counter.insert("pizza");', ' counter.insert("pizza");', ' String [] expected = {"pizza"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void testTie() {', ' System.out.println("\\nChecking tie for 2nd place");', ' WordCounter counter = new WordCounter();', ' counter.insert("panache");', ' counter.insert("pizzaz");', ' counter.insert("pizza");', ' counter.insert("zebra");', ' counter.insert("pizza");', ' counter.insert("lion");', ' counter.insert("pizzaz");', ' counter.insert("panache");', ' counter.insert("panache");', ' counter.insert("camel");', ' // order is important here', ' String [] expected = {"pizza", "pizzaz"};', ' checkExpected(counter, 1, expected);', ' }', '', '', ' public void testPastTheEnd() {', ' System.out.println("\\nChecking past the end");', ' WordCounter counter = new WordCounter();', ' counter.insert("hi");', ' counter.insert("hello");', ' counter.insert("greetings");', ' counter.insert("salutations");', ' counter.insert("hi");', ' counter.insert("welcome");', ' counter.insert("goodbye");', ' counter.insert("later");', ' counter.insert("hello");', ' counter.insert("when");', ' counter.insert("hi");', ' assertNull(counter.getKthMostFrequent(8));', ' }', '', ' public void test100Top5() {', ' System.out.println("\\nChecking top 5 of 100 words");', ' WordCounter counter = new WordCounter();', ' // Open the file "allWordsBig"', ' openFile("allWordsBig");', ' // Read the next 100 words', ' readWords(counter, 100);', ' String [] expected = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void test300Top5() {', ' System.out.println("\\nChecking top 5 of first 100 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 100);', ' String [] expected1 = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter, 0, expected1);', '', ' System.out.println("Adding 100 more words and rechecking top 5");', ' readWords(counter, 100);', ' String [] expected2 = {"edu", "cmu", "comp", "cs", "state"};', ' checkExpected(counter, 0, expected2);', '', ' System.out.println("Adding 100 more words and rechecking top 5");', ' readWords(counter, 100);', ' String [] expected3 = {"edu", "cmu", "comp", "ohio", "state"};', ' checkExpected(counter, 0, expected3);', ' }', '', ' public void test300Words14Thru19() {', ' System.out.println("\\nChecking rank 14 through 19 of 300 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' // Read the next 300 words', ' readWords(counter, 300);', ' String [] expected = {"cantaloupe", "from", "ksu", "okstate", "on", "srv"};', ' checkExpected(counter, 14, expected);', ' }', '', ' public void test300CorrectNumber() {', ' System.out.println("\\nChecking correct number of unique words in 300 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 300);', ' /* check the 122th, 123th, and 124th most frequent word in the corpus so far ', ' * and check if the result is not null.', ' */', ' assertNotNull(counter.getKthMostFrequent(122));', ' assertNotNull(counter.getKthMostFrequent(123));', ' assertNotNull(counter.getKthMostFrequent(124));', ' // check the 125th most frequent word in the corpus so far', ' // and check if the result is null.', ' assertNull(counter.getKthMostFrequent(125));', ' }', '', ' public void test300and100() {', ' System.out.println("\\nChecking top 5 of 100 and 300 words with two counters");', ' WordCounter counter1 = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter1, 300);', ' closeFiles();', '', ' WordCounter counter2 = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter2, 100);', '', ' String [] expected1 = {"edu", "cmu", "comp", "ohio", "state"};', ' checkExpected(counter1, 0, expected1);', '', ' String [] expected2 = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter2, 0, expected2);', ' }', '', ' public void testAllTop15() {', ' System.out.println("\\nChecking top 15 of all words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' // Read the next 6000000 words', ' readWords(counter, 6000000);', ' String [] expected = {"the", "edu", "to", "of", "and",', ' "in", "is", "ax", "that", "it",', ' "cmu", "for", "com", "you", "cs"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void testAllTop10000() {', ' System.out.println("\\nChecking time to get top 10000 of all words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 6000000);', '', ' for (int i=0; i<10000; i++) {', ' counter.getKthMostFrequent(i);', ' }', ' }', '', ' public void testSpeed() {', ' System.out.println("\\nMixing adding data with finding top k");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWordsMixed (counter, 6000000);', ' String [] expected = {"the", "edu", "to", "of", "and",', ' "in", "is", "ax", "that", "it",', ' "cmu", "for", "com", "you", "cs"};', ' checkExpected(counter, 0, expected);', ' }', '', '}'] | [{'reason_category': 'If Body', 'usage_line': 183}, {'reason_category': 'If Body', 'usage_line': 184}, {'reason_category': 'If Body', 'usage_line': 185}] | Global_Variable 'file' used at line 183 is defined at line 174 and has a Short-Range dependency.
Global_Variable 'file' used at line 184 is defined at line 174 and has a Short-Range dependency. | {'If Body': 3} | {'Global_Variable Short-Range': 2} |
infilling_java | CounterTester | 187 | 189 | ['import junit.framework.TestCase;', 'import java.io.*;', 'import java.util.HashMap;', 'import java.util.TreeMap;', 'import java.util.ArrayList;', '', '/**', ' * This silly little class wraps String, int pairs so they can be sorted.', ' * Used by the WordCounter class.', ' */', 'class WordWrapper implements Comparable <WordWrapper> {', '', ' private String myWord;', ' private int myCount;', ' private int mySlot;', '', ' /**', ' * Creates a new WordWrapper with string "XXX" and count zero.', ' */', ' public WordWrapper (String myWordIn, int myCountIn, int mySlotIn) {', ' myWord = myWordIn;', ' myCount = myCountIn;', ' mySlot = mySlotIn;', ' }', ' /**', ' * Returns a copy of the string in the WordWrapper.', ' *', ' * @return The word contained in this object. Is copied out: no aliasing.', ' */', ' public String extractWord () {', ' return new String (myWord);', ' }', '', ' /**', ' * Returns the count in this WordWrapper.', ' *', ' * @return The count contained in the object.', ' */', ' public int extractCount () {', ' return myCount;', ' }', '', ' public void incCount () {', ' myCount++;', ' }', '', ' public int getCount () {', ' return myCount;', ' }', '', ' public int getPos () {', ' return mySlot;', ' }', '', ' public void setPos (int toWhat) {', ' ', ' mySlot = toWhat;', ' }', '', ' public String toString () {', ' return myWord + " " + mySlot;', ' }', '', ' /**', ' * Comparison operator so we implement the Comparable interface.', ' *', ' * @param w The word wrapper to compare to', ' * @return a positive, zero, or negative value depending upon whether this', ' * word wrapper is less then, equal to, or greater than param w. The', ' * relationship is determied by looking at the counts.', ' */', ' public int compareTo (WordWrapper w) {', " // Check if the count of the current word (myCount) is equal to the count of the word 'w'", ' // If the counts are equal, compare the words lexicographically', ' if (w.myCount == myCount) {', ' return myWord.compareTo(w.myWord);', ' }', " // If the counts are not equal, subtract the count of the current word from the count of the word 'w'", ' return w.myCount - myCount;', ' }', '}', '', '', '/**', ' * This class is used to count occurences of words (strings) in a corpus. Used by', ' * the IndexedDocumentCollection class to find the most frequent words in the corpus.', ' */', '', 'class WordCounter {', ' ', " // this is the map that holds (for each word) the number of times we've seen it", ' // note that Integer is a wrapper for the buitin Java int type', ' private HashMap <String, WordWrapper> wordsIHaveSeen = new HashMap <String, WordWrapper> ();', ' private TreeMap <String, String> ones = new TreeMap <String, String> ();', ' ', ' // the set of words that have been extracted', ' private ArrayList<WordWrapper> extractedWords = new ArrayList <WordWrapper> ();', '', ' /**', ' * Accepts a word and increments the count of the number of times we have seen it.', ' * Note that a deep copy of the param is done (no aliasing).', ' *', ' * @param addMe The string to count', ' */', ' public void insert (String addMe) {', ' if (ones.containsKey (addMe)) {', ' ones.remove (addMe);', ' WordWrapper temp = new WordWrapper (addMe, 1, extractedWords.size ());', ' wordsIHaveSeen.put(addMe, temp);', ' extractedWords.add (temp);', ' }', '', ' // first check to see if the word is alredy in wordsIHaveSeen', ' if (wordsIHaveSeen.containsKey (addMe)) {', ' // if it is, then remove and increment its count', ' WordWrapper temp = wordsIHaveSeen.get (addMe);', ' temp.incCount ();', '', ' // find the slot that we go to in the extractedWords list', " // by sorting the 'extractedWords' list in ascending order", ' for (int i = temp.getPos () - 1; i >= 0 && ', ' extractedWords.get (i).compareTo (extractedWords.get (i + 1)) > 0; i--) {', ' temp = extractedWords.get (i + 1);', ' temp.setPos (i);', ' ', ' WordWrapper temp2 = extractedWords.get (i);', ' temp2.setPos (i + 1);', ' ', ' extractedWords.set (i + 1, temp2);', ' extractedWords.set (i, temp);', ' }', '', ' // in this case it is not there, so just add it', ' } else {', ' ones.put (addMe, addMe);', ' }', ' }', '', ' /**', ' * Returns the kth most frequent word in the corpus so far. A deep copy is returned,', ' * so no aliasing is possible. Returns null if there are not enough words.', ' *', ' * @param k Note that the most frequent word is at k = 0', ' * @return The kth most frequent word in the corpus to date', ' */', ' public String getKthMostFrequent (int k) {', '', ' // if we got here, then the array is all set up, so just return the kth most frequent word', ' if (k >= extractedWords.size ()) {', ' int which = extractedWords.size ();', ' for (String s : ones.navigableKeySet ()) {', ' if (which == k)', ' return s;', ' which++;', ' }', ' return null;', ' } else {', ' // If k is less than the size of the extractedWords list,', ' // return the kth most frequent word from extractedWords', ' return extractedWords.get (k).extractWord ();', ' }', ' }', '}', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class CounterTester extends TestCase {', '', ' /**', ' * File object to read words from, with buffering.', ' */', ' private FileReader file = null;', ' private BufferedReader reader = null;', '', ' /**', ' * Close file readers.', ' */', ' private void closeFiles() {', ' try {', ' if (file != null) {', ' file.close();', ' file = null;', ' }', ' if (reader != null) {'] | [' reader.close();', ' reader = null;', ' }'] | [' } catch (Exception e) {', ' System.err.println("Problem closing file");', ' System.err.println(e);', ' e.printStackTrace();', ' }', ' }', '', ' /**', ' * Close files no matter what happens in the test.', ' */', ' protected void tearDown () {', ' closeFiles();', ' }', '', ' /**', ' * Open file and set up readers.', ' *', ' * @param fileName name of file to open', ' * */', ' private void openFile(String fileName) {', ' try {', ' file = new FileReader(fileName);', ' reader = new BufferedReader(file);', ' } catch (Exception e) {', ' System.err.format("Problem opening %s file\\n", fileName);', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Read the next numWords from the file.', ' *', ' * @param counter word counter to update', ' * @param numWords number of words to read.', ' */', ' private void readWords(WordCounter counter, int numWords) {', ' try {', ' for (int i=0; i<numWords; i++) {', ' if (i % 100000 == 0)', ' System.out.print (".");', ' String word = reader.readLine();', ' if (word == null) {', ' return;', ' }', " // Insert 'word' into the counter.", ' counter.insert(word);', ' }', ' } catch (Exception e) {', ' System.err.println("Problem reading file");', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Read the next numWords from the file, mixing with queries', ' *', ' * @param counter word counter to update', ' * @param numWords number of words to read.', ' */', ' private void readWordsMixed (WordCounter counter, int numWords) {', ' try {', ' int j = 0;', ' for (int i=0; i<numWords; i++) {', ' String word = reader.readLine();', " // If 'word' is null, it means we've reached the end of the file. So, return from the method.", ' if (word == null) {', ' return;', ' }', ' counter.insert(word);', '', ' // If the current iteration number is a multiple of 10 and greater than 100,000, perform a query of the kth most frequent word.', ' if (i % 10 == 0 && i > 100000) {', ' String myStr = counter.getKthMostFrequent(j++);', ' }', '', ' // rest j once we get to 100', ' if (j == 100)', ' j = 0;', ' }', ' } catch (Exception e) {', ' System.err.println("Problem reading file");', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Check that a sequence of words starts at the "start"th most', ' * frequent word.', ' *', ' * @param counter word counter to lookup', ' * @param start frequency index to start checking at', ' * @param expected array of expected words that start at that frequency', ' */', ' private void checkExpected(WordCounter counter, int start, String [] expected) {', ' for (int i = 0; i<expected.length; i++) {', ' String actual = counter.getKthMostFrequent(start);', ' System.out.format("k: %d, expected: %s, actual: %s\\n",', ' start, expected[i], actual);', ' assertEquals(expected[i], actual);', ' start++;', ' }', ' }', '', ' /**', ' * A test method.', ' * (Replace "X" with a name describing the test. You may write as', ' * many "testSomething" methods in this class as you wish, and each', ' * one will be called when running JUnit over this class.)', ' */', ' public void testSimple() {', ' System.out.println("\\nChecking insert");', ' WordCounter counter = new WordCounter();', ' counter.insert("pizzaz");', ' // Insert the word "pizza" into the counter twice', ' counter.insert("pizza");', ' counter.insert("pizza");', ' String [] expected = {"pizza"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void testTie() {', ' System.out.println("\\nChecking tie for 2nd place");', ' WordCounter counter = new WordCounter();', ' counter.insert("panache");', ' counter.insert("pizzaz");', ' counter.insert("pizza");', ' counter.insert("zebra");', ' counter.insert("pizza");', ' counter.insert("lion");', ' counter.insert("pizzaz");', ' counter.insert("panache");', ' counter.insert("panache");', ' counter.insert("camel");', ' // order is important here', ' String [] expected = {"pizza", "pizzaz"};', ' checkExpected(counter, 1, expected);', ' }', '', '', ' public void testPastTheEnd() {', ' System.out.println("\\nChecking past the end");', ' WordCounter counter = new WordCounter();', ' counter.insert("hi");', ' counter.insert("hello");', ' counter.insert("greetings");', ' counter.insert("salutations");', ' counter.insert("hi");', ' counter.insert("welcome");', ' counter.insert("goodbye");', ' counter.insert("later");', ' counter.insert("hello");', ' counter.insert("when");', ' counter.insert("hi");', ' assertNull(counter.getKthMostFrequent(8));', ' }', '', ' public void test100Top5() {', ' System.out.println("\\nChecking top 5 of 100 words");', ' WordCounter counter = new WordCounter();', ' // Open the file "allWordsBig"', ' openFile("allWordsBig");', ' // Read the next 100 words', ' readWords(counter, 100);', ' String [] expected = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void test300Top5() {', ' System.out.println("\\nChecking top 5 of first 100 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 100);', ' String [] expected1 = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter, 0, expected1);', '', ' System.out.println("Adding 100 more words and rechecking top 5");', ' readWords(counter, 100);', ' String [] expected2 = {"edu", "cmu", "comp", "cs", "state"};', ' checkExpected(counter, 0, expected2);', '', ' System.out.println("Adding 100 more words and rechecking top 5");', ' readWords(counter, 100);', ' String [] expected3 = {"edu", "cmu", "comp", "ohio", "state"};', ' checkExpected(counter, 0, expected3);', ' }', '', ' public void test300Words14Thru19() {', ' System.out.println("\\nChecking rank 14 through 19 of 300 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' // Read the next 300 words', ' readWords(counter, 300);', ' String [] expected = {"cantaloupe", "from", "ksu", "okstate", "on", "srv"};', ' checkExpected(counter, 14, expected);', ' }', '', ' public void test300CorrectNumber() {', ' System.out.println("\\nChecking correct number of unique words in 300 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 300);', ' /* check the 122th, 123th, and 124th most frequent word in the corpus so far ', ' * and check if the result is not null.', ' */', ' assertNotNull(counter.getKthMostFrequent(122));', ' assertNotNull(counter.getKthMostFrequent(123));', ' assertNotNull(counter.getKthMostFrequent(124));', ' // check the 125th most frequent word in the corpus so far', ' // and check if the result is null.', ' assertNull(counter.getKthMostFrequent(125));', ' }', '', ' public void test300and100() {', ' System.out.println("\\nChecking top 5 of 100 and 300 words with two counters");', ' WordCounter counter1 = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter1, 300);', ' closeFiles();', '', ' WordCounter counter2 = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter2, 100);', '', ' String [] expected1 = {"edu", "cmu", "comp", "ohio", "state"};', ' checkExpected(counter1, 0, expected1);', '', ' String [] expected2 = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter2, 0, expected2);', ' }', '', ' public void testAllTop15() {', ' System.out.println("\\nChecking top 15 of all words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' // Read the next 6000000 words', ' readWords(counter, 6000000);', ' String [] expected = {"the", "edu", "to", "of", "and",', ' "in", "is", "ax", "that", "it",', ' "cmu", "for", "com", "you", "cs"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void testAllTop10000() {', ' System.out.println("\\nChecking time to get top 10000 of all words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 6000000);', '', ' for (int i=0; i<10000; i++) {', ' counter.getKthMostFrequent(i);', ' }', ' }', '', ' public void testSpeed() {', ' System.out.println("\\nMixing adding data with finding top k");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWordsMixed (counter, 6000000);', ' String [] expected = {"the", "edu", "to", "of", "and",', ' "in", "is", "ax", "that", "it",', ' "cmu", "for", "com", "you", "cs"};', ' checkExpected(counter, 0, expected);', ' }', '', '}'] | [{'reason_category': 'If Body', 'usage_line': 187}, {'reason_category': 'If Body', 'usage_line': 188}, {'reason_category': 'If Body', 'usage_line': 189}] | Global_Variable 'reader' used at line 187 is defined at line 175 and has a Medium-Range dependency.
Global_Variable 'reader' used at line 188 is defined at line 175 and has a Medium-Range dependency. | {'If Body': 3} | {'Global_Variable Medium-Range': 2} |
infilling_java | CounterTester | 182 | 189 | ['import junit.framework.TestCase;', 'import java.io.*;', 'import java.util.HashMap;', 'import java.util.TreeMap;', 'import java.util.ArrayList;', '', '/**', ' * This silly little class wraps String, int pairs so they can be sorted.', ' * Used by the WordCounter class.', ' */', 'class WordWrapper implements Comparable <WordWrapper> {', '', ' private String myWord;', ' private int myCount;', ' private int mySlot;', '', ' /**', ' * Creates a new WordWrapper with string "XXX" and count zero.', ' */', ' public WordWrapper (String myWordIn, int myCountIn, int mySlotIn) {', ' myWord = myWordIn;', ' myCount = myCountIn;', ' mySlot = mySlotIn;', ' }', ' /**', ' * Returns a copy of the string in the WordWrapper.', ' *', ' * @return The word contained in this object. Is copied out: no aliasing.', ' */', ' public String extractWord () {', ' return new String (myWord);', ' }', '', ' /**', ' * Returns the count in this WordWrapper.', ' *', ' * @return The count contained in the object.', ' */', ' public int extractCount () {', ' return myCount;', ' }', '', ' public void incCount () {', ' myCount++;', ' }', '', ' public int getCount () {', ' return myCount;', ' }', '', ' public int getPos () {', ' return mySlot;', ' }', '', ' public void setPos (int toWhat) {', ' ', ' mySlot = toWhat;', ' }', '', ' public String toString () {', ' return myWord + " " + mySlot;', ' }', '', ' /**', ' * Comparison operator so we implement the Comparable interface.', ' *', ' * @param w The word wrapper to compare to', ' * @return a positive, zero, or negative value depending upon whether this', ' * word wrapper is less then, equal to, or greater than param w. The', ' * relationship is determied by looking at the counts.', ' */', ' public int compareTo (WordWrapper w) {', " // Check if the count of the current word (myCount) is equal to the count of the word 'w'", ' // If the counts are equal, compare the words lexicographically', ' if (w.myCount == myCount) {', ' return myWord.compareTo(w.myWord);', ' }', " // If the counts are not equal, subtract the count of the current word from the count of the word 'w'", ' return w.myCount - myCount;', ' }', '}', '', '', '/**', ' * This class is used to count occurences of words (strings) in a corpus. Used by', ' * the IndexedDocumentCollection class to find the most frequent words in the corpus.', ' */', '', 'class WordCounter {', ' ', " // this is the map that holds (for each word) the number of times we've seen it", ' // note that Integer is a wrapper for the buitin Java int type', ' private HashMap <String, WordWrapper> wordsIHaveSeen = new HashMap <String, WordWrapper> ();', ' private TreeMap <String, String> ones = new TreeMap <String, String> ();', ' ', ' // the set of words that have been extracted', ' private ArrayList<WordWrapper> extractedWords = new ArrayList <WordWrapper> ();', '', ' /**', ' * Accepts a word and increments the count of the number of times we have seen it.', ' * Note that a deep copy of the param is done (no aliasing).', ' *', ' * @param addMe The string to count', ' */', ' public void insert (String addMe) {', ' if (ones.containsKey (addMe)) {', ' ones.remove (addMe);', ' WordWrapper temp = new WordWrapper (addMe, 1, extractedWords.size ());', ' wordsIHaveSeen.put(addMe, temp);', ' extractedWords.add (temp);', ' }', '', ' // first check to see if the word is alredy in wordsIHaveSeen', ' if (wordsIHaveSeen.containsKey (addMe)) {', ' // if it is, then remove and increment its count', ' WordWrapper temp = wordsIHaveSeen.get (addMe);', ' temp.incCount ();', '', ' // find the slot that we go to in the extractedWords list', " // by sorting the 'extractedWords' list in ascending order", ' for (int i = temp.getPos () - 1; i >= 0 && ', ' extractedWords.get (i).compareTo (extractedWords.get (i + 1)) > 0; i--) {', ' temp = extractedWords.get (i + 1);', ' temp.setPos (i);', ' ', ' WordWrapper temp2 = extractedWords.get (i);', ' temp2.setPos (i + 1);', ' ', ' extractedWords.set (i + 1, temp2);', ' extractedWords.set (i, temp);', ' }', '', ' // in this case it is not there, so just add it', ' } else {', ' ones.put (addMe, addMe);', ' }', ' }', '', ' /**', ' * Returns the kth most frequent word in the corpus so far. A deep copy is returned,', ' * so no aliasing is possible. Returns null if there are not enough words.', ' *', ' * @param k Note that the most frequent word is at k = 0', ' * @return The kth most frequent word in the corpus to date', ' */', ' public String getKthMostFrequent (int k) {', '', ' // if we got here, then the array is all set up, so just return the kth most frequent word', ' if (k >= extractedWords.size ()) {', ' int which = extractedWords.size ();', ' for (String s : ones.navigableKeySet ()) {', ' if (which == k)', ' return s;', ' which++;', ' }', ' return null;', ' } else {', ' // If k is less than the size of the extractedWords list,', ' // return the kth most frequent word from extractedWords', ' return extractedWords.get (k).extractWord ();', ' }', ' }', '}', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class CounterTester extends TestCase {', '', ' /**', ' * File object to read words from, with buffering.', ' */', ' private FileReader file = null;', ' private BufferedReader reader = null;', '', ' /**', ' * Close file readers.', ' */', ' private void closeFiles() {', ' try {'] | [' if (file != null) {', ' file.close();', ' file = null;', ' }', ' if (reader != null) {', ' reader.close();', ' reader = null;', ' }'] | [' } catch (Exception e) {', ' System.err.println("Problem closing file");', ' System.err.println(e);', ' e.printStackTrace();', ' }', ' }', '', ' /**', ' * Close files no matter what happens in the test.', ' */', ' protected void tearDown () {', ' closeFiles();', ' }', '', ' /**', ' * Open file and set up readers.', ' *', ' * @param fileName name of file to open', ' * */', ' private void openFile(String fileName) {', ' try {', ' file = new FileReader(fileName);', ' reader = new BufferedReader(file);', ' } catch (Exception e) {', ' System.err.format("Problem opening %s file\\n", fileName);', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Read the next numWords from the file.', ' *', ' * @param counter word counter to update', ' * @param numWords number of words to read.', ' */', ' private void readWords(WordCounter counter, int numWords) {', ' try {', ' for (int i=0; i<numWords; i++) {', ' if (i % 100000 == 0)', ' System.out.print (".");', ' String word = reader.readLine();', ' if (word == null) {', ' return;', ' }', " // Insert 'word' into the counter.", ' counter.insert(word);', ' }', ' } catch (Exception e) {', ' System.err.println("Problem reading file");', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Read the next numWords from the file, mixing with queries', ' *', ' * @param counter word counter to update', ' * @param numWords number of words to read.', ' */', ' private void readWordsMixed (WordCounter counter, int numWords) {', ' try {', ' int j = 0;', ' for (int i=0; i<numWords; i++) {', ' String word = reader.readLine();', " // If 'word' is null, it means we've reached the end of the file. So, return from the method.", ' if (word == null) {', ' return;', ' }', ' counter.insert(word);', '', ' // If the current iteration number is a multiple of 10 and greater than 100,000, perform a query of the kth most frequent word.', ' if (i % 10 == 0 && i > 100000) {', ' String myStr = counter.getKthMostFrequent(j++);', ' }', '', ' // rest j once we get to 100', ' if (j == 100)', ' j = 0;', ' }', ' } catch (Exception e) {', ' System.err.println("Problem reading file");', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Check that a sequence of words starts at the "start"th most', ' * frequent word.', ' *', ' * @param counter word counter to lookup', ' * @param start frequency index to start checking at', ' * @param expected array of expected words that start at that frequency', ' */', ' private void checkExpected(WordCounter counter, int start, String [] expected) {', ' for (int i = 0; i<expected.length; i++) {', ' String actual = counter.getKthMostFrequent(start);', ' System.out.format("k: %d, expected: %s, actual: %s\\n",', ' start, expected[i], actual);', ' assertEquals(expected[i], actual);', ' start++;', ' }', ' }', '', ' /**', ' * A test method.', ' * (Replace "X" with a name describing the test. You may write as', ' * many "testSomething" methods in this class as you wish, and each', ' * one will be called when running JUnit over this class.)', ' */', ' public void testSimple() {', ' System.out.println("\\nChecking insert");', ' WordCounter counter = new WordCounter();', ' counter.insert("pizzaz");', ' // Insert the word "pizza" into the counter twice', ' counter.insert("pizza");', ' counter.insert("pizza");', ' String [] expected = {"pizza"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void testTie() {', ' System.out.println("\\nChecking tie for 2nd place");', ' WordCounter counter = new WordCounter();', ' counter.insert("panache");', ' counter.insert("pizzaz");', ' counter.insert("pizza");', ' counter.insert("zebra");', ' counter.insert("pizza");', ' counter.insert("lion");', ' counter.insert("pizzaz");', ' counter.insert("panache");', ' counter.insert("panache");', ' counter.insert("camel");', ' // order is important here', ' String [] expected = {"pizza", "pizzaz"};', ' checkExpected(counter, 1, expected);', ' }', '', '', ' public void testPastTheEnd() {', ' System.out.println("\\nChecking past the end");', ' WordCounter counter = new WordCounter();', ' counter.insert("hi");', ' counter.insert("hello");', ' counter.insert("greetings");', ' counter.insert("salutations");', ' counter.insert("hi");', ' counter.insert("welcome");', ' counter.insert("goodbye");', ' counter.insert("later");', ' counter.insert("hello");', ' counter.insert("when");', ' counter.insert("hi");', ' assertNull(counter.getKthMostFrequent(8));', ' }', '', ' public void test100Top5() {', ' System.out.println("\\nChecking top 5 of 100 words");', ' WordCounter counter = new WordCounter();', ' // Open the file "allWordsBig"', ' openFile("allWordsBig");', ' // Read the next 100 words', ' readWords(counter, 100);', ' String [] expected = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void test300Top5() {', ' System.out.println("\\nChecking top 5 of first 100 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 100);', ' String [] expected1 = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter, 0, expected1);', '', ' System.out.println("Adding 100 more words and rechecking top 5");', ' readWords(counter, 100);', ' String [] expected2 = {"edu", "cmu", "comp", "cs", "state"};', ' checkExpected(counter, 0, expected2);', '', ' System.out.println("Adding 100 more words and rechecking top 5");', ' readWords(counter, 100);', ' String [] expected3 = {"edu", "cmu", "comp", "ohio", "state"};', ' checkExpected(counter, 0, expected3);', ' }', '', ' public void test300Words14Thru19() {', ' System.out.println("\\nChecking rank 14 through 19 of 300 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' // Read the next 300 words', ' readWords(counter, 300);', ' String [] expected = {"cantaloupe", "from", "ksu", "okstate", "on", "srv"};', ' checkExpected(counter, 14, expected);', ' }', '', ' public void test300CorrectNumber() {', ' System.out.println("\\nChecking correct number of unique words in 300 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 300);', ' /* check the 122th, 123th, and 124th most frequent word in the corpus so far ', ' * and check if the result is not null.', ' */', ' assertNotNull(counter.getKthMostFrequent(122));', ' assertNotNull(counter.getKthMostFrequent(123));', ' assertNotNull(counter.getKthMostFrequent(124));', ' // check the 125th most frequent word in the corpus so far', ' // and check if the result is null.', ' assertNull(counter.getKthMostFrequent(125));', ' }', '', ' public void test300and100() {', ' System.out.println("\\nChecking top 5 of 100 and 300 words with two counters");', ' WordCounter counter1 = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter1, 300);', ' closeFiles();', '', ' WordCounter counter2 = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter2, 100);', '', ' String [] expected1 = {"edu", "cmu", "comp", "ohio", "state"};', ' checkExpected(counter1, 0, expected1);', '', ' String [] expected2 = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter2, 0, expected2);', ' }', '', ' public void testAllTop15() {', ' System.out.println("\\nChecking top 15 of all words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' // Read the next 6000000 words', ' readWords(counter, 6000000);', ' String [] expected = {"the", "edu", "to", "of", "and",', ' "in", "is", "ax", "that", "it",', ' "cmu", "for", "com", "you", "cs"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void testAllTop10000() {', ' System.out.println("\\nChecking time to get top 10000 of all words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 6000000);', '', ' for (int i=0; i<10000; i++) {', ' counter.getKthMostFrequent(i);', ' }', ' }', '', ' public void testSpeed() {', ' System.out.println("\\nMixing adding data with finding top k");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWordsMixed (counter, 6000000);', ' String [] expected = {"the", "edu", "to", "of", "and",', ' "in", "is", "ax", "that", "it",', ' "cmu", "for", "com", "you", "cs"};', ' checkExpected(counter, 0, expected);', ' }', '', '}'] | [{'reason_category': 'If Condition', 'usage_line': 182}, {'reason_category': 'If Body', 'usage_line': 183}, {'reason_category': 'If Body', 'usage_line': 184}, {'reason_category': 'If Body', 'usage_line': 185}, {'reason_category': 'If Condition', 'usage_line': 186}, {'reason_category': 'If Body', 'usage_line': 187}, {'reason_category': 'If Body', 'usage_line': 188}, {'reason_category': 'If Body', 'usage_line': 189}] | Global_Variable 'file' used at line 182 is defined at line 174 and has a Short-Range dependency.
Global_Variable 'file' used at line 183 is defined at line 174 and has a Short-Range dependency.
Global_Variable 'file' used at line 184 is defined at line 174 and has a Short-Range dependency.
Global_Variable 'reader' used at line 186 is defined at line 175 and has a Medium-Range dependency.
Global_Variable 'reader' used at line 187 is defined at line 175 and has a Medium-Range dependency.
Global_Variable 'reader' used at line 188 is defined at line 175 and has a Medium-Range dependency. | {'If Condition': 2, 'If Body': 6} | {'Global_Variable Short-Range': 3, 'Global_Variable Medium-Range': 3} |
infilling_java | CounterTester | 201 | 202 | ['import junit.framework.TestCase;', 'import java.io.*;', 'import java.util.HashMap;', 'import java.util.TreeMap;', 'import java.util.ArrayList;', '', '/**', ' * This silly little class wraps String, int pairs so they can be sorted.', ' * Used by the WordCounter class.', ' */', 'class WordWrapper implements Comparable <WordWrapper> {', '', ' private String myWord;', ' private int myCount;', ' private int mySlot;', '', ' /**', ' * Creates a new WordWrapper with string "XXX" and count zero.', ' */', ' public WordWrapper (String myWordIn, int myCountIn, int mySlotIn) {', ' myWord = myWordIn;', ' myCount = myCountIn;', ' mySlot = mySlotIn;', ' }', ' /**', ' * Returns a copy of the string in the WordWrapper.', ' *', ' * @return The word contained in this object. Is copied out: no aliasing.', ' */', ' public String extractWord () {', ' return new String (myWord);', ' }', '', ' /**', ' * Returns the count in this WordWrapper.', ' *', ' * @return The count contained in the object.', ' */', ' public int extractCount () {', ' return myCount;', ' }', '', ' public void incCount () {', ' myCount++;', ' }', '', ' public int getCount () {', ' return myCount;', ' }', '', ' public int getPos () {', ' return mySlot;', ' }', '', ' public void setPos (int toWhat) {', ' ', ' mySlot = toWhat;', ' }', '', ' public String toString () {', ' return myWord + " " + mySlot;', ' }', '', ' /**', ' * Comparison operator so we implement the Comparable interface.', ' *', ' * @param w The word wrapper to compare to', ' * @return a positive, zero, or negative value depending upon whether this', ' * word wrapper is less then, equal to, or greater than param w. The', ' * relationship is determied by looking at the counts.', ' */', ' public int compareTo (WordWrapper w) {', " // Check if the count of the current word (myCount) is equal to the count of the word 'w'", ' // If the counts are equal, compare the words lexicographically', ' if (w.myCount == myCount) {', ' return myWord.compareTo(w.myWord);', ' }', " // If the counts are not equal, subtract the count of the current word from the count of the word 'w'", ' return w.myCount - myCount;', ' }', '}', '', '', '/**', ' * This class is used to count occurences of words (strings) in a corpus. Used by', ' * the IndexedDocumentCollection class to find the most frequent words in the corpus.', ' */', '', 'class WordCounter {', ' ', " // this is the map that holds (for each word) the number of times we've seen it", ' // note that Integer is a wrapper for the buitin Java int type', ' private HashMap <String, WordWrapper> wordsIHaveSeen = new HashMap <String, WordWrapper> ();', ' private TreeMap <String, String> ones = new TreeMap <String, String> ();', ' ', ' // the set of words that have been extracted', ' private ArrayList<WordWrapper> extractedWords = new ArrayList <WordWrapper> ();', '', ' /**', ' * Accepts a word and increments the count of the number of times we have seen it.', ' * Note that a deep copy of the param is done (no aliasing).', ' *', ' * @param addMe The string to count', ' */', ' public void insert (String addMe) {', ' if (ones.containsKey (addMe)) {', ' ones.remove (addMe);', ' WordWrapper temp = new WordWrapper (addMe, 1, extractedWords.size ());', ' wordsIHaveSeen.put(addMe, temp);', ' extractedWords.add (temp);', ' }', '', ' // first check to see if the word is alredy in wordsIHaveSeen', ' if (wordsIHaveSeen.containsKey (addMe)) {', ' // if it is, then remove and increment its count', ' WordWrapper temp = wordsIHaveSeen.get (addMe);', ' temp.incCount ();', '', ' // find the slot that we go to in the extractedWords list', " // by sorting the 'extractedWords' list in ascending order", ' for (int i = temp.getPos () - 1; i >= 0 && ', ' extractedWords.get (i).compareTo (extractedWords.get (i + 1)) > 0; i--) {', ' temp = extractedWords.get (i + 1);', ' temp.setPos (i);', ' ', ' WordWrapper temp2 = extractedWords.get (i);', ' temp2.setPos (i + 1);', ' ', ' extractedWords.set (i + 1, temp2);', ' extractedWords.set (i, temp);', ' }', '', ' // in this case it is not there, so just add it', ' } else {', ' ones.put (addMe, addMe);', ' }', ' }', '', ' /**', ' * Returns the kth most frequent word in the corpus so far. A deep copy is returned,', ' * so no aliasing is possible. Returns null if there are not enough words.', ' *', ' * @param k Note that the most frequent word is at k = 0', ' * @return The kth most frequent word in the corpus to date', ' */', ' public String getKthMostFrequent (int k) {', '', ' // if we got here, then the array is all set up, so just return the kth most frequent word', ' if (k >= extractedWords.size ()) {', ' int which = extractedWords.size ();', ' for (String s : ones.navigableKeySet ()) {', ' if (which == k)', ' return s;', ' which++;', ' }', ' return null;', ' } else {', ' // If k is less than the size of the extractedWords list,', ' // return the kth most frequent word from extractedWords', ' return extractedWords.get (k).extractWord ();', ' }', ' }', '}', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class CounterTester extends TestCase {', '', ' /**', ' * File object to read words from, with buffering.', ' */', ' private FileReader file = null;', ' private BufferedReader reader = null;', '', ' /**', ' * Close file readers.', ' */', ' private void closeFiles() {', ' try {', ' if (file != null) {', ' file.close();', ' file = null;', ' }', ' if (reader != null) {', ' reader.close();', ' reader = null;', ' }', ' } catch (Exception e) {', ' System.err.println("Problem closing file");', ' System.err.println(e);', ' e.printStackTrace();', ' }', ' }', '', ' /**', ' * Close files no matter what happens in the test.', ' */', ' protected void tearDown () {'] | [' closeFiles();', ' }'] | ['', ' /**', ' * Open file and set up readers.', ' *', ' * @param fileName name of file to open', ' * */', ' private void openFile(String fileName) {', ' try {', ' file = new FileReader(fileName);', ' reader = new BufferedReader(file);', ' } catch (Exception e) {', ' System.err.format("Problem opening %s file\\n", fileName);', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Read the next numWords from the file.', ' *', ' * @param counter word counter to update', ' * @param numWords number of words to read.', ' */', ' private void readWords(WordCounter counter, int numWords) {', ' try {', ' for (int i=0; i<numWords; i++) {', ' if (i % 100000 == 0)', ' System.out.print (".");', ' String word = reader.readLine();', ' if (word == null) {', ' return;', ' }', " // Insert 'word' into the counter.", ' counter.insert(word);', ' }', ' } catch (Exception e) {', ' System.err.println("Problem reading file");', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Read the next numWords from the file, mixing with queries', ' *', ' * @param counter word counter to update', ' * @param numWords number of words to read.', ' */', ' private void readWordsMixed (WordCounter counter, int numWords) {', ' try {', ' int j = 0;', ' for (int i=0; i<numWords; i++) {', ' String word = reader.readLine();', " // If 'word' is null, it means we've reached the end of the file. So, return from the method.", ' if (word == null) {', ' return;', ' }', ' counter.insert(word);', '', ' // If the current iteration number is a multiple of 10 and greater than 100,000, perform a query of the kth most frequent word.', ' if (i % 10 == 0 && i > 100000) {', ' String myStr = counter.getKthMostFrequent(j++);', ' }', '', ' // rest j once we get to 100', ' if (j == 100)', ' j = 0;', ' }', ' } catch (Exception e) {', ' System.err.println("Problem reading file");', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Check that a sequence of words starts at the "start"th most', ' * frequent word.', ' *', ' * @param counter word counter to lookup', ' * @param start frequency index to start checking at', ' * @param expected array of expected words that start at that frequency', ' */', ' private void checkExpected(WordCounter counter, int start, String [] expected) {', ' for (int i = 0; i<expected.length; i++) {', ' String actual = counter.getKthMostFrequent(start);', ' System.out.format("k: %d, expected: %s, actual: %s\\n",', ' start, expected[i], actual);', ' assertEquals(expected[i], actual);', ' start++;', ' }', ' }', '', ' /**', ' * A test method.', ' * (Replace "X" with a name describing the test. You may write as', ' * many "testSomething" methods in this class as you wish, and each', ' * one will be called when running JUnit over this class.)', ' */', ' public void testSimple() {', ' System.out.println("\\nChecking insert");', ' WordCounter counter = new WordCounter();', ' counter.insert("pizzaz");', ' // Insert the word "pizza" into the counter twice', ' counter.insert("pizza");', ' counter.insert("pizza");', ' String [] expected = {"pizza"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void testTie() {', ' System.out.println("\\nChecking tie for 2nd place");', ' WordCounter counter = new WordCounter();', ' counter.insert("panache");', ' counter.insert("pizzaz");', ' counter.insert("pizza");', ' counter.insert("zebra");', ' counter.insert("pizza");', ' counter.insert("lion");', ' counter.insert("pizzaz");', ' counter.insert("panache");', ' counter.insert("panache");', ' counter.insert("camel");', ' // order is important here', ' String [] expected = {"pizza", "pizzaz"};', ' checkExpected(counter, 1, expected);', ' }', '', '', ' public void testPastTheEnd() {', ' System.out.println("\\nChecking past the end");', ' WordCounter counter = new WordCounter();', ' counter.insert("hi");', ' counter.insert("hello");', ' counter.insert("greetings");', ' counter.insert("salutations");', ' counter.insert("hi");', ' counter.insert("welcome");', ' counter.insert("goodbye");', ' counter.insert("later");', ' counter.insert("hello");', ' counter.insert("when");', ' counter.insert("hi");', ' assertNull(counter.getKthMostFrequent(8));', ' }', '', ' public void test100Top5() {', ' System.out.println("\\nChecking top 5 of 100 words");', ' WordCounter counter = new WordCounter();', ' // Open the file "allWordsBig"', ' openFile("allWordsBig");', ' // Read the next 100 words', ' readWords(counter, 100);', ' String [] expected = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void test300Top5() {', ' System.out.println("\\nChecking top 5 of first 100 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 100);', ' String [] expected1 = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter, 0, expected1);', '', ' System.out.println("Adding 100 more words and rechecking top 5");', ' readWords(counter, 100);', ' String [] expected2 = {"edu", "cmu", "comp", "cs", "state"};', ' checkExpected(counter, 0, expected2);', '', ' System.out.println("Adding 100 more words and rechecking top 5");', ' readWords(counter, 100);', ' String [] expected3 = {"edu", "cmu", "comp", "ohio", "state"};', ' checkExpected(counter, 0, expected3);', ' }', '', ' public void test300Words14Thru19() {', ' System.out.println("\\nChecking rank 14 through 19 of 300 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' // Read the next 300 words', ' readWords(counter, 300);', ' String [] expected = {"cantaloupe", "from", "ksu", "okstate", "on", "srv"};', ' checkExpected(counter, 14, expected);', ' }', '', ' public void test300CorrectNumber() {', ' System.out.println("\\nChecking correct number of unique words in 300 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 300);', ' /* check the 122th, 123th, and 124th most frequent word in the corpus so far ', ' * and check if the result is not null.', ' */', ' assertNotNull(counter.getKthMostFrequent(122));', ' assertNotNull(counter.getKthMostFrequent(123));', ' assertNotNull(counter.getKthMostFrequent(124));', ' // check the 125th most frequent word in the corpus so far', ' // and check if the result is null.', ' assertNull(counter.getKthMostFrequent(125));', ' }', '', ' public void test300and100() {', ' System.out.println("\\nChecking top 5 of 100 and 300 words with two counters");', ' WordCounter counter1 = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter1, 300);', ' closeFiles();', '', ' WordCounter counter2 = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter2, 100);', '', ' String [] expected1 = {"edu", "cmu", "comp", "ohio", "state"};', ' checkExpected(counter1, 0, expected1);', '', ' String [] expected2 = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter2, 0, expected2);', ' }', '', ' public void testAllTop15() {', ' System.out.println("\\nChecking top 15 of all words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' // Read the next 6000000 words', ' readWords(counter, 6000000);', ' String [] expected = {"the", "edu", "to", "of", "and",', ' "in", "is", "ax", "that", "it",', ' "cmu", "for", "com", "you", "cs"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void testAllTop10000() {', ' System.out.println("\\nChecking time to get top 10000 of all words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 6000000);', '', ' for (int i=0; i<10000; i++) {', ' counter.getKthMostFrequent(i);', ' }', ' }', '', ' public void testSpeed() {', ' System.out.println("\\nMixing adding data with finding top k");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWordsMixed (counter, 6000000);', ' String [] expected = {"the", "edu", "to", "of", "and",', ' "in", "is", "ax", "that", "it",', ' "cmu", "for", "com", "you", "cs"};', ' checkExpected(counter, 0, expected);', ' }', '', '}'] | [] | Function 'closeFiles' used at line 201 is defined at line 180 and has a Medium-Range dependency. | {} | {'Function Medium-Range': 1} |
infilling_java | CounterTester | 211 | 212 | ['import junit.framework.TestCase;', 'import java.io.*;', 'import java.util.HashMap;', 'import java.util.TreeMap;', 'import java.util.ArrayList;', '', '/**', ' * This silly little class wraps String, int pairs so they can be sorted.', ' * Used by the WordCounter class.', ' */', 'class WordWrapper implements Comparable <WordWrapper> {', '', ' private String myWord;', ' private int myCount;', ' private int mySlot;', '', ' /**', ' * Creates a new WordWrapper with string "XXX" and count zero.', ' */', ' public WordWrapper (String myWordIn, int myCountIn, int mySlotIn) {', ' myWord = myWordIn;', ' myCount = myCountIn;', ' mySlot = mySlotIn;', ' }', ' /**', ' * Returns a copy of the string in the WordWrapper.', ' *', ' * @return The word contained in this object. Is copied out: no aliasing.', ' */', ' public String extractWord () {', ' return new String (myWord);', ' }', '', ' /**', ' * Returns the count in this WordWrapper.', ' *', ' * @return The count contained in the object.', ' */', ' public int extractCount () {', ' return myCount;', ' }', '', ' public void incCount () {', ' myCount++;', ' }', '', ' public int getCount () {', ' return myCount;', ' }', '', ' public int getPos () {', ' return mySlot;', ' }', '', ' public void setPos (int toWhat) {', ' ', ' mySlot = toWhat;', ' }', '', ' public String toString () {', ' return myWord + " " + mySlot;', ' }', '', ' /**', ' * Comparison operator so we implement the Comparable interface.', ' *', ' * @param w The word wrapper to compare to', ' * @return a positive, zero, or negative value depending upon whether this', ' * word wrapper is less then, equal to, or greater than param w. The', ' * relationship is determied by looking at the counts.', ' */', ' public int compareTo (WordWrapper w) {', " // Check if the count of the current word (myCount) is equal to the count of the word 'w'", ' // If the counts are equal, compare the words lexicographically', ' if (w.myCount == myCount) {', ' return myWord.compareTo(w.myWord);', ' }', " // If the counts are not equal, subtract the count of the current word from the count of the word 'w'", ' return w.myCount - myCount;', ' }', '}', '', '', '/**', ' * This class is used to count occurences of words (strings) in a corpus. Used by', ' * the IndexedDocumentCollection class to find the most frequent words in the corpus.', ' */', '', 'class WordCounter {', ' ', " // this is the map that holds (for each word) the number of times we've seen it", ' // note that Integer is a wrapper for the buitin Java int type', ' private HashMap <String, WordWrapper> wordsIHaveSeen = new HashMap <String, WordWrapper> ();', ' private TreeMap <String, String> ones = new TreeMap <String, String> ();', ' ', ' // the set of words that have been extracted', ' private ArrayList<WordWrapper> extractedWords = new ArrayList <WordWrapper> ();', '', ' /**', ' * Accepts a word and increments the count of the number of times we have seen it.', ' * Note that a deep copy of the param is done (no aliasing).', ' *', ' * @param addMe The string to count', ' */', ' public void insert (String addMe) {', ' if (ones.containsKey (addMe)) {', ' ones.remove (addMe);', ' WordWrapper temp = new WordWrapper (addMe, 1, extractedWords.size ());', ' wordsIHaveSeen.put(addMe, temp);', ' extractedWords.add (temp);', ' }', '', ' // first check to see if the word is alredy in wordsIHaveSeen', ' if (wordsIHaveSeen.containsKey (addMe)) {', ' // if it is, then remove and increment its count', ' WordWrapper temp = wordsIHaveSeen.get (addMe);', ' temp.incCount ();', '', ' // find the slot that we go to in the extractedWords list', " // by sorting the 'extractedWords' list in ascending order", ' for (int i = temp.getPos () - 1; i >= 0 && ', ' extractedWords.get (i).compareTo (extractedWords.get (i + 1)) > 0; i--) {', ' temp = extractedWords.get (i + 1);', ' temp.setPos (i);', ' ', ' WordWrapper temp2 = extractedWords.get (i);', ' temp2.setPos (i + 1);', ' ', ' extractedWords.set (i + 1, temp2);', ' extractedWords.set (i, temp);', ' }', '', ' // in this case it is not there, so just add it', ' } else {', ' ones.put (addMe, addMe);', ' }', ' }', '', ' /**', ' * Returns the kth most frequent word in the corpus so far. A deep copy is returned,', ' * so no aliasing is possible. Returns null if there are not enough words.', ' *', ' * @param k Note that the most frequent word is at k = 0', ' * @return The kth most frequent word in the corpus to date', ' */', ' public String getKthMostFrequent (int k) {', '', ' // if we got here, then the array is all set up, so just return the kth most frequent word', ' if (k >= extractedWords.size ()) {', ' int which = extractedWords.size ();', ' for (String s : ones.navigableKeySet ()) {', ' if (which == k)', ' return s;', ' which++;', ' }', ' return null;', ' } else {', ' // If k is less than the size of the extractedWords list,', ' // return the kth most frequent word from extractedWords', ' return extractedWords.get (k).extractWord ();', ' }', ' }', '}', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class CounterTester extends TestCase {', '', ' /**', ' * File object to read words from, with buffering.', ' */', ' private FileReader file = null;', ' private BufferedReader reader = null;', '', ' /**', ' * Close file readers.', ' */', ' private void closeFiles() {', ' try {', ' if (file != null) {', ' file.close();', ' file = null;', ' }', ' if (reader != null) {', ' reader.close();', ' reader = null;', ' }', ' } catch (Exception e) {', ' System.err.println("Problem closing file");', ' System.err.println(e);', ' e.printStackTrace();', ' }', ' }', '', ' /**', ' * Close files no matter what happens in the test.', ' */', ' protected void tearDown () {', ' closeFiles();', ' }', '', ' /**', ' * Open file and set up readers.', ' *', ' * @param fileName name of file to open', ' * */', ' private void openFile(String fileName) {', ' try {'] | [' file = new FileReader(fileName);', ' reader = new BufferedReader(file);'] | [' } catch (Exception e) {', ' System.err.format("Problem opening %s file\\n", fileName);', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Read the next numWords from the file.', ' *', ' * @param counter word counter to update', ' * @param numWords number of words to read.', ' */', ' private void readWords(WordCounter counter, int numWords) {', ' try {', ' for (int i=0; i<numWords; i++) {', ' if (i % 100000 == 0)', ' System.out.print (".");', ' String word = reader.readLine();', ' if (word == null) {', ' return;', ' }', " // Insert 'word' into the counter.", ' counter.insert(word);', ' }', ' } catch (Exception e) {', ' System.err.println("Problem reading file");', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Read the next numWords from the file, mixing with queries', ' *', ' * @param counter word counter to update', ' * @param numWords number of words to read.', ' */', ' private void readWordsMixed (WordCounter counter, int numWords) {', ' try {', ' int j = 0;', ' for (int i=0; i<numWords; i++) {', ' String word = reader.readLine();', " // If 'word' is null, it means we've reached the end of the file. So, return from the method.", ' if (word == null) {', ' return;', ' }', ' counter.insert(word);', '', ' // If the current iteration number is a multiple of 10 and greater than 100,000, perform a query of the kth most frequent word.', ' if (i % 10 == 0 && i > 100000) {', ' String myStr = counter.getKthMostFrequent(j++);', ' }', '', ' // rest j once we get to 100', ' if (j == 100)', ' j = 0;', ' }', ' } catch (Exception e) {', ' System.err.println("Problem reading file");', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Check that a sequence of words starts at the "start"th most', ' * frequent word.', ' *', ' * @param counter word counter to lookup', ' * @param start frequency index to start checking at', ' * @param expected array of expected words that start at that frequency', ' */', ' private void checkExpected(WordCounter counter, int start, String [] expected) {', ' for (int i = 0; i<expected.length; i++) {', ' String actual = counter.getKthMostFrequent(start);', ' System.out.format("k: %d, expected: %s, actual: %s\\n",', ' start, expected[i], actual);', ' assertEquals(expected[i], actual);', ' start++;', ' }', ' }', '', ' /**', ' * A test method.', ' * (Replace "X" with a name describing the test. You may write as', ' * many "testSomething" methods in this class as you wish, and each', ' * one will be called when running JUnit over this class.)', ' */', ' public void testSimple() {', ' System.out.println("\\nChecking insert");', ' WordCounter counter = new WordCounter();', ' counter.insert("pizzaz");', ' // Insert the word "pizza" into the counter twice', ' counter.insert("pizza");', ' counter.insert("pizza");', ' String [] expected = {"pizza"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void testTie() {', ' System.out.println("\\nChecking tie for 2nd place");', ' WordCounter counter = new WordCounter();', ' counter.insert("panache");', ' counter.insert("pizzaz");', ' counter.insert("pizza");', ' counter.insert("zebra");', ' counter.insert("pizza");', ' counter.insert("lion");', ' counter.insert("pizzaz");', ' counter.insert("panache");', ' counter.insert("panache");', ' counter.insert("camel");', ' // order is important here', ' String [] expected = {"pizza", "pizzaz"};', ' checkExpected(counter, 1, expected);', ' }', '', '', ' public void testPastTheEnd() {', ' System.out.println("\\nChecking past the end");', ' WordCounter counter = new WordCounter();', ' counter.insert("hi");', ' counter.insert("hello");', ' counter.insert("greetings");', ' counter.insert("salutations");', ' counter.insert("hi");', ' counter.insert("welcome");', ' counter.insert("goodbye");', ' counter.insert("later");', ' counter.insert("hello");', ' counter.insert("when");', ' counter.insert("hi");', ' assertNull(counter.getKthMostFrequent(8));', ' }', '', ' public void test100Top5() {', ' System.out.println("\\nChecking top 5 of 100 words");', ' WordCounter counter = new WordCounter();', ' // Open the file "allWordsBig"', ' openFile("allWordsBig");', ' // Read the next 100 words', ' readWords(counter, 100);', ' String [] expected = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void test300Top5() {', ' System.out.println("\\nChecking top 5 of first 100 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 100);', ' String [] expected1 = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter, 0, expected1);', '', ' System.out.println("Adding 100 more words and rechecking top 5");', ' readWords(counter, 100);', ' String [] expected2 = {"edu", "cmu", "comp", "cs", "state"};', ' checkExpected(counter, 0, expected2);', '', ' System.out.println("Adding 100 more words and rechecking top 5");', ' readWords(counter, 100);', ' String [] expected3 = {"edu", "cmu", "comp", "ohio", "state"};', ' checkExpected(counter, 0, expected3);', ' }', '', ' public void test300Words14Thru19() {', ' System.out.println("\\nChecking rank 14 through 19 of 300 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' // Read the next 300 words', ' readWords(counter, 300);', ' String [] expected = {"cantaloupe", "from", "ksu", "okstate", "on", "srv"};', ' checkExpected(counter, 14, expected);', ' }', '', ' public void test300CorrectNumber() {', ' System.out.println("\\nChecking correct number of unique words in 300 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 300);', ' /* check the 122th, 123th, and 124th most frequent word in the corpus so far ', ' * and check if the result is not null.', ' */', ' assertNotNull(counter.getKthMostFrequent(122));', ' assertNotNull(counter.getKthMostFrequent(123));', ' assertNotNull(counter.getKthMostFrequent(124));', ' // check the 125th most frequent word in the corpus so far', ' // and check if the result is null.', ' assertNull(counter.getKthMostFrequent(125));', ' }', '', ' public void test300and100() {', ' System.out.println("\\nChecking top 5 of 100 and 300 words with two counters");', ' WordCounter counter1 = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter1, 300);', ' closeFiles();', '', ' WordCounter counter2 = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter2, 100);', '', ' String [] expected1 = {"edu", "cmu", "comp", "ohio", "state"};', ' checkExpected(counter1, 0, expected1);', '', ' String [] expected2 = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter2, 0, expected2);', ' }', '', ' public void testAllTop15() {', ' System.out.println("\\nChecking top 15 of all words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' // Read the next 6000000 words', ' readWords(counter, 6000000);', ' String [] expected = {"the", "edu", "to", "of", "and",', ' "in", "is", "ax", "that", "it",', ' "cmu", "for", "com", "you", "cs"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void testAllTop10000() {', ' System.out.println("\\nChecking time to get top 10000 of all words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 6000000);', '', ' for (int i=0; i<10000; i++) {', ' counter.getKthMostFrequent(i);', ' }', ' }', '', ' public void testSpeed() {', ' System.out.println("\\nMixing adding data with finding top k");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWordsMixed (counter, 6000000);', ' String [] expected = {"the", "edu", "to", "of", "and",', ' "in", "is", "ax", "that", "it",', ' "cmu", "for", "com", "you", "cs"};', ' checkExpected(counter, 0, expected);', ' }', '', '}'] | [] | Variable 'fileName' used at line 211 is defined at line 209 and has a Short-Range dependency.
Global_Variable 'file' used at line 211 is defined at line 174 and has a Long-Range dependency.
Global_Variable 'file' used at line 212 is defined at line 211 and has a Short-Range dependency.
Global_Variable 'reader' used at line 212 is defined at line 175 and has a Long-Range dependency. | {} | {'Variable Short-Range': 1, 'Global_Variable Long-Range': 2, 'Global_Variable Short-Range': 1} |
infilling_java | CounterTester | 231 | 231 | ['import junit.framework.TestCase;', 'import java.io.*;', 'import java.util.HashMap;', 'import java.util.TreeMap;', 'import java.util.ArrayList;', '', '/**', ' * This silly little class wraps String, int pairs so they can be sorted.', ' * Used by the WordCounter class.', ' */', 'class WordWrapper implements Comparable <WordWrapper> {', '', ' private String myWord;', ' private int myCount;', ' private int mySlot;', '', ' /**', ' * Creates a new WordWrapper with string "XXX" and count zero.', ' */', ' public WordWrapper (String myWordIn, int myCountIn, int mySlotIn) {', ' myWord = myWordIn;', ' myCount = myCountIn;', ' mySlot = mySlotIn;', ' }', ' /**', ' * Returns a copy of the string in the WordWrapper.', ' *', ' * @return The word contained in this object. Is copied out: no aliasing.', ' */', ' public String extractWord () {', ' return new String (myWord);', ' }', '', ' /**', ' * Returns the count in this WordWrapper.', ' *', ' * @return The count contained in the object.', ' */', ' public int extractCount () {', ' return myCount;', ' }', '', ' public void incCount () {', ' myCount++;', ' }', '', ' public int getCount () {', ' return myCount;', ' }', '', ' public int getPos () {', ' return mySlot;', ' }', '', ' public void setPos (int toWhat) {', ' ', ' mySlot = toWhat;', ' }', '', ' public String toString () {', ' return myWord + " " + mySlot;', ' }', '', ' /**', ' * Comparison operator so we implement the Comparable interface.', ' *', ' * @param w The word wrapper to compare to', ' * @return a positive, zero, or negative value depending upon whether this', ' * word wrapper is less then, equal to, or greater than param w. The', ' * relationship is determied by looking at the counts.', ' */', ' public int compareTo (WordWrapper w) {', " // Check if the count of the current word (myCount) is equal to the count of the word 'w'", ' // If the counts are equal, compare the words lexicographically', ' if (w.myCount == myCount) {', ' return myWord.compareTo(w.myWord);', ' }', " // If the counts are not equal, subtract the count of the current word from the count of the word 'w'", ' return w.myCount - myCount;', ' }', '}', '', '', '/**', ' * This class is used to count occurences of words (strings) in a corpus. Used by', ' * the IndexedDocumentCollection class to find the most frequent words in the corpus.', ' */', '', 'class WordCounter {', ' ', " // this is the map that holds (for each word) the number of times we've seen it", ' // note that Integer is a wrapper for the buitin Java int type', ' private HashMap <String, WordWrapper> wordsIHaveSeen = new HashMap <String, WordWrapper> ();', ' private TreeMap <String, String> ones = new TreeMap <String, String> ();', ' ', ' // the set of words that have been extracted', ' private ArrayList<WordWrapper> extractedWords = new ArrayList <WordWrapper> ();', '', ' /**', ' * Accepts a word and increments the count of the number of times we have seen it.', ' * Note that a deep copy of the param is done (no aliasing).', ' *', ' * @param addMe The string to count', ' */', ' public void insert (String addMe) {', ' if (ones.containsKey (addMe)) {', ' ones.remove (addMe);', ' WordWrapper temp = new WordWrapper (addMe, 1, extractedWords.size ());', ' wordsIHaveSeen.put(addMe, temp);', ' extractedWords.add (temp);', ' }', '', ' // first check to see if the word is alredy in wordsIHaveSeen', ' if (wordsIHaveSeen.containsKey (addMe)) {', ' // if it is, then remove and increment its count', ' WordWrapper temp = wordsIHaveSeen.get (addMe);', ' temp.incCount ();', '', ' // find the slot that we go to in the extractedWords list', " // by sorting the 'extractedWords' list in ascending order", ' for (int i = temp.getPos () - 1; i >= 0 && ', ' extractedWords.get (i).compareTo (extractedWords.get (i + 1)) > 0; i--) {', ' temp = extractedWords.get (i + 1);', ' temp.setPos (i);', ' ', ' WordWrapper temp2 = extractedWords.get (i);', ' temp2.setPos (i + 1);', ' ', ' extractedWords.set (i + 1, temp2);', ' extractedWords.set (i, temp);', ' }', '', ' // in this case it is not there, so just add it', ' } else {', ' ones.put (addMe, addMe);', ' }', ' }', '', ' /**', ' * Returns the kth most frequent word in the corpus so far. A deep copy is returned,', ' * so no aliasing is possible. Returns null if there are not enough words.', ' *', ' * @param k Note that the most frequent word is at k = 0', ' * @return The kth most frequent word in the corpus to date', ' */', ' public String getKthMostFrequent (int k) {', '', ' // if we got here, then the array is all set up, so just return the kth most frequent word', ' if (k >= extractedWords.size ()) {', ' int which = extractedWords.size ();', ' for (String s : ones.navigableKeySet ()) {', ' if (which == k)', ' return s;', ' which++;', ' }', ' return null;', ' } else {', ' // If k is less than the size of the extractedWords list,', ' // return the kth most frequent word from extractedWords', ' return extractedWords.get (k).extractWord ();', ' }', ' }', '}', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class CounterTester extends TestCase {', '', ' /**', ' * File object to read words from, with buffering.', ' */', ' private FileReader file = null;', ' private BufferedReader reader = null;', '', ' /**', ' * Close file readers.', ' */', ' private void closeFiles() {', ' try {', ' if (file != null) {', ' file.close();', ' file = null;', ' }', ' if (reader != null) {', ' reader.close();', ' reader = null;', ' }', ' } catch (Exception e) {', ' System.err.println("Problem closing file");', ' System.err.println(e);', ' e.printStackTrace();', ' }', ' }', '', ' /**', ' * Close files no matter what happens in the test.', ' */', ' protected void tearDown () {', ' closeFiles();', ' }', '', ' /**', ' * Open file and set up readers.', ' *', ' * @param fileName name of file to open', ' * */', ' private void openFile(String fileName) {', ' try {', ' file = new FileReader(fileName);', ' reader = new BufferedReader(file);', ' } catch (Exception e) {', ' System.err.format("Problem opening %s file\\n", fileName);', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Read the next numWords from the file.', ' *', ' * @param counter word counter to update', ' * @param numWords number of words to read.', ' */', ' private void readWords(WordCounter counter, int numWords) {', ' try {', ' for (int i=0; i<numWords; i++) {', ' if (i % 100000 == 0)'] | [' System.out.print (".");'] | [' String word = reader.readLine();', ' if (word == null) {', ' return;', ' }', " // Insert 'word' into the counter.", ' counter.insert(word);', ' }', ' } catch (Exception e) {', ' System.err.println("Problem reading file");', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Read the next numWords from the file, mixing with queries', ' *', ' * @param counter word counter to update', ' * @param numWords number of words to read.', ' */', ' private void readWordsMixed (WordCounter counter, int numWords) {', ' try {', ' int j = 0;', ' for (int i=0; i<numWords; i++) {', ' String word = reader.readLine();', " // If 'word' is null, it means we've reached the end of the file. So, return from the method.", ' if (word == null) {', ' return;', ' }', ' counter.insert(word);', '', ' // If the current iteration number is a multiple of 10 and greater than 100,000, perform a query of the kth most frequent word.', ' if (i % 10 == 0 && i > 100000) {', ' String myStr = counter.getKthMostFrequent(j++);', ' }', '', ' // rest j once we get to 100', ' if (j == 100)', ' j = 0;', ' }', ' } catch (Exception e) {', ' System.err.println("Problem reading file");', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Check that a sequence of words starts at the "start"th most', ' * frequent word.', ' *', ' * @param counter word counter to lookup', ' * @param start frequency index to start checking at', ' * @param expected array of expected words that start at that frequency', ' */', ' private void checkExpected(WordCounter counter, int start, String [] expected) {', ' for (int i = 0; i<expected.length; i++) {', ' String actual = counter.getKthMostFrequent(start);', ' System.out.format("k: %d, expected: %s, actual: %s\\n",', ' start, expected[i], actual);', ' assertEquals(expected[i], actual);', ' start++;', ' }', ' }', '', ' /**', ' * A test method.', ' * (Replace "X" with a name describing the test. You may write as', ' * many "testSomething" methods in this class as you wish, and each', ' * one will be called when running JUnit over this class.)', ' */', ' public void testSimple() {', ' System.out.println("\\nChecking insert");', ' WordCounter counter = new WordCounter();', ' counter.insert("pizzaz");', ' // Insert the word "pizza" into the counter twice', ' counter.insert("pizza");', ' counter.insert("pizza");', ' String [] expected = {"pizza"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void testTie() {', ' System.out.println("\\nChecking tie for 2nd place");', ' WordCounter counter = new WordCounter();', ' counter.insert("panache");', ' counter.insert("pizzaz");', ' counter.insert("pizza");', ' counter.insert("zebra");', ' counter.insert("pizza");', ' counter.insert("lion");', ' counter.insert("pizzaz");', ' counter.insert("panache");', ' counter.insert("panache");', ' counter.insert("camel");', ' // order is important here', ' String [] expected = {"pizza", "pizzaz"};', ' checkExpected(counter, 1, expected);', ' }', '', '', ' public void testPastTheEnd() {', ' System.out.println("\\nChecking past the end");', ' WordCounter counter = new WordCounter();', ' counter.insert("hi");', ' counter.insert("hello");', ' counter.insert("greetings");', ' counter.insert("salutations");', ' counter.insert("hi");', ' counter.insert("welcome");', ' counter.insert("goodbye");', ' counter.insert("later");', ' counter.insert("hello");', ' counter.insert("when");', ' counter.insert("hi");', ' assertNull(counter.getKthMostFrequent(8));', ' }', '', ' public void test100Top5() {', ' System.out.println("\\nChecking top 5 of 100 words");', ' WordCounter counter = new WordCounter();', ' // Open the file "allWordsBig"', ' openFile("allWordsBig");', ' // Read the next 100 words', ' readWords(counter, 100);', ' String [] expected = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void test300Top5() {', ' System.out.println("\\nChecking top 5 of first 100 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 100);', ' String [] expected1 = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter, 0, expected1);', '', ' System.out.println("Adding 100 more words and rechecking top 5");', ' readWords(counter, 100);', ' String [] expected2 = {"edu", "cmu", "comp", "cs", "state"};', ' checkExpected(counter, 0, expected2);', '', ' System.out.println("Adding 100 more words and rechecking top 5");', ' readWords(counter, 100);', ' String [] expected3 = {"edu", "cmu", "comp", "ohio", "state"};', ' checkExpected(counter, 0, expected3);', ' }', '', ' public void test300Words14Thru19() {', ' System.out.println("\\nChecking rank 14 through 19 of 300 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' // Read the next 300 words', ' readWords(counter, 300);', ' String [] expected = {"cantaloupe", "from", "ksu", "okstate", "on", "srv"};', ' checkExpected(counter, 14, expected);', ' }', '', ' public void test300CorrectNumber() {', ' System.out.println("\\nChecking correct number of unique words in 300 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 300);', ' /* check the 122th, 123th, and 124th most frequent word in the corpus so far ', ' * and check if the result is not null.', ' */', ' assertNotNull(counter.getKthMostFrequent(122));', ' assertNotNull(counter.getKthMostFrequent(123));', ' assertNotNull(counter.getKthMostFrequent(124));', ' // check the 125th most frequent word in the corpus so far', ' // and check if the result is null.', ' assertNull(counter.getKthMostFrequent(125));', ' }', '', ' public void test300and100() {', ' System.out.println("\\nChecking top 5 of 100 and 300 words with two counters");', ' WordCounter counter1 = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter1, 300);', ' closeFiles();', '', ' WordCounter counter2 = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter2, 100);', '', ' String [] expected1 = {"edu", "cmu", "comp", "ohio", "state"};', ' checkExpected(counter1, 0, expected1);', '', ' String [] expected2 = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter2, 0, expected2);', ' }', '', ' public void testAllTop15() {', ' System.out.println("\\nChecking top 15 of all words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' // Read the next 6000000 words', ' readWords(counter, 6000000);', ' String [] expected = {"the", "edu", "to", "of", "and",', ' "in", "is", "ax", "that", "it",', ' "cmu", "for", "com", "you", "cs"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void testAllTop10000() {', ' System.out.println("\\nChecking time to get top 10000 of all words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 6000000);', '', ' for (int i=0; i<10000; i++) {', ' counter.getKthMostFrequent(i);', ' }', ' }', '', ' public void testSpeed() {', ' System.out.println("\\nMixing adding data with finding top k");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWordsMixed (counter, 6000000);', ' String [] expected = {"the", "edu", "to", "of", "and",', ' "in", "is", "ax", "that", "it",', ' "cmu", "for", "com", "you", "cs"};', ' checkExpected(counter, 0, expected);', ' }', '', '}'] | [{'reason_category': 'If Body', 'usage_line': 231}, {'reason_category': 'Loop Body', 'usage_line': 231}] | null | {'If Body': 1, 'Loop Body': 1} | null |
infilling_java | CounterTester | 234 | 235 | ['import junit.framework.TestCase;', 'import java.io.*;', 'import java.util.HashMap;', 'import java.util.TreeMap;', 'import java.util.ArrayList;', '', '/**', ' * This silly little class wraps String, int pairs so they can be sorted.', ' * Used by the WordCounter class.', ' */', 'class WordWrapper implements Comparable <WordWrapper> {', '', ' private String myWord;', ' private int myCount;', ' private int mySlot;', '', ' /**', ' * Creates a new WordWrapper with string "XXX" and count zero.', ' */', ' public WordWrapper (String myWordIn, int myCountIn, int mySlotIn) {', ' myWord = myWordIn;', ' myCount = myCountIn;', ' mySlot = mySlotIn;', ' }', ' /**', ' * Returns a copy of the string in the WordWrapper.', ' *', ' * @return The word contained in this object. Is copied out: no aliasing.', ' */', ' public String extractWord () {', ' return new String (myWord);', ' }', '', ' /**', ' * Returns the count in this WordWrapper.', ' *', ' * @return The count contained in the object.', ' */', ' public int extractCount () {', ' return myCount;', ' }', '', ' public void incCount () {', ' myCount++;', ' }', '', ' public int getCount () {', ' return myCount;', ' }', '', ' public int getPos () {', ' return mySlot;', ' }', '', ' public void setPos (int toWhat) {', ' ', ' mySlot = toWhat;', ' }', '', ' public String toString () {', ' return myWord + " " + mySlot;', ' }', '', ' /**', ' * Comparison operator so we implement the Comparable interface.', ' *', ' * @param w The word wrapper to compare to', ' * @return a positive, zero, or negative value depending upon whether this', ' * word wrapper is less then, equal to, or greater than param w. The', ' * relationship is determied by looking at the counts.', ' */', ' public int compareTo (WordWrapper w) {', " // Check if the count of the current word (myCount) is equal to the count of the word 'w'", ' // If the counts are equal, compare the words lexicographically', ' if (w.myCount == myCount) {', ' return myWord.compareTo(w.myWord);', ' }', " // If the counts are not equal, subtract the count of the current word from the count of the word 'w'", ' return w.myCount - myCount;', ' }', '}', '', '', '/**', ' * This class is used to count occurences of words (strings) in a corpus. Used by', ' * the IndexedDocumentCollection class to find the most frequent words in the corpus.', ' */', '', 'class WordCounter {', ' ', " // this is the map that holds (for each word) the number of times we've seen it", ' // note that Integer is a wrapper for the buitin Java int type', ' private HashMap <String, WordWrapper> wordsIHaveSeen = new HashMap <String, WordWrapper> ();', ' private TreeMap <String, String> ones = new TreeMap <String, String> ();', ' ', ' // the set of words that have been extracted', ' private ArrayList<WordWrapper> extractedWords = new ArrayList <WordWrapper> ();', '', ' /**', ' * Accepts a word and increments the count of the number of times we have seen it.', ' * Note that a deep copy of the param is done (no aliasing).', ' *', ' * @param addMe The string to count', ' */', ' public void insert (String addMe) {', ' if (ones.containsKey (addMe)) {', ' ones.remove (addMe);', ' WordWrapper temp = new WordWrapper (addMe, 1, extractedWords.size ());', ' wordsIHaveSeen.put(addMe, temp);', ' extractedWords.add (temp);', ' }', '', ' // first check to see if the word is alredy in wordsIHaveSeen', ' if (wordsIHaveSeen.containsKey (addMe)) {', ' // if it is, then remove and increment its count', ' WordWrapper temp = wordsIHaveSeen.get (addMe);', ' temp.incCount ();', '', ' // find the slot that we go to in the extractedWords list', " // by sorting the 'extractedWords' list in ascending order", ' for (int i = temp.getPos () - 1; i >= 0 && ', ' extractedWords.get (i).compareTo (extractedWords.get (i + 1)) > 0; i--) {', ' temp = extractedWords.get (i + 1);', ' temp.setPos (i);', ' ', ' WordWrapper temp2 = extractedWords.get (i);', ' temp2.setPos (i + 1);', ' ', ' extractedWords.set (i + 1, temp2);', ' extractedWords.set (i, temp);', ' }', '', ' // in this case it is not there, so just add it', ' } else {', ' ones.put (addMe, addMe);', ' }', ' }', '', ' /**', ' * Returns the kth most frequent word in the corpus so far. A deep copy is returned,', ' * so no aliasing is possible. Returns null if there are not enough words.', ' *', ' * @param k Note that the most frequent word is at k = 0', ' * @return The kth most frequent word in the corpus to date', ' */', ' public String getKthMostFrequent (int k) {', '', ' // if we got here, then the array is all set up, so just return the kth most frequent word', ' if (k >= extractedWords.size ()) {', ' int which = extractedWords.size ();', ' for (String s : ones.navigableKeySet ()) {', ' if (which == k)', ' return s;', ' which++;', ' }', ' return null;', ' } else {', ' // If k is less than the size of the extractedWords list,', ' // return the kth most frequent word from extractedWords', ' return extractedWords.get (k).extractWord ();', ' }', ' }', '}', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class CounterTester extends TestCase {', '', ' /**', ' * File object to read words from, with buffering.', ' */', ' private FileReader file = null;', ' private BufferedReader reader = null;', '', ' /**', ' * Close file readers.', ' */', ' private void closeFiles() {', ' try {', ' if (file != null) {', ' file.close();', ' file = null;', ' }', ' if (reader != null) {', ' reader.close();', ' reader = null;', ' }', ' } catch (Exception e) {', ' System.err.println("Problem closing file");', ' System.err.println(e);', ' e.printStackTrace();', ' }', ' }', '', ' /**', ' * Close files no matter what happens in the test.', ' */', ' protected void tearDown () {', ' closeFiles();', ' }', '', ' /**', ' * Open file and set up readers.', ' *', ' * @param fileName name of file to open', ' * */', ' private void openFile(String fileName) {', ' try {', ' file = new FileReader(fileName);', ' reader = new BufferedReader(file);', ' } catch (Exception e) {', ' System.err.format("Problem opening %s file\\n", fileName);', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Read the next numWords from the file.', ' *', ' * @param counter word counter to update', ' * @param numWords number of words to read.', ' */', ' private void readWords(WordCounter counter, int numWords) {', ' try {', ' for (int i=0; i<numWords; i++) {', ' if (i % 100000 == 0)', ' System.out.print (".");', ' String word = reader.readLine();', ' if (word == null) {'] | [' return;', ' }'] | [" // Insert 'word' into the counter.", ' counter.insert(word);', ' }', ' } catch (Exception e) {', ' System.err.println("Problem reading file");', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Read the next numWords from the file, mixing with queries', ' *', ' * @param counter word counter to update', ' * @param numWords number of words to read.', ' */', ' private void readWordsMixed (WordCounter counter, int numWords) {', ' try {', ' int j = 0;', ' for (int i=0; i<numWords; i++) {', ' String word = reader.readLine();', " // If 'word' is null, it means we've reached the end of the file. So, return from the method.", ' if (word == null) {', ' return;', ' }', ' counter.insert(word);', '', ' // If the current iteration number is a multiple of 10 and greater than 100,000, perform a query of the kth most frequent word.', ' if (i % 10 == 0 && i > 100000) {', ' String myStr = counter.getKthMostFrequent(j++);', ' }', '', ' // rest j once we get to 100', ' if (j == 100)', ' j = 0;', ' }', ' } catch (Exception e) {', ' System.err.println("Problem reading file");', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Check that a sequence of words starts at the "start"th most', ' * frequent word.', ' *', ' * @param counter word counter to lookup', ' * @param start frequency index to start checking at', ' * @param expected array of expected words that start at that frequency', ' */', ' private void checkExpected(WordCounter counter, int start, String [] expected) {', ' for (int i = 0; i<expected.length; i++) {', ' String actual = counter.getKthMostFrequent(start);', ' System.out.format("k: %d, expected: %s, actual: %s\\n",', ' start, expected[i], actual);', ' assertEquals(expected[i], actual);', ' start++;', ' }', ' }', '', ' /**', ' * A test method.', ' * (Replace "X" with a name describing the test. You may write as', ' * many "testSomething" methods in this class as you wish, and each', ' * one will be called when running JUnit over this class.)', ' */', ' public void testSimple() {', ' System.out.println("\\nChecking insert");', ' WordCounter counter = new WordCounter();', ' counter.insert("pizzaz");', ' // Insert the word "pizza" into the counter twice', ' counter.insert("pizza");', ' counter.insert("pizza");', ' String [] expected = {"pizza"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void testTie() {', ' System.out.println("\\nChecking tie for 2nd place");', ' WordCounter counter = new WordCounter();', ' counter.insert("panache");', ' counter.insert("pizzaz");', ' counter.insert("pizza");', ' counter.insert("zebra");', ' counter.insert("pizza");', ' counter.insert("lion");', ' counter.insert("pizzaz");', ' counter.insert("panache");', ' counter.insert("panache");', ' counter.insert("camel");', ' // order is important here', ' String [] expected = {"pizza", "pizzaz"};', ' checkExpected(counter, 1, expected);', ' }', '', '', ' public void testPastTheEnd() {', ' System.out.println("\\nChecking past the end");', ' WordCounter counter = new WordCounter();', ' counter.insert("hi");', ' counter.insert("hello");', ' counter.insert("greetings");', ' counter.insert("salutations");', ' counter.insert("hi");', ' counter.insert("welcome");', ' counter.insert("goodbye");', ' counter.insert("later");', ' counter.insert("hello");', ' counter.insert("when");', ' counter.insert("hi");', ' assertNull(counter.getKthMostFrequent(8));', ' }', '', ' public void test100Top5() {', ' System.out.println("\\nChecking top 5 of 100 words");', ' WordCounter counter = new WordCounter();', ' // Open the file "allWordsBig"', ' openFile("allWordsBig");', ' // Read the next 100 words', ' readWords(counter, 100);', ' String [] expected = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void test300Top5() {', ' System.out.println("\\nChecking top 5 of first 100 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 100);', ' String [] expected1 = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter, 0, expected1);', '', ' System.out.println("Adding 100 more words and rechecking top 5");', ' readWords(counter, 100);', ' String [] expected2 = {"edu", "cmu", "comp", "cs", "state"};', ' checkExpected(counter, 0, expected2);', '', ' System.out.println("Adding 100 more words and rechecking top 5");', ' readWords(counter, 100);', ' String [] expected3 = {"edu", "cmu", "comp", "ohio", "state"};', ' checkExpected(counter, 0, expected3);', ' }', '', ' public void test300Words14Thru19() {', ' System.out.println("\\nChecking rank 14 through 19 of 300 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' // Read the next 300 words', ' readWords(counter, 300);', ' String [] expected = {"cantaloupe", "from", "ksu", "okstate", "on", "srv"};', ' checkExpected(counter, 14, expected);', ' }', '', ' public void test300CorrectNumber() {', ' System.out.println("\\nChecking correct number of unique words in 300 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 300);', ' /* check the 122th, 123th, and 124th most frequent word in the corpus so far ', ' * and check if the result is not null.', ' */', ' assertNotNull(counter.getKthMostFrequent(122));', ' assertNotNull(counter.getKthMostFrequent(123));', ' assertNotNull(counter.getKthMostFrequent(124));', ' // check the 125th most frequent word in the corpus so far', ' // and check if the result is null.', ' assertNull(counter.getKthMostFrequent(125));', ' }', '', ' public void test300and100() {', ' System.out.println("\\nChecking top 5 of 100 and 300 words with two counters");', ' WordCounter counter1 = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter1, 300);', ' closeFiles();', '', ' WordCounter counter2 = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter2, 100);', '', ' String [] expected1 = {"edu", "cmu", "comp", "ohio", "state"};', ' checkExpected(counter1, 0, expected1);', '', ' String [] expected2 = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter2, 0, expected2);', ' }', '', ' public void testAllTop15() {', ' System.out.println("\\nChecking top 15 of all words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' // Read the next 6000000 words', ' readWords(counter, 6000000);', ' String [] expected = {"the", "edu", "to", "of", "and",', ' "in", "is", "ax", "that", "it",', ' "cmu", "for", "com", "you", "cs"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void testAllTop10000() {', ' System.out.println("\\nChecking time to get top 10000 of all words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 6000000);', '', ' for (int i=0; i<10000; i++) {', ' counter.getKthMostFrequent(i);', ' }', ' }', '', ' public void testSpeed() {', ' System.out.println("\\nMixing adding data with finding top k");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWordsMixed (counter, 6000000);', ' String [] expected = {"the", "edu", "to", "of", "and",', ' "in", "is", "ax", "that", "it",', ' "cmu", "for", "com", "you", "cs"};', ' checkExpected(counter, 0, expected);', ' }', '', '}'] | [{'reason_category': 'If Body', 'usage_line': 234}, {'reason_category': 'Loop Body', 'usage_line': 234}, {'reason_category': 'if Body', 'usage_line': 235}, {'reason_category': 'Loop Body', 'usage_line': 235}] | null | {'If Body': 1, 'Loop Body': 2} | null |
infilling_java | CounterTester | 230 | 238 | ['import junit.framework.TestCase;', 'import java.io.*;', 'import java.util.HashMap;', 'import java.util.TreeMap;', 'import java.util.ArrayList;', '', '/**', ' * This silly little class wraps String, int pairs so they can be sorted.', ' * Used by the WordCounter class.', ' */', 'class WordWrapper implements Comparable <WordWrapper> {', '', ' private String myWord;', ' private int myCount;', ' private int mySlot;', '', ' /**', ' * Creates a new WordWrapper with string "XXX" and count zero.', ' */', ' public WordWrapper (String myWordIn, int myCountIn, int mySlotIn) {', ' myWord = myWordIn;', ' myCount = myCountIn;', ' mySlot = mySlotIn;', ' }', ' /**', ' * Returns a copy of the string in the WordWrapper.', ' *', ' * @return The word contained in this object. Is copied out: no aliasing.', ' */', ' public String extractWord () {', ' return new String (myWord);', ' }', '', ' /**', ' * Returns the count in this WordWrapper.', ' *', ' * @return The count contained in the object.', ' */', ' public int extractCount () {', ' return myCount;', ' }', '', ' public void incCount () {', ' myCount++;', ' }', '', ' public int getCount () {', ' return myCount;', ' }', '', ' public int getPos () {', ' return mySlot;', ' }', '', ' public void setPos (int toWhat) {', ' ', ' mySlot = toWhat;', ' }', '', ' public String toString () {', ' return myWord + " " + mySlot;', ' }', '', ' /**', ' * Comparison operator so we implement the Comparable interface.', ' *', ' * @param w The word wrapper to compare to', ' * @return a positive, zero, or negative value depending upon whether this', ' * word wrapper is less then, equal to, or greater than param w. The', ' * relationship is determied by looking at the counts.', ' */', ' public int compareTo (WordWrapper w) {', " // Check if the count of the current word (myCount) is equal to the count of the word 'w'", ' // If the counts are equal, compare the words lexicographically', ' if (w.myCount == myCount) {', ' return myWord.compareTo(w.myWord);', ' }', " // If the counts are not equal, subtract the count of the current word from the count of the word 'w'", ' return w.myCount - myCount;', ' }', '}', '', '', '/**', ' * This class is used to count occurences of words (strings) in a corpus. Used by', ' * the IndexedDocumentCollection class to find the most frequent words in the corpus.', ' */', '', 'class WordCounter {', ' ', " // this is the map that holds (for each word) the number of times we've seen it", ' // note that Integer is a wrapper for the buitin Java int type', ' private HashMap <String, WordWrapper> wordsIHaveSeen = new HashMap <String, WordWrapper> ();', ' private TreeMap <String, String> ones = new TreeMap <String, String> ();', ' ', ' // the set of words that have been extracted', ' private ArrayList<WordWrapper> extractedWords = new ArrayList <WordWrapper> ();', '', ' /**', ' * Accepts a word and increments the count of the number of times we have seen it.', ' * Note that a deep copy of the param is done (no aliasing).', ' *', ' * @param addMe The string to count', ' */', ' public void insert (String addMe) {', ' if (ones.containsKey (addMe)) {', ' ones.remove (addMe);', ' WordWrapper temp = new WordWrapper (addMe, 1, extractedWords.size ());', ' wordsIHaveSeen.put(addMe, temp);', ' extractedWords.add (temp);', ' }', '', ' // first check to see if the word is alredy in wordsIHaveSeen', ' if (wordsIHaveSeen.containsKey (addMe)) {', ' // if it is, then remove and increment its count', ' WordWrapper temp = wordsIHaveSeen.get (addMe);', ' temp.incCount ();', '', ' // find the slot that we go to in the extractedWords list', " // by sorting the 'extractedWords' list in ascending order", ' for (int i = temp.getPos () - 1; i >= 0 && ', ' extractedWords.get (i).compareTo (extractedWords.get (i + 1)) > 0; i--) {', ' temp = extractedWords.get (i + 1);', ' temp.setPos (i);', ' ', ' WordWrapper temp2 = extractedWords.get (i);', ' temp2.setPos (i + 1);', ' ', ' extractedWords.set (i + 1, temp2);', ' extractedWords.set (i, temp);', ' }', '', ' // in this case it is not there, so just add it', ' } else {', ' ones.put (addMe, addMe);', ' }', ' }', '', ' /**', ' * Returns the kth most frequent word in the corpus so far. A deep copy is returned,', ' * so no aliasing is possible. Returns null if there are not enough words.', ' *', ' * @param k Note that the most frequent word is at k = 0', ' * @return The kth most frequent word in the corpus to date', ' */', ' public String getKthMostFrequent (int k) {', '', ' // if we got here, then the array is all set up, so just return the kth most frequent word', ' if (k >= extractedWords.size ()) {', ' int which = extractedWords.size ();', ' for (String s : ones.navigableKeySet ()) {', ' if (which == k)', ' return s;', ' which++;', ' }', ' return null;', ' } else {', ' // If k is less than the size of the extractedWords list,', ' // return the kth most frequent word from extractedWords', ' return extractedWords.get (k).extractWord ();', ' }', ' }', '}', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class CounterTester extends TestCase {', '', ' /**', ' * File object to read words from, with buffering.', ' */', ' private FileReader file = null;', ' private BufferedReader reader = null;', '', ' /**', ' * Close file readers.', ' */', ' private void closeFiles() {', ' try {', ' if (file != null) {', ' file.close();', ' file = null;', ' }', ' if (reader != null) {', ' reader.close();', ' reader = null;', ' }', ' } catch (Exception e) {', ' System.err.println("Problem closing file");', ' System.err.println(e);', ' e.printStackTrace();', ' }', ' }', '', ' /**', ' * Close files no matter what happens in the test.', ' */', ' protected void tearDown () {', ' closeFiles();', ' }', '', ' /**', ' * Open file and set up readers.', ' *', ' * @param fileName name of file to open', ' * */', ' private void openFile(String fileName) {', ' try {', ' file = new FileReader(fileName);', ' reader = new BufferedReader(file);', ' } catch (Exception e) {', ' System.err.format("Problem opening %s file\\n", fileName);', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Read the next numWords from the file.', ' *', ' * @param counter word counter to update', ' * @param numWords number of words to read.', ' */', ' private void readWords(WordCounter counter, int numWords) {', ' try {', ' for (int i=0; i<numWords; i++) {'] | [' if (i % 100000 == 0)', ' System.out.print (".");', ' String word = reader.readLine();', ' if (word == null) {', ' return;', ' }', " // Insert 'word' into the counter.", ' counter.insert(word);', ' }'] | [' } catch (Exception e) {', ' System.err.println("Problem reading file");', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Read the next numWords from the file, mixing with queries', ' *', ' * @param counter word counter to update', ' * @param numWords number of words to read.', ' */', ' private void readWordsMixed (WordCounter counter, int numWords) {', ' try {', ' int j = 0;', ' for (int i=0; i<numWords; i++) {', ' String word = reader.readLine();', " // If 'word' is null, it means we've reached the end of the file. So, return from the method.", ' if (word == null) {', ' return;', ' }', ' counter.insert(word);', '', ' // If the current iteration number is a multiple of 10 and greater than 100,000, perform a query of the kth most frequent word.', ' if (i % 10 == 0 && i > 100000) {', ' String myStr = counter.getKthMostFrequent(j++);', ' }', '', ' // rest j once we get to 100', ' if (j == 100)', ' j = 0;', ' }', ' } catch (Exception e) {', ' System.err.println("Problem reading file");', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Check that a sequence of words starts at the "start"th most', ' * frequent word.', ' *', ' * @param counter word counter to lookup', ' * @param start frequency index to start checking at', ' * @param expected array of expected words that start at that frequency', ' */', ' private void checkExpected(WordCounter counter, int start, String [] expected) {', ' for (int i = 0; i<expected.length; i++) {', ' String actual = counter.getKthMostFrequent(start);', ' System.out.format("k: %d, expected: %s, actual: %s\\n",', ' start, expected[i], actual);', ' assertEquals(expected[i], actual);', ' start++;', ' }', ' }', '', ' /**', ' * A test method.', ' * (Replace "X" with a name describing the test. You may write as', ' * many "testSomething" methods in this class as you wish, and each', ' * one will be called when running JUnit over this class.)', ' */', ' public void testSimple() {', ' System.out.println("\\nChecking insert");', ' WordCounter counter = new WordCounter();', ' counter.insert("pizzaz");', ' // Insert the word "pizza" into the counter twice', ' counter.insert("pizza");', ' counter.insert("pizza");', ' String [] expected = {"pizza"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void testTie() {', ' System.out.println("\\nChecking tie for 2nd place");', ' WordCounter counter = new WordCounter();', ' counter.insert("panache");', ' counter.insert("pizzaz");', ' counter.insert("pizza");', ' counter.insert("zebra");', ' counter.insert("pizza");', ' counter.insert("lion");', ' counter.insert("pizzaz");', ' counter.insert("panache");', ' counter.insert("panache");', ' counter.insert("camel");', ' // order is important here', ' String [] expected = {"pizza", "pizzaz"};', ' checkExpected(counter, 1, expected);', ' }', '', '', ' public void testPastTheEnd() {', ' System.out.println("\\nChecking past the end");', ' WordCounter counter = new WordCounter();', ' counter.insert("hi");', ' counter.insert("hello");', ' counter.insert("greetings");', ' counter.insert("salutations");', ' counter.insert("hi");', ' counter.insert("welcome");', ' counter.insert("goodbye");', ' counter.insert("later");', ' counter.insert("hello");', ' counter.insert("when");', ' counter.insert("hi");', ' assertNull(counter.getKthMostFrequent(8));', ' }', '', ' public void test100Top5() {', ' System.out.println("\\nChecking top 5 of 100 words");', ' WordCounter counter = new WordCounter();', ' // Open the file "allWordsBig"', ' openFile("allWordsBig");', ' // Read the next 100 words', ' readWords(counter, 100);', ' String [] expected = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void test300Top5() {', ' System.out.println("\\nChecking top 5 of first 100 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 100);', ' String [] expected1 = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter, 0, expected1);', '', ' System.out.println("Adding 100 more words and rechecking top 5");', ' readWords(counter, 100);', ' String [] expected2 = {"edu", "cmu", "comp", "cs", "state"};', ' checkExpected(counter, 0, expected2);', '', ' System.out.println("Adding 100 more words and rechecking top 5");', ' readWords(counter, 100);', ' String [] expected3 = {"edu", "cmu", "comp", "ohio", "state"};', ' checkExpected(counter, 0, expected3);', ' }', '', ' public void test300Words14Thru19() {', ' System.out.println("\\nChecking rank 14 through 19 of 300 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' // Read the next 300 words', ' readWords(counter, 300);', ' String [] expected = {"cantaloupe", "from", "ksu", "okstate", "on", "srv"};', ' checkExpected(counter, 14, expected);', ' }', '', ' public void test300CorrectNumber() {', ' System.out.println("\\nChecking correct number of unique words in 300 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 300);', ' /* check the 122th, 123th, and 124th most frequent word in the corpus so far ', ' * and check if the result is not null.', ' */', ' assertNotNull(counter.getKthMostFrequent(122));', ' assertNotNull(counter.getKthMostFrequent(123));', ' assertNotNull(counter.getKthMostFrequent(124));', ' // check the 125th most frequent word in the corpus so far', ' // and check if the result is null.', ' assertNull(counter.getKthMostFrequent(125));', ' }', '', ' public void test300and100() {', ' System.out.println("\\nChecking top 5 of 100 and 300 words with two counters");', ' WordCounter counter1 = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter1, 300);', ' closeFiles();', '', ' WordCounter counter2 = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter2, 100);', '', ' String [] expected1 = {"edu", "cmu", "comp", "ohio", "state"};', ' checkExpected(counter1, 0, expected1);', '', ' String [] expected2 = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter2, 0, expected2);', ' }', '', ' public void testAllTop15() {', ' System.out.println("\\nChecking top 15 of all words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' // Read the next 6000000 words', ' readWords(counter, 6000000);', ' String [] expected = {"the", "edu", "to", "of", "and",', ' "in", "is", "ax", "that", "it",', ' "cmu", "for", "com", "you", "cs"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void testAllTop10000() {', ' System.out.println("\\nChecking time to get top 10000 of all words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 6000000);', '', ' for (int i=0; i<10000; i++) {', ' counter.getKthMostFrequent(i);', ' }', ' }', '', ' public void testSpeed() {', ' System.out.println("\\nMixing adding data with finding top k");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWordsMixed (counter, 6000000);', ' String [] expected = {"the", "edu", "to", "of", "and",', ' "in", "is", "ax", "that", "it",', ' "cmu", "for", "com", "you", "cs"};', ' checkExpected(counter, 0, expected);', ' }', '', '}'] | [{'reason_category': 'Loop Body', 'usage_line': 230}, {'reason_category': 'If Condition', 'usage_line': 230}, {'reason_category': 'If Body', 'usage_line': 231}, {'reason_category': 'Loop Body', 'usage_line': 231}, {'reason_category': 'Loop Body', 'usage_line': 232}, {'reason_category': 'If Condition', 'usage_line': 233}, {'reason_category': 'Loop Body', 'usage_line': 233}, {'reason_category': 'If Body', 'usage_line': 234}, {'reason_category': 'Loop Body', 'usage_line': 234}, {'reason_category': 'if Body', 'usage_line': 235}, {'reason_category': 'Loop Body', 'usage_line': 235}, {'reason_category': 'Loop Body', 'usage_line': 236}, {'reason_category': 'Loop Body', 'usage_line': 237}, {'reason_category': 'Loop Body', 'usage_line': 238}] | Variable 'i' used at line 230 is defined at line 229 and has a Short-Range dependency.
Global_Variable 'reader' used at line 232 is defined at line 175 and has a Long-Range dependency.
Variable 'word' used at line 233 is defined at line 232 and has a Short-Range dependency.
Variable 'counter' used at line 237 is defined at line 227 and has a Short-Range dependency.
Variable 'word' used at line 237 is defined at line 232 and has a Short-Range dependency. | {'Loop Body': 9, 'If Condition': 2, 'If Body': 2} | {'Variable Short-Range': 4, 'Global_Variable Long-Range': 1} |
infilling_java | CounterTester | 260 | 261 | ['import junit.framework.TestCase;', 'import java.io.*;', 'import java.util.HashMap;', 'import java.util.TreeMap;', 'import java.util.ArrayList;', '', '/**', ' * This silly little class wraps String, int pairs so they can be sorted.', ' * Used by the WordCounter class.', ' */', 'class WordWrapper implements Comparable <WordWrapper> {', '', ' private String myWord;', ' private int myCount;', ' private int mySlot;', '', ' /**', ' * Creates a new WordWrapper with string "XXX" and count zero.', ' */', ' public WordWrapper (String myWordIn, int myCountIn, int mySlotIn) {', ' myWord = myWordIn;', ' myCount = myCountIn;', ' mySlot = mySlotIn;', ' }', ' /**', ' * Returns a copy of the string in the WordWrapper.', ' *', ' * @return The word contained in this object. Is copied out: no aliasing.', ' */', ' public String extractWord () {', ' return new String (myWord);', ' }', '', ' /**', ' * Returns the count in this WordWrapper.', ' *', ' * @return The count contained in the object.', ' */', ' public int extractCount () {', ' return myCount;', ' }', '', ' public void incCount () {', ' myCount++;', ' }', '', ' public int getCount () {', ' return myCount;', ' }', '', ' public int getPos () {', ' return mySlot;', ' }', '', ' public void setPos (int toWhat) {', ' ', ' mySlot = toWhat;', ' }', '', ' public String toString () {', ' return myWord + " " + mySlot;', ' }', '', ' /**', ' * Comparison operator so we implement the Comparable interface.', ' *', ' * @param w The word wrapper to compare to', ' * @return a positive, zero, or negative value depending upon whether this', ' * word wrapper is less then, equal to, or greater than param w. The', ' * relationship is determied by looking at the counts.', ' */', ' public int compareTo (WordWrapper w) {', " // Check if the count of the current word (myCount) is equal to the count of the word 'w'", ' // If the counts are equal, compare the words lexicographically', ' if (w.myCount == myCount) {', ' return myWord.compareTo(w.myWord);', ' }', " // If the counts are not equal, subtract the count of the current word from the count of the word 'w'", ' return w.myCount - myCount;', ' }', '}', '', '', '/**', ' * This class is used to count occurences of words (strings) in a corpus. Used by', ' * the IndexedDocumentCollection class to find the most frequent words in the corpus.', ' */', '', 'class WordCounter {', ' ', " // this is the map that holds (for each word) the number of times we've seen it", ' // note that Integer is a wrapper for the buitin Java int type', ' private HashMap <String, WordWrapper> wordsIHaveSeen = new HashMap <String, WordWrapper> ();', ' private TreeMap <String, String> ones = new TreeMap <String, String> ();', ' ', ' // the set of words that have been extracted', ' private ArrayList<WordWrapper> extractedWords = new ArrayList <WordWrapper> ();', '', ' /**', ' * Accepts a word and increments the count of the number of times we have seen it.', ' * Note that a deep copy of the param is done (no aliasing).', ' *', ' * @param addMe The string to count', ' */', ' public void insert (String addMe) {', ' if (ones.containsKey (addMe)) {', ' ones.remove (addMe);', ' WordWrapper temp = new WordWrapper (addMe, 1, extractedWords.size ());', ' wordsIHaveSeen.put(addMe, temp);', ' extractedWords.add (temp);', ' }', '', ' // first check to see if the word is alredy in wordsIHaveSeen', ' if (wordsIHaveSeen.containsKey (addMe)) {', ' // if it is, then remove and increment its count', ' WordWrapper temp = wordsIHaveSeen.get (addMe);', ' temp.incCount ();', '', ' // find the slot that we go to in the extractedWords list', " // by sorting the 'extractedWords' list in ascending order", ' for (int i = temp.getPos () - 1; i >= 0 && ', ' extractedWords.get (i).compareTo (extractedWords.get (i + 1)) > 0; i--) {', ' temp = extractedWords.get (i + 1);', ' temp.setPos (i);', ' ', ' WordWrapper temp2 = extractedWords.get (i);', ' temp2.setPos (i + 1);', ' ', ' extractedWords.set (i + 1, temp2);', ' extractedWords.set (i, temp);', ' }', '', ' // in this case it is not there, so just add it', ' } else {', ' ones.put (addMe, addMe);', ' }', ' }', '', ' /**', ' * Returns the kth most frequent word in the corpus so far. A deep copy is returned,', ' * so no aliasing is possible. Returns null if there are not enough words.', ' *', ' * @param k Note that the most frequent word is at k = 0', ' * @return The kth most frequent word in the corpus to date', ' */', ' public String getKthMostFrequent (int k) {', '', ' // if we got here, then the array is all set up, so just return the kth most frequent word', ' if (k >= extractedWords.size ()) {', ' int which = extractedWords.size ();', ' for (String s : ones.navigableKeySet ()) {', ' if (which == k)', ' return s;', ' which++;', ' }', ' return null;', ' } else {', ' // If k is less than the size of the extractedWords list,', ' // return the kth most frequent word from extractedWords', ' return extractedWords.get (k).extractWord ();', ' }', ' }', '}', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class CounterTester extends TestCase {', '', ' /**', ' * File object to read words from, with buffering.', ' */', ' private FileReader file = null;', ' private BufferedReader reader = null;', '', ' /**', ' * Close file readers.', ' */', ' private void closeFiles() {', ' try {', ' if (file != null) {', ' file.close();', ' file = null;', ' }', ' if (reader != null) {', ' reader.close();', ' reader = null;', ' }', ' } catch (Exception e) {', ' System.err.println("Problem closing file");', ' System.err.println(e);', ' e.printStackTrace();', ' }', ' }', '', ' /**', ' * Close files no matter what happens in the test.', ' */', ' protected void tearDown () {', ' closeFiles();', ' }', '', ' /**', ' * Open file and set up readers.', ' *', ' * @param fileName name of file to open', ' * */', ' private void openFile(String fileName) {', ' try {', ' file = new FileReader(fileName);', ' reader = new BufferedReader(file);', ' } catch (Exception e) {', ' System.err.format("Problem opening %s file\\n", fileName);', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Read the next numWords from the file.', ' *', ' * @param counter word counter to update', ' * @param numWords number of words to read.', ' */', ' private void readWords(WordCounter counter, int numWords) {', ' try {', ' for (int i=0; i<numWords; i++) {', ' if (i % 100000 == 0)', ' System.out.print (".");', ' String word = reader.readLine();', ' if (word == null) {', ' return;', ' }', " // Insert 'word' into the counter.", ' counter.insert(word);', ' }', ' } catch (Exception e) {', ' System.err.println("Problem reading file");', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Read the next numWords from the file, mixing with queries', ' *', ' * @param counter word counter to update', ' * @param numWords number of words to read.', ' */', ' private void readWordsMixed (WordCounter counter, int numWords) {', ' try {', ' int j = 0;', ' for (int i=0; i<numWords; i++) {', ' String word = reader.readLine();', " // If 'word' is null, it means we've reached the end of the file. So, return from the method.", ' if (word == null) {'] | [' return;', ' }'] | [' counter.insert(word);', '', ' // If the current iteration number is a multiple of 10 and greater than 100,000, perform a query of the kth most frequent word.', ' if (i % 10 == 0 && i > 100000) {', ' String myStr = counter.getKthMostFrequent(j++);', ' }', '', ' // rest j once we get to 100', ' if (j == 100)', ' j = 0;', ' }', ' } catch (Exception e) {', ' System.err.println("Problem reading file");', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Check that a sequence of words starts at the "start"th most', ' * frequent word.', ' *', ' * @param counter word counter to lookup', ' * @param start frequency index to start checking at', ' * @param expected array of expected words that start at that frequency', ' */', ' private void checkExpected(WordCounter counter, int start, String [] expected) {', ' for (int i = 0; i<expected.length; i++) {', ' String actual = counter.getKthMostFrequent(start);', ' System.out.format("k: %d, expected: %s, actual: %s\\n",', ' start, expected[i], actual);', ' assertEquals(expected[i], actual);', ' start++;', ' }', ' }', '', ' /**', ' * A test method.', ' * (Replace "X" with a name describing the test. You may write as', ' * many "testSomething" methods in this class as you wish, and each', ' * one will be called when running JUnit over this class.)', ' */', ' public void testSimple() {', ' System.out.println("\\nChecking insert");', ' WordCounter counter = new WordCounter();', ' counter.insert("pizzaz");', ' // Insert the word "pizza" into the counter twice', ' counter.insert("pizza");', ' counter.insert("pizza");', ' String [] expected = {"pizza"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void testTie() {', ' System.out.println("\\nChecking tie for 2nd place");', ' WordCounter counter = new WordCounter();', ' counter.insert("panache");', ' counter.insert("pizzaz");', ' counter.insert("pizza");', ' counter.insert("zebra");', ' counter.insert("pizza");', ' counter.insert("lion");', ' counter.insert("pizzaz");', ' counter.insert("panache");', ' counter.insert("panache");', ' counter.insert("camel");', ' // order is important here', ' String [] expected = {"pizza", "pizzaz"};', ' checkExpected(counter, 1, expected);', ' }', '', '', ' public void testPastTheEnd() {', ' System.out.println("\\nChecking past the end");', ' WordCounter counter = new WordCounter();', ' counter.insert("hi");', ' counter.insert("hello");', ' counter.insert("greetings");', ' counter.insert("salutations");', ' counter.insert("hi");', ' counter.insert("welcome");', ' counter.insert("goodbye");', ' counter.insert("later");', ' counter.insert("hello");', ' counter.insert("when");', ' counter.insert("hi");', ' assertNull(counter.getKthMostFrequent(8));', ' }', '', ' public void test100Top5() {', ' System.out.println("\\nChecking top 5 of 100 words");', ' WordCounter counter = new WordCounter();', ' // Open the file "allWordsBig"', ' openFile("allWordsBig");', ' // Read the next 100 words', ' readWords(counter, 100);', ' String [] expected = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void test300Top5() {', ' System.out.println("\\nChecking top 5 of first 100 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 100);', ' String [] expected1 = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter, 0, expected1);', '', ' System.out.println("Adding 100 more words and rechecking top 5");', ' readWords(counter, 100);', ' String [] expected2 = {"edu", "cmu", "comp", "cs", "state"};', ' checkExpected(counter, 0, expected2);', '', ' System.out.println("Adding 100 more words and rechecking top 5");', ' readWords(counter, 100);', ' String [] expected3 = {"edu", "cmu", "comp", "ohio", "state"};', ' checkExpected(counter, 0, expected3);', ' }', '', ' public void test300Words14Thru19() {', ' System.out.println("\\nChecking rank 14 through 19 of 300 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' // Read the next 300 words', ' readWords(counter, 300);', ' String [] expected = {"cantaloupe", "from", "ksu", "okstate", "on", "srv"};', ' checkExpected(counter, 14, expected);', ' }', '', ' public void test300CorrectNumber() {', ' System.out.println("\\nChecking correct number of unique words in 300 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 300);', ' /* check the 122th, 123th, and 124th most frequent word in the corpus so far ', ' * and check if the result is not null.', ' */', ' assertNotNull(counter.getKthMostFrequent(122));', ' assertNotNull(counter.getKthMostFrequent(123));', ' assertNotNull(counter.getKthMostFrequent(124));', ' // check the 125th most frequent word in the corpus so far', ' // and check if the result is null.', ' assertNull(counter.getKthMostFrequent(125));', ' }', '', ' public void test300and100() {', ' System.out.println("\\nChecking top 5 of 100 and 300 words with two counters");', ' WordCounter counter1 = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter1, 300);', ' closeFiles();', '', ' WordCounter counter2 = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter2, 100);', '', ' String [] expected1 = {"edu", "cmu", "comp", "ohio", "state"};', ' checkExpected(counter1, 0, expected1);', '', ' String [] expected2 = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter2, 0, expected2);', ' }', '', ' public void testAllTop15() {', ' System.out.println("\\nChecking top 15 of all words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' // Read the next 6000000 words', ' readWords(counter, 6000000);', ' String [] expected = {"the", "edu", "to", "of", "and",', ' "in", "is", "ax", "that", "it",', ' "cmu", "for", "com", "you", "cs"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void testAllTop10000() {', ' System.out.println("\\nChecking time to get top 10000 of all words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 6000000);', '', ' for (int i=0; i<10000; i++) {', ' counter.getKthMostFrequent(i);', ' }', ' }', '', ' public void testSpeed() {', ' System.out.println("\\nMixing adding data with finding top k");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWordsMixed (counter, 6000000);', ' String [] expected = {"the", "edu", "to", "of", "and",', ' "in", "is", "ax", "that", "it",', ' "cmu", "for", "com", "you", "cs"};', ' checkExpected(counter, 0, expected);', ' }', '', '}'] | [{'reason_category': 'Loop Body', 'usage_line': 260}, {'reason_category': 'If Body', 'usage_line': 260}, {'reason_category': 'Loop Body', 'usage_line': 261}, {'reason_category': 'If Body', 'usage_line': 261}] | null | {'Loop Body': 2, 'If Body': 2} | null |
infilling_java | CounterTester | 266 | 267 | ['import junit.framework.TestCase;', 'import java.io.*;', 'import java.util.HashMap;', 'import java.util.TreeMap;', 'import java.util.ArrayList;', '', '/**', ' * This silly little class wraps String, int pairs so they can be sorted.', ' * Used by the WordCounter class.', ' */', 'class WordWrapper implements Comparable <WordWrapper> {', '', ' private String myWord;', ' private int myCount;', ' private int mySlot;', '', ' /**', ' * Creates a new WordWrapper with string "XXX" and count zero.', ' */', ' public WordWrapper (String myWordIn, int myCountIn, int mySlotIn) {', ' myWord = myWordIn;', ' myCount = myCountIn;', ' mySlot = mySlotIn;', ' }', ' /**', ' * Returns a copy of the string in the WordWrapper.', ' *', ' * @return The word contained in this object. Is copied out: no aliasing.', ' */', ' public String extractWord () {', ' return new String (myWord);', ' }', '', ' /**', ' * Returns the count in this WordWrapper.', ' *', ' * @return The count contained in the object.', ' */', ' public int extractCount () {', ' return myCount;', ' }', '', ' public void incCount () {', ' myCount++;', ' }', '', ' public int getCount () {', ' return myCount;', ' }', '', ' public int getPos () {', ' return mySlot;', ' }', '', ' public void setPos (int toWhat) {', ' ', ' mySlot = toWhat;', ' }', '', ' public String toString () {', ' return myWord + " " + mySlot;', ' }', '', ' /**', ' * Comparison operator so we implement the Comparable interface.', ' *', ' * @param w The word wrapper to compare to', ' * @return a positive, zero, or negative value depending upon whether this', ' * word wrapper is less then, equal to, or greater than param w. The', ' * relationship is determied by looking at the counts.', ' */', ' public int compareTo (WordWrapper w) {', " // Check if the count of the current word (myCount) is equal to the count of the word 'w'", ' // If the counts are equal, compare the words lexicographically', ' if (w.myCount == myCount) {', ' return myWord.compareTo(w.myWord);', ' }', " // If the counts are not equal, subtract the count of the current word from the count of the word 'w'", ' return w.myCount - myCount;', ' }', '}', '', '', '/**', ' * This class is used to count occurences of words (strings) in a corpus. Used by', ' * the IndexedDocumentCollection class to find the most frequent words in the corpus.', ' */', '', 'class WordCounter {', ' ', " // this is the map that holds (for each word) the number of times we've seen it", ' // note that Integer is a wrapper for the buitin Java int type', ' private HashMap <String, WordWrapper> wordsIHaveSeen = new HashMap <String, WordWrapper> ();', ' private TreeMap <String, String> ones = new TreeMap <String, String> ();', ' ', ' // the set of words that have been extracted', ' private ArrayList<WordWrapper> extractedWords = new ArrayList <WordWrapper> ();', '', ' /**', ' * Accepts a word and increments the count of the number of times we have seen it.', ' * Note that a deep copy of the param is done (no aliasing).', ' *', ' * @param addMe The string to count', ' */', ' public void insert (String addMe) {', ' if (ones.containsKey (addMe)) {', ' ones.remove (addMe);', ' WordWrapper temp = new WordWrapper (addMe, 1, extractedWords.size ());', ' wordsIHaveSeen.put(addMe, temp);', ' extractedWords.add (temp);', ' }', '', ' // first check to see if the word is alredy in wordsIHaveSeen', ' if (wordsIHaveSeen.containsKey (addMe)) {', ' // if it is, then remove and increment its count', ' WordWrapper temp = wordsIHaveSeen.get (addMe);', ' temp.incCount ();', '', ' // find the slot that we go to in the extractedWords list', " // by sorting the 'extractedWords' list in ascending order", ' for (int i = temp.getPos () - 1; i >= 0 && ', ' extractedWords.get (i).compareTo (extractedWords.get (i + 1)) > 0; i--) {', ' temp = extractedWords.get (i + 1);', ' temp.setPos (i);', ' ', ' WordWrapper temp2 = extractedWords.get (i);', ' temp2.setPos (i + 1);', ' ', ' extractedWords.set (i + 1, temp2);', ' extractedWords.set (i, temp);', ' }', '', ' // in this case it is not there, so just add it', ' } else {', ' ones.put (addMe, addMe);', ' }', ' }', '', ' /**', ' * Returns the kth most frequent word in the corpus so far. A deep copy is returned,', ' * so no aliasing is possible. Returns null if there are not enough words.', ' *', ' * @param k Note that the most frequent word is at k = 0', ' * @return The kth most frequent word in the corpus to date', ' */', ' public String getKthMostFrequent (int k) {', '', ' // if we got here, then the array is all set up, so just return the kth most frequent word', ' if (k >= extractedWords.size ()) {', ' int which = extractedWords.size ();', ' for (String s : ones.navigableKeySet ()) {', ' if (which == k)', ' return s;', ' which++;', ' }', ' return null;', ' } else {', ' // If k is less than the size of the extractedWords list,', ' // return the kth most frequent word from extractedWords', ' return extractedWords.get (k).extractWord ();', ' }', ' }', '}', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class CounterTester extends TestCase {', '', ' /**', ' * File object to read words from, with buffering.', ' */', ' private FileReader file = null;', ' private BufferedReader reader = null;', '', ' /**', ' * Close file readers.', ' */', ' private void closeFiles() {', ' try {', ' if (file != null) {', ' file.close();', ' file = null;', ' }', ' if (reader != null) {', ' reader.close();', ' reader = null;', ' }', ' } catch (Exception e) {', ' System.err.println("Problem closing file");', ' System.err.println(e);', ' e.printStackTrace();', ' }', ' }', '', ' /**', ' * Close files no matter what happens in the test.', ' */', ' protected void tearDown () {', ' closeFiles();', ' }', '', ' /**', ' * Open file and set up readers.', ' *', ' * @param fileName name of file to open', ' * */', ' private void openFile(String fileName) {', ' try {', ' file = new FileReader(fileName);', ' reader = new BufferedReader(file);', ' } catch (Exception e) {', ' System.err.format("Problem opening %s file\\n", fileName);', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Read the next numWords from the file.', ' *', ' * @param counter word counter to update', ' * @param numWords number of words to read.', ' */', ' private void readWords(WordCounter counter, int numWords) {', ' try {', ' for (int i=0; i<numWords; i++) {', ' if (i % 100000 == 0)', ' System.out.print (".");', ' String word = reader.readLine();', ' if (word == null) {', ' return;', ' }', " // Insert 'word' into the counter.", ' counter.insert(word);', ' }', ' } catch (Exception e) {', ' System.err.println("Problem reading file");', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Read the next numWords from the file, mixing with queries', ' *', ' * @param counter word counter to update', ' * @param numWords number of words to read.', ' */', ' private void readWordsMixed (WordCounter counter, int numWords) {', ' try {', ' int j = 0;', ' for (int i=0; i<numWords; i++) {', ' String word = reader.readLine();', " // If 'word' is null, it means we've reached the end of the file. So, return from the method.", ' if (word == null) {', ' return;', ' }', ' counter.insert(word);', '', ' // If the current iteration number is a multiple of 10 and greater than 100,000, perform a query of the kth most frequent word.', ' if (i % 10 == 0 && i > 100000) {'] | [' String myStr = counter.getKthMostFrequent(j++);', ' }'] | ['', ' // rest j once we get to 100', ' if (j == 100)', ' j = 0;', ' }', ' } catch (Exception e) {', ' System.err.println("Problem reading file");', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Check that a sequence of words starts at the "start"th most', ' * frequent word.', ' *', ' * @param counter word counter to lookup', ' * @param start frequency index to start checking at', ' * @param expected array of expected words that start at that frequency', ' */', ' private void checkExpected(WordCounter counter, int start, String [] expected) {', ' for (int i = 0; i<expected.length; i++) {', ' String actual = counter.getKthMostFrequent(start);', ' System.out.format("k: %d, expected: %s, actual: %s\\n",', ' start, expected[i], actual);', ' assertEquals(expected[i], actual);', ' start++;', ' }', ' }', '', ' /**', ' * A test method.', ' * (Replace "X" with a name describing the test. You may write as', ' * many "testSomething" methods in this class as you wish, and each', ' * one will be called when running JUnit over this class.)', ' */', ' public void testSimple() {', ' System.out.println("\\nChecking insert");', ' WordCounter counter = new WordCounter();', ' counter.insert("pizzaz");', ' // Insert the word "pizza" into the counter twice', ' counter.insert("pizza");', ' counter.insert("pizza");', ' String [] expected = {"pizza"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void testTie() {', ' System.out.println("\\nChecking tie for 2nd place");', ' WordCounter counter = new WordCounter();', ' counter.insert("panache");', ' counter.insert("pizzaz");', ' counter.insert("pizza");', ' counter.insert("zebra");', ' counter.insert("pizza");', ' counter.insert("lion");', ' counter.insert("pizzaz");', ' counter.insert("panache");', ' counter.insert("panache");', ' counter.insert("camel");', ' // order is important here', ' String [] expected = {"pizza", "pizzaz"};', ' checkExpected(counter, 1, expected);', ' }', '', '', ' public void testPastTheEnd() {', ' System.out.println("\\nChecking past the end");', ' WordCounter counter = new WordCounter();', ' counter.insert("hi");', ' counter.insert("hello");', ' counter.insert("greetings");', ' counter.insert("salutations");', ' counter.insert("hi");', ' counter.insert("welcome");', ' counter.insert("goodbye");', ' counter.insert("later");', ' counter.insert("hello");', ' counter.insert("when");', ' counter.insert("hi");', ' assertNull(counter.getKthMostFrequent(8));', ' }', '', ' public void test100Top5() {', ' System.out.println("\\nChecking top 5 of 100 words");', ' WordCounter counter = new WordCounter();', ' // Open the file "allWordsBig"', ' openFile("allWordsBig");', ' // Read the next 100 words', ' readWords(counter, 100);', ' String [] expected = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void test300Top5() {', ' System.out.println("\\nChecking top 5 of first 100 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 100);', ' String [] expected1 = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter, 0, expected1);', '', ' System.out.println("Adding 100 more words and rechecking top 5");', ' readWords(counter, 100);', ' String [] expected2 = {"edu", "cmu", "comp", "cs", "state"};', ' checkExpected(counter, 0, expected2);', '', ' System.out.println("Adding 100 more words and rechecking top 5");', ' readWords(counter, 100);', ' String [] expected3 = {"edu", "cmu", "comp", "ohio", "state"};', ' checkExpected(counter, 0, expected3);', ' }', '', ' public void test300Words14Thru19() {', ' System.out.println("\\nChecking rank 14 through 19 of 300 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' // Read the next 300 words', ' readWords(counter, 300);', ' String [] expected = {"cantaloupe", "from", "ksu", "okstate", "on", "srv"};', ' checkExpected(counter, 14, expected);', ' }', '', ' public void test300CorrectNumber() {', ' System.out.println("\\nChecking correct number of unique words in 300 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 300);', ' /* check the 122th, 123th, and 124th most frequent word in the corpus so far ', ' * and check if the result is not null.', ' */', ' assertNotNull(counter.getKthMostFrequent(122));', ' assertNotNull(counter.getKthMostFrequent(123));', ' assertNotNull(counter.getKthMostFrequent(124));', ' // check the 125th most frequent word in the corpus so far', ' // and check if the result is null.', ' assertNull(counter.getKthMostFrequent(125));', ' }', '', ' public void test300and100() {', ' System.out.println("\\nChecking top 5 of 100 and 300 words with two counters");', ' WordCounter counter1 = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter1, 300);', ' closeFiles();', '', ' WordCounter counter2 = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter2, 100);', '', ' String [] expected1 = {"edu", "cmu", "comp", "ohio", "state"};', ' checkExpected(counter1, 0, expected1);', '', ' String [] expected2 = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter2, 0, expected2);', ' }', '', ' public void testAllTop15() {', ' System.out.println("\\nChecking top 15 of all words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' // Read the next 6000000 words', ' readWords(counter, 6000000);', ' String [] expected = {"the", "edu", "to", "of", "and",', ' "in", "is", "ax", "that", "it",', ' "cmu", "for", "com", "you", "cs"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void testAllTop10000() {', ' System.out.println("\\nChecking time to get top 10000 of all words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 6000000);', '', ' for (int i=0; i<10000; i++) {', ' counter.getKthMostFrequent(i);', ' }', ' }', '', ' public void testSpeed() {', ' System.out.println("\\nMixing adding data with finding top k");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWordsMixed (counter, 6000000);', ' String [] expected = {"the", "edu", "to", "of", "and",', ' "in", "is", "ax", "that", "it",', ' "cmu", "for", "com", "you", "cs"};', ' checkExpected(counter, 0, expected);', ' }', '', '}'] | [{'reason_category': 'Loop Body', 'usage_line': 266}, {'reason_category': 'If Body', 'usage_line': 266}, {'reason_category': 'Loop Body', 'usage_line': 267}, {'reason_category': 'If Body', 'usage_line': 267}] | Variable 'counter' used at line 266 is defined at line 253 and has a Medium-Range dependency.
Variable 'j' used at line 266 is defined at line 255 and has a Medium-Range dependency. | {'Loop Body': 2, 'If Body': 2} | {'Variable Medium-Range': 2} |
infilling_java | CounterTester | 271 | 271 | ['import junit.framework.TestCase;', 'import java.io.*;', 'import java.util.HashMap;', 'import java.util.TreeMap;', 'import java.util.ArrayList;', '', '/**', ' * This silly little class wraps String, int pairs so they can be sorted.', ' * Used by the WordCounter class.', ' */', 'class WordWrapper implements Comparable <WordWrapper> {', '', ' private String myWord;', ' private int myCount;', ' private int mySlot;', '', ' /**', ' * Creates a new WordWrapper with string "XXX" and count zero.', ' */', ' public WordWrapper (String myWordIn, int myCountIn, int mySlotIn) {', ' myWord = myWordIn;', ' myCount = myCountIn;', ' mySlot = mySlotIn;', ' }', ' /**', ' * Returns a copy of the string in the WordWrapper.', ' *', ' * @return The word contained in this object. Is copied out: no aliasing.', ' */', ' public String extractWord () {', ' return new String (myWord);', ' }', '', ' /**', ' * Returns the count in this WordWrapper.', ' *', ' * @return The count contained in the object.', ' */', ' public int extractCount () {', ' return myCount;', ' }', '', ' public void incCount () {', ' myCount++;', ' }', '', ' public int getCount () {', ' return myCount;', ' }', '', ' public int getPos () {', ' return mySlot;', ' }', '', ' public void setPos (int toWhat) {', ' ', ' mySlot = toWhat;', ' }', '', ' public String toString () {', ' return myWord + " " + mySlot;', ' }', '', ' /**', ' * Comparison operator so we implement the Comparable interface.', ' *', ' * @param w The word wrapper to compare to', ' * @return a positive, zero, or negative value depending upon whether this', ' * word wrapper is less then, equal to, or greater than param w. The', ' * relationship is determied by looking at the counts.', ' */', ' public int compareTo (WordWrapper w) {', " // Check if the count of the current word (myCount) is equal to the count of the word 'w'", ' // If the counts are equal, compare the words lexicographically', ' if (w.myCount == myCount) {', ' return myWord.compareTo(w.myWord);', ' }', " // If the counts are not equal, subtract the count of the current word from the count of the word 'w'", ' return w.myCount - myCount;', ' }', '}', '', '', '/**', ' * This class is used to count occurences of words (strings) in a corpus. Used by', ' * the IndexedDocumentCollection class to find the most frequent words in the corpus.', ' */', '', 'class WordCounter {', ' ', " // this is the map that holds (for each word) the number of times we've seen it", ' // note that Integer is a wrapper for the buitin Java int type', ' private HashMap <String, WordWrapper> wordsIHaveSeen = new HashMap <String, WordWrapper> ();', ' private TreeMap <String, String> ones = new TreeMap <String, String> ();', ' ', ' // the set of words that have been extracted', ' private ArrayList<WordWrapper> extractedWords = new ArrayList <WordWrapper> ();', '', ' /**', ' * Accepts a word and increments the count of the number of times we have seen it.', ' * Note that a deep copy of the param is done (no aliasing).', ' *', ' * @param addMe The string to count', ' */', ' public void insert (String addMe) {', ' if (ones.containsKey (addMe)) {', ' ones.remove (addMe);', ' WordWrapper temp = new WordWrapper (addMe, 1, extractedWords.size ());', ' wordsIHaveSeen.put(addMe, temp);', ' extractedWords.add (temp);', ' }', '', ' // first check to see if the word is alredy in wordsIHaveSeen', ' if (wordsIHaveSeen.containsKey (addMe)) {', ' // if it is, then remove and increment its count', ' WordWrapper temp = wordsIHaveSeen.get (addMe);', ' temp.incCount ();', '', ' // find the slot that we go to in the extractedWords list', " // by sorting the 'extractedWords' list in ascending order", ' for (int i = temp.getPos () - 1; i >= 0 && ', ' extractedWords.get (i).compareTo (extractedWords.get (i + 1)) > 0; i--) {', ' temp = extractedWords.get (i + 1);', ' temp.setPos (i);', ' ', ' WordWrapper temp2 = extractedWords.get (i);', ' temp2.setPos (i + 1);', ' ', ' extractedWords.set (i + 1, temp2);', ' extractedWords.set (i, temp);', ' }', '', ' // in this case it is not there, so just add it', ' } else {', ' ones.put (addMe, addMe);', ' }', ' }', '', ' /**', ' * Returns the kth most frequent word in the corpus so far. A deep copy is returned,', ' * so no aliasing is possible. Returns null if there are not enough words.', ' *', ' * @param k Note that the most frequent word is at k = 0', ' * @return The kth most frequent word in the corpus to date', ' */', ' public String getKthMostFrequent (int k) {', '', ' // if we got here, then the array is all set up, so just return the kth most frequent word', ' if (k >= extractedWords.size ()) {', ' int which = extractedWords.size ();', ' for (String s : ones.navigableKeySet ()) {', ' if (which == k)', ' return s;', ' which++;', ' }', ' return null;', ' } else {', ' // If k is less than the size of the extractedWords list,', ' // return the kth most frequent word from extractedWords', ' return extractedWords.get (k).extractWord ();', ' }', ' }', '}', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class CounterTester extends TestCase {', '', ' /**', ' * File object to read words from, with buffering.', ' */', ' private FileReader file = null;', ' private BufferedReader reader = null;', '', ' /**', ' * Close file readers.', ' */', ' private void closeFiles() {', ' try {', ' if (file != null) {', ' file.close();', ' file = null;', ' }', ' if (reader != null) {', ' reader.close();', ' reader = null;', ' }', ' } catch (Exception e) {', ' System.err.println("Problem closing file");', ' System.err.println(e);', ' e.printStackTrace();', ' }', ' }', '', ' /**', ' * Close files no matter what happens in the test.', ' */', ' protected void tearDown () {', ' closeFiles();', ' }', '', ' /**', ' * Open file and set up readers.', ' *', ' * @param fileName name of file to open', ' * */', ' private void openFile(String fileName) {', ' try {', ' file = new FileReader(fileName);', ' reader = new BufferedReader(file);', ' } catch (Exception e) {', ' System.err.format("Problem opening %s file\\n", fileName);', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Read the next numWords from the file.', ' *', ' * @param counter word counter to update', ' * @param numWords number of words to read.', ' */', ' private void readWords(WordCounter counter, int numWords) {', ' try {', ' for (int i=0; i<numWords; i++) {', ' if (i % 100000 == 0)', ' System.out.print (".");', ' String word = reader.readLine();', ' if (word == null) {', ' return;', ' }', " // Insert 'word' into the counter.", ' counter.insert(word);', ' }', ' } catch (Exception e) {', ' System.err.println("Problem reading file");', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Read the next numWords from the file, mixing with queries', ' *', ' * @param counter word counter to update', ' * @param numWords number of words to read.', ' */', ' private void readWordsMixed (WordCounter counter, int numWords) {', ' try {', ' int j = 0;', ' for (int i=0; i<numWords; i++) {', ' String word = reader.readLine();', " // If 'word' is null, it means we've reached the end of the file. So, return from the method.", ' if (word == null) {', ' return;', ' }', ' counter.insert(word);', '', ' // If the current iteration number is a multiple of 10 and greater than 100,000, perform a query of the kth most frequent word.', ' if (i % 10 == 0 && i > 100000) {', ' String myStr = counter.getKthMostFrequent(j++);', ' }', '', ' // rest j once we get to 100', ' if (j == 100)'] | [' j = 0;'] | [' }', ' } catch (Exception e) {', ' System.err.println("Problem reading file");', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Check that a sequence of words starts at the "start"th most', ' * frequent word.', ' *', ' * @param counter word counter to lookup', ' * @param start frequency index to start checking at', ' * @param expected array of expected words that start at that frequency', ' */', ' private void checkExpected(WordCounter counter, int start, String [] expected) {', ' for (int i = 0; i<expected.length; i++) {', ' String actual = counter.getKthMostFrequent(start);', ' System.out.format("k: %d, expected: %s, actual: %s\\n",', ' start, expected[i], actual);', ' assertEquals(expected[i], actual);', ' start++;', ' }', ' }', '', ' /**', ' * A test method.', ' * (Replace "X" with a name describing the test. You may write as', ' * many "testSomething" methods in this class as you wish, and each', ' * one will be called when running JUnit over this class.)', ' */', ' public void testSimple() {', ' System.out.println("\\nChecking insert");', ' WordCounter counter = new WordCounter();', ' counter.insert("pizzaz");', ' // Insert the word "pizza" into the counter twice', ' counter.insert("pizza");', ' counter.insert("pizza");', ' String [] expected = {"pizza"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void testTie() {', ' System.out.println("\\nChecking tie for 2nd place");', ' WordCounter counter = new WordCounter();', ' counter.insert("panache");', ' counter.insert("pizzaz");', ' counter.insert("pizza");', ' counter.insert("zebra");', ' counter.insert("pizza");', ' counter.insert("lion");', ' counter.insert("pizzaz");', ' counter.insert("panache");', ' counter.insert("panache");', ' counter.insert("camel");', ' // order is important here', ' String [] expected = {"pizza", "pizzaz"};', ' checkExpected(counter, 1, expected);', ' }', '', '', ' public void testPastTheEnd() {', ' System.out.println("\\nChecking past the end");', ' WordCounter counter = new WordCounter();', ' counter.insert("hi");', ' counter.insert("hello");', ' counter.insert("greetings");', ' counter.insert("salutations");', ' counter.insert("hi");', ' counter.insert("welcome");', ' counter.insert("goodbye");', ' counter.insert("later");', ' counter.insert("hello");', ' counter.insert("when");', ' counter.insert("hi");', ' assertNull(counter.getKthMostFrequent(8));', ' }', '', ' public void test100Top5() {', ' System.out.println("\\nChecking top 5 of 100 words");', ' WordCounter counter = new WordCounter();', ' // Open the file "allWordsBig"', ' openFile("allWordsBig");', ' // Read the next 100 words', ' readWords(counter, 100);', ' String [] expected = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void test300Top5() {', ' System.out.println("\\nChecking top 5 of first 100 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 100);', ' String [] expected1 = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter, 0, expected1);', '', ' System.out.println("Adding 100 more words and rechecking top 5");', ' readWords(counter, 100);', ' String [] expected2 = {"edu", "cmu", "comp", "cs", "state"};', ' checkExpected(counter, 0, expected2);', '', ' System.out.println("Adding 100 more words and rechecking top 5");', ' readWords(counter, 100);', ' String [] expected3 = {"edu", "cmu", "comp", "ohio", "state"};', ' checkExpected(counter, 0, expected3);', ' }', '', ' public void test300Words14Thru19() {', ' System.out.println("\\nChecking rank 14 through 19 of 300 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' // Read the next 300 words', ' readWords(counter, 300);', ' String [] expected = {"cantaloupe", "from", "ksu", "okstate", "on", "srv"};', ' checkExpected(counter, 14, expected);', ' }', '', ' public void test300CorrectNumber() {', ' System.out.println("\\nChecking correct number of unique words in 300 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 300);', ' /* check the 122th, 123th, and 124th most frequent word in the corpus so far ', ' * and check if the result is not null.', ' */', ' assertNotNull(counter.getKthMostFrequent(122));', ' assertNotNull(counter.getKthMostFrequent(123));', ' assertNotNull(counter.getKthMostFrequent(124));', ' // check the 125th most frequent word in the corpus so far', ' // and check if the result is null.', ' assertNull(counter.getKthMostFrequent(125));', ' }', '', ' public void test300and100() {', ' System.out.println("\\nChecking top 5 of 100 and 300 words with two counters");', ' WordCounter counter1 = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter1, 300);', ' closeFiles();', '', ' WordCounter counter2 = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter2, 100);', '', ' String [] expected1 = {"edu", "cmu", "comp", "ohio", "state"};', ' checkExpected(counter1, 0, expected1);', '', ' String [] expected2 = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter2, 0, expected2);', ' }', '', ' public void testAllTop15() {', ' System.out.println("\\nChecking top 15 of all words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' // Read the next 6000000 words', ' readWords(counter, 6000000);', ' String [] expected = {"the", "edu", "to", "of", "and",', ' "in", "is", "ax", "that", "it",', ' "cmu", "for", "com", "you", "cs"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void testAllTop10000() {', ' System.out.println("\\nChecking time to get top 10000 of all words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 6000000);', '', ' for (int i=0; i<10000; i++) {', ' counter.getKthMostFrequent(i);', ' }', ' }', '', ' public void testSpeed() {', ' System.out.println("\\nMixing adding data with finding top k");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWordsMixed (counter, 6000000);', ' String [] expected = {"the", "edu", "to", "of", "and",', ' "in", "is", "ax", "that", "it",', ' "cmu", "for", "com", "you", "cs"};', ' checkExpected(counter, 0, expected);', ' }', '', '}'] | [{'reason_category': 'Loop Body', 'usage_line': 271}, {'reason_category': 'If Body', 'usage_line': 271}] | Variable 'j' used at line 271 is defined at line 255 and has a Medium-Range dependency. | {'Loop Body': 1, 'If Body': 1} | {'Variable Medium-Range': 1} |
infilling_java | CounterTester | 445 | 446 | ['import junit.framework.TestCase;', 'import java.io.*;', 'import java.util.HashMap;', 'import java.util.TreeMap;', 'import java.util.ArrayList;', '', '/**', ' * This silly little class wraps String, int pairs so they can be sorted.', ' * Used by the WordCounter class.', ' */', 'class WordWrapper implements Comparable <WordWrapper> {', '', ' private String myWord;', ' private int myCount;', ' private int mySlot;', '', ' /**', ' * Creates a new WordWrapper with string "XXX" and count zero.', ' */', ' public WordWrapper (String myWordIn, int myCountIn, int mySlotIn) {', ' myWord = myWordIn;', ' myCount = myCountIn;', ' mySlot = mySlotIn;', ' }', ' /**', ' * Returns a copy of the string in the WordWrapper.', ' *', ' * @return The word contained in this object. Is copied out: no aliasing.', ' */', ' public String extractWord () {', ' return new String (myWord);', ' }', '', ' /**', ' * Returns the count in this WordWrapper.', ' *', ' * @return The count contained in the object.', ' */', ' public int extractCount () {', ' return myCount;', ' }', '', ' public void incCount () {', ' myCount++;', ' }', '', ' public int getCount () {', ' return myCount;', ' }', '', ' public int getPos () {', ' return mySlot;', ' }', '', ' public void setPos (int toWhat) {', ' ', ' mySlot = toWhat;', ' }', '', ' public String toString () {', ' return myWord + " " + mySlot;', ' }', '', ' /**', ' * Comparison operator so we implement the Comparable interface.', ' *', ' * @param w The word wrapper to compare to', ' * @return a positive, zero, or negative value depending upon whether this', ' * word wrapper is less then, equal to, or greater than param w. The', ' * relationship is determied by looking at the counts.', ' */', ' public int compareTo (WordWrapper w) {', " // Check if the count of the current word (myCount) is equal to the count of the word 'w'", ' // If the counts are equal, compare the words lexicographically', ' if (w.myCount == myCount) {', ' return myWord.compareTo(w.myWord);', ' }', " // If the counts are not equal, subtract the count of the current word from the count of the word 'w'", ' return w.myCount - myCount;', ' }', '}', '', '', '/**', ' * This class is used to count occurences of words (strings) in a corpus. Used by', ' * the IndexedDocumentCollection class to find the most frequent words in the corpus.', ' */', '', 'class WordCounter {', ' ', " // this is the map that holds (for each word) the number of times we've seen it", ' // note that Integer is a wrapper for the buitin Java int type', ' private HashMap <String, WordWrapper> wordsIHaveSeen = new HashMap <String, WordWrapper> ();', ' private TreeMap <String, String> ones = new TreeMap <String, String> ();', ' ', ' // the set of words that have been extracted', ' private ArrayList<WordWrapper> extractedWords = new ArrayList <WordWrapper> ();', '', ' /**', ' * Accepts a word and increments the count of the number of times we have seen it.', ' * Note that a deep copy of the param is done (no aliasing).', ' *', ' * @param addMe The string to count', ' */', ' public void insert (String addMe) {', ' if (ones.containsKey (addMe)) {', ' ones.remove (addMe);', ' WordWrapper temp = new WordWrapper (addMe, 1, extractedWords.size ());', ' wordsIHaveSeen.put(addMe, temp);', ' extractedWords.add (temp);', ' }', '', ' // first check to see if the word is alredy in wordsIHaveSeen', ' if (wordsIHaveSeen.containsKey (addMe)) {', ' // if it is, then remove and increment its count', ' WordWrapper temp = wordsIHaveSeen.get (addMe);', ' temp.incCount ();', '', ' // find the slot that we go to in the extractedWords list', " // by sorting the 'extractedWords' list in ascending order", ' for (int i = temp.getPos () - 1; i >= 0 && ', ' extractedWords.get (i).compareTo (extractedWords.get (i + 1)) > 0; i--) {', ' temp = extractedWords.get (i + 1);', ' temp.setPos (i);', ' ', ' WordWrapper temp2 = extractedWords.get (i);', ' temp2.setPos (i + 1);', ' ', ' extractedWords.set (i + 1, temp2);', ' extractedWords.set (i, temp);', ' }', '', ' // in this case it is not there, so just add it', ' } else {', ' ones.put (addMe, addMe);', ' }', ' }', '', ' /**', ' * Returns the kth most frequent word in the corpus so far. A deep copy is returned,', ' * so no aliasing is possible. Returns null if there are not enough words.', ' *', ' * @param k Note that the most frequent word is at k = 0', ' * @return The kth most frequent word in the corpus to date', ' */', ' public String getKthMostFrequent (int k) {', '', ' // if we got here, then the array is all set up, so just return the kth most frequent word', ' if (k >= extractedWords.size ()) {', ' int which = extractedWords.size ();', ' for (String s : ones.navigableKeySet ()) {', ' if (which == k)', ' return s;', ' which++;', ' }', ' return null;', ' } else {', ' // If k is less than the size of the extractedWords list,', ' // return the kth most frequent word from extractedWords', ' return extractedWords.get (k).extractWord ();', ' }', ' }', '}', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class CounterTester extends TestCase {', '', ' /**', ' * File object to read words from, with buffering.', ' */', ' private FileReader file = null;', ' private BufferedReader reader = null;', '', ' /**', ' * Close file readers.', ' */', ' private void closeFiles() {', ' try {', ' if (file != null) {', ' file.close();', ' file = null;', ' }', ' if (reader != null) {', ' reader.close();', ' reader = null;', ' }', ' } catch (Exception e) {', ' System.err.println("Problem closing file");', ' System.err.println(e);', ' e.printStackTrace();', ' }', ' }', '', ' /**', ' * Close files no matter what happens in the test.', ' */', ' protected void tearDown () {', ' closeFiles();', ' }', '', ' /**', ' * Open file and set up readers.', ' *', ' * @param fileName name of file to open', ' * */', ' private void openFile(String fileName) {', ' try {', ' file = new FileReader(fileName);', ' reader = new BufferedReader(file);', ' } catch (Exception e) {', ' System.err.format("Problem opening %s file\\n", fileName);', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Read the next numWords from the file.', ' *', ' * @param counter word counter to update', ' * @param numWords number of words to read.', ' */', ' private void readWords(WordCounter counter, int numWords) {', ' try {', ' for (int i=0; i<numWords; i++) {', ' if (i % 100000 == 0)', ' System.out.print (".");', ' String word = reader.readLine();', ' if (word == null) {', ' return;', ' }', " // Insert 'word' into the counter.", ' counter.insert(word);', ' }', ' } catch (Exception e) {', ' System.err.println("Problem reading file");', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Read the next numWords from the file, mixing with queries', ' *', ' * @param counter word counter to update', ' * @param numWords number of words to read.', ' */', ' private void readWordsMixed (WordCounter counter, int numWords) {', ' try {', ' int j = 0;', ' for (int i=0; i<numWords; i++) {', ' String word = reader.readLine();', " // If 'word' is null, it means we've reached the end of the file. So, return from the method.", ' if (word == null) {', ' return;', ' }', ' counter.insert(word);', '', ' // If the current iteration number is a multiple of 10 and greater than 100,000, perform a query of the kth most frequent word.', ' if (i % 10 == 0 && i > 100000) {', ' String myStr = counter.getKthMostFrequent(j++);', ' }', '', ' // rest j once we get to 100', ' if (j == 100)', ' j = 0;', ' }', ' } catch (Exception e) {', ' System.err.println("Problem reading file");', ' System.err.println(e);', ' e.printStackTrace();', ' fail();', ' }', ' }', '', ' /**', ' * Check that a sequence of words starts at the "start"th most', ' * frequent word.', ' *', ' * @param counter word counter to lookup', ' * @param start frequency index to start checking at', ' * @param expected array of expected words that start at that frequency', ' */', ' private void checkExpected(WordCounter counter, int start, String [] expected) {', ' for (int i = 0; i<expected.length; i++) {', ' String actual = counter.getKthMostFrequent(start);', ' System.out.format("k: %d, expected: %s, actual: %s\\n",', ' start, expected[i], actual);', ' assertEquals(expected[i], actual);', ' start++;', ' }', ' }', '', ' /**', ' * A test method.', ' * (Replace "X" with a name describing the test. You may write as', ' * many "testSomething" methods in this class as you wish, and each', ' * one will be called when running JUnit over this class.)', ' */', ' public void testSimple() {', ' System.out.println("\\nChecking insert");', ' WordCounter counter = new WordCounter();', ' counter.insert("pizzaz");', ' // Insert the word "pizza" into the counter twice', ' counter.insert("pizza");', ' counter.insert("pizza");', ' String [] expected = {"pizza"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void testTie() {', ' System.out.println("\\nChecking tie for 2nd place");', ' WordCounter counter = new WordCounter();', ' counter.insert("panache");', ' counter.insert("pizzaz");', ' counter.insert("pizza");', ' counter.insert("zebra");', ' counter.insert("pizza");', ' counter.insert("lion");', ' counter.insert("pizzaz");', ' counter.insert("panache");', ' counter.insert("panache");', ' counter.insert("camel");', ' // order is important here', ' String [] expected = {"pizza", "pizzaz"};', ' checkExpected(counter, 1, expected);', ' }', '', '', ' public void testPastTheEnd() {', ' System.out.println("\\nChecking past the end");', ' WordCounter counter = new WordCounter();', ' counter.insert("hi");', ' counter.insert("hello");', ' counter.insert("greetings");', ' counter.insert("salutations");', ' counter.insert("hi");', ' counter.insert("welcome");', ' counter.insert("goodbye");', ' counter.insert("later");', ' counter.insert("hello");', ' counter.insert("when");', ' counter.insert("hi");', ' assertNull(counter.getKthMostFrequent(8));', ' }', '', ' public void test100Top5() {', ' System.out.println("\\nChecking top 5 of 100 words");', ' WordCounter counter = new WordCounter();', ' // Open the file "allWordsBig"', ' openFile("allWordsBig");', ' // Read the next 100 words', ' readWords(counter, 100);', ' String [] expected = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void test300Top5() {', ' System.out.println("\\nChecking top 5 of first 100 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 100);', ' String [] expected1 = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter, 0, expected1);', '', ' System.out.println("Adding 100 more words and rechecking top 5");', ' readWords(counter, 100);', ' String [] expected2 = {"edu", "cmu", "comp", "cs", "state"};', ' checkExpected(counter, 0, expected2);', '', ' System.out.println("Adding 100 more words and rechecking top 5");', ' readWords(counter, 100);', ' String [] expected3 = {"edu", "cmu", "comp", "ohio", "state"};', ' checkExpected(counter, 0, expected3);', ' }', '', ' public void test300Words14Thru19() {', ' System.out.println("\\nChecking rank 14 through 19 of 300 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' // Read the next 300 words', ' readWords(counter, 300);', ' String [] expected = {"cantaloupe", "from", "ksu", "okstate", "on", "srv"};', ' checkExpected(counter, 14, expected);', ' }', '', ' public void test300CorrectNumber() {', ' System.out.println("\\nChecking correct number of unique words in 300 words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 300);', ' /* check the 122th, 123th, and 124th most frequent word in the corpus so far ', ' * and check if the result is not null.', ' */', ' assertNotNull(counter.getKthMostFrequent(122));', ' assertNotNull(counter.getKthMostFrequent(123));', ' assertNotNull(counter.getKthMostFrequent(124));', ' // check the 125th most frequent word in the corpus so far', ' // and check if the result is null.', ' assertNull(counter.getKthMostFrequent(125));', ' }', '', ' public void test300and100() {', ' System.out.println("\\nChecking top 5 of 100 and 300 words with two counters");', ' WordCounter counter1 = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter1, 300);', ' closeFiles();', '', ' WordCounter counter2 = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter2, 100);', '', ' String [] expected1 = {"edu", "cmu", "comp", "ohio", "state"};', ' checkExpected(counter1, 0, expected1);', '', ' String [] expected2 = {"edu", "comp", "cs", "windows", "cmu"};', ' checkExpected(counter2, 0, expected2);', ' }', '', ' public void testAllTop15() {', ' System.out.println("\\nChecking top 15 of all words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' // Read the next 6000000 words', ' readWords(counter, 6000000);', ' String [] expected = {"the", "edu", "to", "of", "and",', ' "in", "is", "ax", "that", "it",', ' "cmu", "for", "com", "you", "cs"};', ' checkExpected(counter, 0, expected);', ' }', '', ' public void testAllTop10000() {', ' System.out.println("\\nChecking time to get top 10000 of all words");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWords(counter, 6000000);', '', ' for (int i=0; i<10000; i++) {'] | [' counter.getKthMostFrequent(i);', ' }'] | [' }', '', ' public void testSpeed() {', ' System.out.println("\\nMixing adding data with finding top k");', ' WordCounter counter = new WordCounter();', ' openFile("allWordsBig");', ' readWordsMixed (counter, 6000000);', ' String [] expected = {"the", "edu", "to", "of", "and",', ' "in", "is", "ax", "that", "it",', ' "cmu", "for", "com", "you", "cs"};', ' checkExpected(counter, 0, expected);', ' }', '', '}'] | [{'reason_category': 'Loop Body', 'usage_line': 445}, {'reason_category': 'Loop Body', 'usage_line': 446}] | Function 'WordCounter.getKthMostFrequent' used at line 445 is defined at line 146 and has a Long-Range dependency.
Variable 'i' used at line 445 is defined at line 444 and has a Short-Range dependency. | {'Loop Body': 2} | {'Function Long-Range': 1, 'Variable Short-Range': 1} |
infilling_java | MTreeTester | 217 | 219 | ['import junit.framework.TestCase;', 'import java.util.ArrayList;', 'import java.util.Random;', 'import java.util.Collections;', '', '// this is a map from a set of keys of type PointInMetricSpace to a', '// set of data of type DataType', 'interface IMTree <Key extends IPointInMetricSpace <Key>, Data> {', ' ', ' // insert a new key/data pair into the map', ' void insert (Key keyToAdd, Data dataToAdd);', ' ', ' // find all of the key/data pairs in the map that fall within a', ' // particular distance of query point if no results are found, then', ' // an empty array is returned (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> find (Key query, double distance);', ' ', ' // find the k closest key/data pairs in the map to a particular', ' // query point ', ' //', ' // if the number of points in the map is less than k, then the', ' // returned list will have less than k pairs in it', ' //', ' // if the number of points is zero, then an empty array is returned', ' // (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> findKClosest (Key query, int k);', ' ', ' // returns the number of nodes that exist on a path from root to leaf in the tree...', ' // whtever the details of the implementation are, a tree with a single leaf node should return 1, and a tree', ' // with more than one lead node should return at least two (since it must have at least one internal node).', ' public int depth ();', ' ', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', '', 'interface IDoubleVector {', '', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '', '// this correponds to some geometric object in a metric space; the object is built out of', '// one or more points of type PointInMetricSpace', 'interface IObjectInMetricSpaceABCD <PointInMetricSpace extends IPointInMetricSpace<PointInMetricSpace>> {', ' ', ' // get the maximum distance from some point on the shape to a particular point in the metric space', ' double maxDistanceTo (PointInMetricSpace checkMe);', ' ', ' // return some arbitrary point on the interior of the geometric object', ' PointInMetricSpace getPointInInterior ();', '}', '', '', '// this interface corresponds to a point in some metric space', 'interface IPointInMetricSpace <PointInMetricSpace> {', ' ', ' // get the distance to another point', ' // ', ' // for this to work in an M-Tree, distances should be "metric" and', ' // obey the triangle inequality', ' double getDistance (PointInMetricSpace toMe);', '}', '', '// this is the basic node type in the structure', 'interface IMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> {', ' ', ' // insert a new key/data pair into the structure. The return value is a new MTreeNode if there was', ' // a split in response to the insertion, or a null if there was no split', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd);', ' ', ' // find all of the key/data pairs in the structure that fall within a particular query sphere', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query); ', ' ', ' // find the set of items closest to the given query point', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ);', ' ', ' // returns a sphere that totally encompasses everything in the node and its subtree', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', ' ', ' // returns the depth', ' public int depth ();', '}', '', '// this is a point in a particular metric space', 'class PointABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the point', ' private PointInMetricSpace me;', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return me; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return checkMe.getDistance (me); ', ' }', ' ', ' // contruct a point', ' public PointABCD (PointInMetricSpace useMe) {', ' me = useMe; ', ' }', '}', '', 'class PQueueABCD <PointInMetricSpace, DataType> {', ' ', ' // this is an object in the queue', ' private class Wrapper {', ' DataWrapper <PointInMetricSpace, DataType> myData;', ' double distance;', ' }', ' ', ' // this is the actual queue', ' ArrayList <Wrapper> myList;', ' ', ' // this is the largest distance value currently in the queue', ' double large;', ' ', ' // this is the max number of objects', ' int maxCount;', ' ', ' // create a priority queue with the speced number of slots', ' PQueueABCD (int maxCountIn) {', ' maxCount = maxCountIn;', ' myList = new ArrayList <Wrapper> ();', ' large = 9e99;', ' }', ' ', ' // get the largest distance in the queue', ' double getDist () {', ' return large;', ' }', ' ', ' // add a new object to the queue... the insertion is ignored if the distance value', ' // exceeds the largest that is in the queue and the queue is already full', ' void insert (PointInMetricSpace key, DataType data, double distance) {', ' ', ' // if we are full, remove the one with the largest distance', ' if (myList.size () == maxCount && distance < large) {', ' ', ' int badIndex = 0;', ' double maxDist = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > maxDist) {'] | [' maxDist = myList.get (i).distance;', ' badIndex = i;', ' }'] | [' }', ' ', ' myList.remove (badIndex);', ' }', ' ', ' // see if there is room', ' if (myList.size () < maxCount) {', ' ', ' // add it ', ' Wrapper newOne = new Wrapper ();', ' newOne.myData = new DataWrapper <PointInMetricSpace, DataType> (key, data);', ' newOne.distance = distance;', ' myList.add (newOne); ', ' }', ' ', ' // if we are full, reset the max distance', ' if (myList.size () == maxCount) {', ' large = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > large) {', ' large = myList.get (i).distance;', ' }', ' }', ' }', ' ', ' }', ' ', ' // extracts the contents of the queue', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> done () {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' for (int i = 0; i < myList.size (); i++) {', ' returnVal.add (myList.get (i).myData); ', ' }', ' ', ' return returnVal;', ' }', ' ', '}', '', '// this is a sphere in a particular metric space', 'class SphereABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the center of the sphere and its radius', ' private PointInMetricSpace center;', ' private double radius;', ' ', ' // build a sphere out of its center and its radius', ' public SphereABCD (PointInMetricSpace centerIn, double radiusIn) {', ' center = centerIn;', ' radius = radiusIn;', ' }', ' ', ' // increase the size of the sphere so it contains the object swallowMe', ' public void swallow (IObjectInMetricSpaceABCD <PointInMetricSpace> swallowMe) {', ' ', ' // see if we need to increase the radius to swallow this guy', ' double dist = swallowMe.maxDistanceTo (center);', ' if (dist > radius)', ' radius = dist;', ' }', ' ', ' // check to see if a sphere intersects another sphere', ' public boolean intersects (SphereABCD <PointInMetricSpace> me) {', ' return (me.center.getDistance (center) <= me.radius + radius);', ' }', ' ', ' // check to see if the sphere contains a point', ' public boolean contains (PointInMetricSpace checkMe) {', ' return (checkMe.getDistance (center) <= radius);', ' }', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return center; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return radius + checkMe.getDistance (center); ', ' }', '}', '', '', '', 'class OneDimPoint implements IPointInMetricSpace <OneDimPoint> {', ' ', ' // this is the actual double', ' Double value;', ' ', ' // construct this out of a double value', ' public OneDimPoint (double makeFromMe) {', ' value = new Double (makeFromMe);', ' }', ' ', ' // get the distance to another point', ' public double getDistance (OneDimPoint toMe) {', ' if (value > toMe.value)', ' return value - toMe.value;', ' else', ' return toMe.value - value;', ' }', ' ', '}', '', 'class MultiDimPoint implements IPointInMetricSpace <MultiDimPoint> {', ' ', ' // this is the point in a multidimensional space', ' IDoubleVector me;', ' ', ' // make this out of an IDoubleVector', ' public MultiDimPoint (IDoubleVector useMe) {', ' me = useMe;', ' }', ' ', ' // get the Euclidean distance to another point', ' public double getDistance (MultiDimPoint toMe) {', ' double distance = 0.0;', ' try {', ' for (int i = 0; i < me.getLength (); i++) {', ' double diff = me.getItem (i) - toMe.me.getItem (i);', ' diff *= diff;', ' distance += diff;', ' }', ' } catch (OutOfBoundsException e) {', ' throw new IndexOutOfBoundsException ("Can\'t compare two MultiDimPoint objects with different dimensionality!"); ', ' }', ' return Math.sqrt(distance);', ' }', ' ', '}', '// this is a leaf node', 'class LeafMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements ', ' IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myData;', ' ', ' // contructor that takes a data list and builds a node out of it', ' private LeafMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myDataIn) {', ' myData = myDataIn; ', ' }', ' ', ' // constructor that creates an empty node', ' public LeafMTreeNodeABCD () {', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> (); ', ' }', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // just add in the new data', ' myData.add (new PointABCD <PointInMetricSpace> (keyToAdd), dataToAdd);', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> newOne = myData.splitInTwo ();', ' LeafMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' myQ.insert (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData (), ', ' query.getDistance (myData.get (i).getKey ().getPointInInterior ()));', ' }', ' }', ' }', ' ', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' returnVal.add (new DataWrapper <PointInMetricSpace, DataType> (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData ()));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return 1; ', ' }', '', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', '// this silly little class is just a wrapper for a key, data pair', 'class DataWrapper <Key, Data> {', ' ', ' Key key;', ' Data data;', ' ', ' public DataWrapper (Key keyIn, Data dataIn) {', ' key = keyIn;', ' data = dataIn;', ' }', ' ', ' public Key getKey () {', ' return key;', ' }', ' ', ' public Data getData () {', ' return data;', ' }', '}', '', '', '// this is an internal node', 'class InternalMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType>', ' implements IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> myData;', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' // this constructs a new internal node that holds precisely the two nodes that are passed in', ' public InternalMTreeNodeABCD (IMTreeNodeABCD <PointInMetricSpace, DataType> refOne,', ' IMTreeNodeABCD <PointInMetricSpace, DataType> refTwo) {', ' ', ' // create a necw list and add the two guys in', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> ();', ' myData.add (refOne.getBoundingSphere (), refOne);', ' myData.add (refTwo.getBoundingSphere (), refTwo);', ' }', ' ', ' // this constructs a new node that holds the list of data that we were passed in', ' public InternalMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> useMe) {', ' myData = useMe; ', ' }', ' ', ' // from the interface', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // find the best child; this is the one we are closest to', ' double bestDist = 9e99;', ' int bestIndex = 0;', ' for (int i = 0; i < myData.size (); i++) {', ' ', ' double newDist = myData.get (i).getKey ().getPointInInterior ().getDistance (keyToAdd);', ' if (newDist < bestDist) {', ' bestDist = newDist;', ' bestIndex = i;', ' }', ' }', ' ', ' // do the recursive insert', ' IMTreeNodeABCD <PointInMetricSpace, DataType> newRef = myData.get (bestIndex).getData ().insert (keyToAdd, dataToAdd);', ' ', ' // if we got something back, then there was a split, so add the new node into our list', ' if (newRef != null) {', ' myData.add (newRef.getBoundingSphere (), newRef);', ' }', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> newOne = myData.splitInTwo ();', ' InternalMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.intersects (myData.get (i).getKey ())) {', ' myData.get (i).getData ().findKClosest (query, myQ);', ' }', ' }', ' }', ' ', ' // from the interface', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.intersects (myData.get (i).getKey ())) {', ' returnVal.addAll (myData.get (i).getData ().find (query));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return myData.get (0).getData ().depth () + 1; ', ' }', ' ', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', 'abstract class AMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> implements IMetricDataListABCD <PointInMetricSpace,KeyType, DataType> {', '', ' // this is the data that is actually stored in the list', ' private ArrayList <DataWrapper <KeyType, DataType>> myData;', ' ', ' // this is the sphere that bounds everything in the list', ' private SphereABCD <PointInMetricSpace> myBoundingSphere;', ' ', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myBoundingSphere; ', ' }', ' ', ' public int size () {', ' if (myData != null)', ' return myData.size (); ', ' else', ' return 0;', ' }', ' ', ' public DataWrapper <KeyType, DataType> get (int pos) {', ' return myData.get (pos);', ' }', ' ', ' public void replaceKey (int pos, KeyType keyToAdd) {', ' DataWrapper <KeyType, DataType> temp = myData.remove (pos);', ' DataWrapper <KeyType, DataType> newOne = new DataWrapper <KeyType, DataType> (keyToAdd, temp.getData ());', ' myData.add (pos, newOne);', ' }', ' ', ' public void add (KeyType keyToAdd, DataType dataToAdd) {', ' ', ' // if this is the first add, then set everyone up', ' if (myData == null) {', ' PointInMetricSpace myCentroid = keyToAdd.getPointInInterior ();', ' myBoundingSphere = new SphereABCD <PointInMetricSpace> (myCentroid, keyToAdd.maxDistanceTo (myCentroid));', ' myData = new ArrayList <DataWrapper <KeyType, DataType>> ();', ' ', ' // otherwise, extend the sphere if needed', ' } else {', ' myBoundingSphere.swallow (keyToAdd);', ' }', ' ', ' // add the data', ' myData.add (new DataWrapper <KeyType, DataType> (keyToAdd, dataToAdd));', ' }', ' ', ' // we want to potentially allow many implementations of the splitting lalgorithm', ' abstract public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // this is here so the actual splitting algorithn can access the list and change the sphere', ' protected ArrayList <DataWrapper <KeyType, DataType>> getList () {', ' return myData;', ' }', ' ', ' // this is here so the splitting algorithm can modify the list and the sphere', ' protected void replaceGuts (AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> withMe) {', ' myData = withMe.myData;', ' myBoundingSphere = withMe.myBoundingSphere;', ' }', ' ', '}', '', '// this is a particular implementation of the metric data list that uses a simple quadratic clustering', '// algorithm to perform a list split. It picks two "seeds" (the most distant objects) and then repeatedly', '// adds to the two new lists by choosing the objects closest to the seeds', 'class ChrisMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> extends AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> {', '', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo () {', ' ', ' // first, we need to find the two most distant points in the list', ' ArrayList <DataWrapper <KeyType, DataType>> myData = getList ();', ' int bestI = 0, bestJ = 0;', ' double maxDist = -1.0;', ' for (int i = 0; i < myData.size (); i++) {', ' for (int j = i + 1; j < myData.size (); j++) {', ' ', ' // get the two keys', ' DataWrapper <KeyType, DataType> pointOne = myData.get (i);', ' DataWrapper <KeyType, DataType> pointTwo = myData.get (j);', ' ', ' // find the difference between them', ' double curDist = pointOne.getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', '', ' // see if it is the biggest', ' if (curDist > maxDist) {', ' maxDist = curDist;', ' bestI = i;', ' bestJ = j;', ' }', ' }', ' }', ' ', ' // now, we have the best two points; those are seeds for the clustering', ' DataWrapper <KeyType, DataType> pointOne = myData.remove (bestI);', ' DataWrapper <KeyType, DataType> pointTwo = myData.remove (bestJ - 1);', ' ', ' // these are the two new lists', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listOne = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listTwo = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' ', ' // put the two seeds in', ' listOne.add (pointOne.getKey (), pointOne.getData ());', ' listTwo.add (pointTwo.getKey (), pointTwo.getData ());', ' ', ' // and add everyone else in', ' while (myData.size () != 0) {', ' ', ' // find the one closest to the first seed', ' int bestIndex = 0;', ' double bestDist = 9e99;', ' ', ' // loop thru all of the candidate data objects', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listOne.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' ', ' // break if no more data', ' if (myData.size () == 0)', ' break;', ' ', ' // loop thru all of the candidate data objects', ' bestDist = 9e99;', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listTwo.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' }', ' ', ' // now we replace our own guts with the first list', ' replaceGuts (listOne);', ' ', ' // and return the other list', ' return listTwo;', ' }', '}', '', 'interface IMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> {', ' ', ' // add a new pair to the list', ' public void add (KeyType keyToAdd, DataType dataToAdd);', ' ', ' // replace a key at the indicated position', ' public void replaceKey (int pos, KeyType keyToAdd);', ' ', ' // get the key, data pair that resides at a particular position', ' public DataWrapper <KeyType, DataType> get (int pos);', ' ', ' // return the number of items in the list', ' public int size ();', ' ', ' // split the list in two, using some clutering algorithm', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // get a sphere that totally bounds all of the objects in the list', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class MTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public MTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class SCMTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public SCMTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', '', 'public class MTreeTester extends TestCase {', ' ', ' // compare two lists of strings to see if the contents are the same', ' private boolean compareStringSets (ArrayList <String> setOne, ArrayList <String> setTwo) {', ' ', ' // sort the sets and make sure they are the same', ' boolean returnVal = true;', ' if (setOne.size () == setTwo.size ()) {', ' Collections.sort (setOne);', ' Collections.sort (setTwo);', ' for (int i = 0; i < setOne.size (); i++) {', ' if (!setOne.get (i).equals (setTwo.get (i))) {', ' returnVal = false;', ' break; ', ' }', ' }', ' } else {', ' returnVal = false;', ' }', ' ', ' // print out the result', ' System.out.println ("**** Expected:");', ' for (int i = 0; i < setOne.size (); i++) {', ' System.out.format (setOne.get (i) + " ");', ' }', ' System.out.println ("\\n**** Got:");', ' for (int i = 0; i < setTwo.size (); i++) {', ' System.out.format (setTwo.get (i) + " ");', ' }', ' System.out.println ("");', ' ', ' return returnVal;', ' }', ' ', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST SIMPLE ONE DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testOneDimRangeQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.find (query, expectedQuerySize / 2);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.find (query, expectedQuerySize / 2);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (numPoints);', ' result1 = myTree.find (query, expectedQuerySize);', ' result2 = hisTree.find (query, expectedQuerySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // like the last one, but runs a top k', ' private void testOneDimTopKQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (167);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.findKClosest (query, querySize);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (0);', ' result1 = myTree.findKClosest (query, querySize);', ' result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST MULTI-DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimRangeQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' double dist1 = 0;', ' double dist2 = 0;', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' dist1 = Math.sqrt (numDims) * expectedQuerySize / 2.0;', ' dist2 = Math.sqrt (numDims) * expectedQuerySize;', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' // do a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, (int) expectedQuerySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = myTree.findKClosest (query2, (int) expectedQuerySize);', ' ', ' // find the distance to the furthest point in both cases', ' for (int i = 0; i < (int) expectedQuerySize; i++) {', ' double newDist = result1.get (i).getKey ().getDistance (query1);', ' if (newDist > dist1)', ' dist1 = newDist;', ' newDist = result2.get (i).getKey ().getDistance (query2);', ' if (newDist > dist2)', ' dist2 = newDist;', ' }', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.find (query1, dist1);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.find (query1, dist1);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.find (query2, dist2);', ' result2 = hisTree.find (query2, dist2);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimTopKQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, querySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.findKClosest (query1, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.findKClosest (query2, querySize);', ' result2 = hisTree.findKClosest (query2, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' ', ' /**', ' * "TIER 1" TESTS', ' * NONE OF THESE REQUIRE ANY SPLITS', ' */', ' public void testEasy1() {', ' testOneDimRangeQuery (true, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy2() {', ' testOneDimRangeQuery (false, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy3() {', ' testOneDimRangeQuery (true, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy4() {', ' testOneDimRangeQuery (false, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy5() {', ' testMultiDimRangeQuery (true, 1, 5, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy6() {', ' testMultiDimRangeQuery (false, 1, 10, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy7() {', ' testMultiDimRangeQuery (true, 1, 5, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy8() {', ' testMultiDimRangeQuery (false, 1, 15, 10000, 10000, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 2" TESTS', ' * NONE OF THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testMod1() {', ' testOneDimRangeQuery (true, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod2() {', ' testOneDimRangeQuery (false, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod3() {', ' testOneDimRangeQuery (true, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod4() {', ' testOneDimRangeQuery (false, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod5() {', ' testMultiDimRangeQuery (true, 2, 5, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod6() {', ' testMultiDimRangeQuery (false, 2, 10, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod7() {', ' testMultiDimRangeQuery (true, 2, 5, 10000, 100, 1000, 10);', ' }', ' ', ' public void testMod8() {', ' testMultiDimRangeQuery (false, 2, 15, 10000, 100, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 3" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testHard1() {', ' testOneDimRangeQuery (true, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard2() {', ' testOneDimRangeQuery (false, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard3() {', ' testOneDimRangeQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard4() {', ' testOneDimRangeQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard5() {', ' testMultiDimRangeQuery (true, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard6() {', ' testMultiDimRangeQuery (false, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard7() {', ' testMultiDimRangeQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard8() {', ' testMultiDimRangeQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', ' ', ' /**', ' * "TIER 4" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE AND THEY TEST THE TOPK FUNCTIONALITY', ' */', ' ', ' public void testTopK1() {', ' testOneDimTopKQuery (true, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK2() {', ' testOneDimTopKQuery (false, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK3() {', ' testOneDimTopKQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK4() {', ' testOneDimTopKQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK5() {', ' testMultiDimTopKQuery (true, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK6() {', ' testMultiDimTopKQuery (false, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK7() {', ' testMultiDimTopKQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK8() {', ' testMultiDimTopKQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', '}'] | [{'reason_category': 'If Body', 'usage_line': 217}, {'reason_category': 'Loop Body', 'usage_line': 217}, {'reason_category': 'If Body', 'usage_line': 218}, {'reason_category': 'Loop Body', 'usage_line': 218}, {'reason_category': 'If Body', 'usage_line': 219}, {'reason_category': 'Loop Body', 'usage_line': 219}] | Global_Variable 'myList' used at line 217 is defined at line 186 and has a Long-Range dependency.
Variable 'i' used at line 217 is defined at line 215 and has a Short-Range dependency.
Variable 'distance' used at line 217 is defined at line 208 and has a Short-Range dependency.
Variable 'maxDist' used at line 217 is defined at line 214 and has a Short-Range dependency.
Variable 'i' used at line 218 is defined at line 215 and has a Short-Range dependency.
Variable 'badIndex' used at line 218 is defined at line 213 and has a Short-Range dependency. | {'If Body': 3, 'Loop Body': 3} | {'Global_Variable Long-Range': 1, 'Variable Short-Range': 5} |
infilling_java | MTreeTester | 216 | 220 | ['import junit.framework.TestCase;', 'import java.util.ArrayList;', 'import java.util.Random;', 'import java.util.Collections;', '', '// this is a map from a set of keys of type PointInMetricSpace to a', '// set of data of type DataType', 'interface IMTree <Key extends IPointInMetricSpace <Key>, Data> {', ' ', ' // insert a new key/data pair into the map', ' void insert (Key keyToAdd, Data dataToAdd);', ' ', ' // find all of the key/data pairs in the map that fall within a', ' // particular distance of query point if no results are found, then', ' // an empty array is returned (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> find (Key query, double distance);', ' ', ' // find the k closest key/data pairs in the map to a particular', ' // query point ', ' //', ' // if the number of points in the map is less than k, then the', ' // returned list will have less than k pairs in it', ' //', ' // if the number of points is zero, then an empty array is returned', ' // (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> findKClosest (Key query, int k);', ' ', ' // returns the number of nodes that exist on a path from root to leaf in the tree...', ' // whtever the details of the implementation are, a tree with a single leaf node should return 1, and a tree', ' // with more than one lead node should return at least two (since it must have at least one internal node).', ' public int depth ();', ' ', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', '', 'interface IDoubleVector {', '', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '', '// this correponds to some geometric object in a metric space; the object is built out of', '// one or more points of type PointInMetricSpace', 'interface IObjectInMetricSpaceABCD <PointInMetricSpace extends IPointInMetricSpace<PointInMetricSpace>> {', ' ', ' // get the maximum distance from some point on the shape to a particular point in the metric space', ' double maxDistanceTo (PointInMetricSpace checkMe);', ' ', ' // return some arbitrary point on the interior of the geometric object', ' PointInMetricSpace getPointInInterior ();', '}', '', '', '// this interface corresponds to a point in some metric space', 'interface IPointInMetricSpace <PointInMetricSpace> {', ' ', ' // get the distance to another point', ' // ', ' // for this to work in an M-Tree, distances should be "metric" and', ' // obey the triangle inequality', ' double getDistance (PointInMetricSpace toMe);', '}', '', '// this is the basic node type in the structure', 'interface IMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> {', ' ', ' // insert a new key/data pair into the structure. The return value is a new MTreeNode if there was', ' // a split in response to the insertion, or a null if there was no split', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd);', ' ', ' // find all of the key/data pairs in the structure that fall within a particular query sphere', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query); ', ' ', ' // find the set of items closest to the given query point', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ);', ' ', ' // returns a sphere that totally encompasses everything in the node and its subtree', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', ' ', ' // returns the depth', ' public int depth ();', '}', '', '// this is a point in a particular metric space', 'class PointABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the point', ' private PointInMetricSpace me;', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return me; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return checkMe.getDistance (me); ', ' }', ' ', ' // contruct a point', ' public PointABCD (PointInMetricSpace useMe) {', ' me = useMe; ', ' }', '}', '', 'class PQueueABCD <PointInMetricSpace, DataType> {', ' ', ' // this is an object in the queue', ' private class Wrapper {', ' DataWrapper <PointInMetricSpace, DataType> myData;', ' double distance;', ' }', ' ', ' // this is the actual queue', ' ArrayList <Wrapper> myList;', ' ', ' // this is the largest distance value currently in the queue', ' double large;', ' ', ' // this is the max number of objects', ' int maxCount;', ' ', ' // create a priority queue with the speced number of slots', ' PQueueABCD (int maxCountIn) {', ' maxCount = maxCountIn;', ' myList = new ArrayList <Wrapper> ();', ' large = 9e99;', ' }', ' ', ' // get the largest distance in the queue', ' double getDist () {', ' return large;', ' }', ' ', ' // add a new object to the queue... the insertion is ignored if the distance value', ' // exceeds the largest that is in the queue and the queue is already full', ' void insert (PointInMetricSpace key, DataType data, double distance) {', ' ', ' // if we are full, remove the one with the largest distance', ' if (myList.size () == maxCount && distance < large) {', ' ', ' int badIndex = 0;', ' double maxDist = 0.0;', ' for (int i = 0; i < myList.size (); i++) {'] | [' if (myList.get (i).distance > maxDist) {', ' maxDist = myList.get (i).distance;', ' badIndex = i;', ' }', ' }'] | [' ', ' myList.remove (badIndex);', ' }', ' ', ' // see if there is room', ' if (myList.size () < maxCount) {', ' ', ' // add it ', ' Wrapper newOne = new Wrapper ();', ' newOne.myData = new DataWrapper <PointInMetricSpace, DataType> (key, data);', ' newOne.distance = distance;', ' myList.add (newOne); ', ' }', ' ', ' // if we are full, reset the max distance', ' if (myList.size () == maxCount) {', ' large = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > large) {', ' large = myList.get (i).distance;', ' }', ' }', ' }', ' ', ' }', ' ', ' // extracts the contents of the queue', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> done () {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' for (int i = 0; i < myList.size (); i++) {', ' returnVal.add (myList.get (i).myData); ', ' }', ' ', ' return returnVal;', ' }', ' ', '}', '', '// this is a sphere in a particular metric space', 'class SphereABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the center of the sphere and its radius', ' private PointInMetricSpace center;', ' private double radius;', ' ', ' // build a sphere out of its center and its radius', ' public SphereABCD (PointInMetricSpace centerIn, double radiusIn) {', ' center = centerIn;', ' radius = radiusIn;', ' }', ' ', ' // increase the size of the sphere so it contains the object swallowMe', ' public void swallow (IObjectInMetricSpaceABCD <PointInMetricSpace> swallowMe) {', ' ', ' // see if we need to increase the radius to swallow this guy', ' double dist = swallowMe.maxDistanceTo (center);', ' if (dist > radius)', ' radius = dist;', ' }', ' ', ' // check to see if a sphere intersects another sphere', ' public boolean intersects (SphereABCD <PointInMetricSpace> me) {', ' return (me.center.getDistance (center) <= me.radius + radius);', ' }', ' ', ' // check to see if the sphere contains a point', ' public boolean contains (PointInMetricSpace checkMe) {', ' return (checkMe.getDistance (center) <= radius);', ' }', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return center; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return radius + checkMe.getDistance (center); ', ' }', '}', '', '', '', 'class OneDimPoint implements IPointInMetricSpace <OneDimPoint> {', ' ', ' // this is the actual double', ' Double value;', ' ', ' // construct this out of a double value', ' public OneDimPoint (double makeFromMe) {', ' value = new Double (makeFromMe);', ' }', ' ', ' // get the distance to another point', ' public double getDistance (OneDimPoint toMe) {', ' if (value > toMe.value)', ' return value - toMe.value;', ' else', ' return toMe.value - value;', ' }', ' ', '}', '', 'class MultiDimPoint implements IPointInMetricSpace <MultiDimPoint> {', ' ', ' // this is the point in a multidimensional space', ' IDoubleVector me;', ' ', ' // make this out of an IDoubleVector', ' public MultiDimPoint (IDoubleVector useMe) {', ' me = useMe;', ' }', ' ', ' // get the Euclidean distance to another point', ' public double getDistance (MultiDimPoint toMe) {', ' double distance = 0.0;', ' try {', ' for (int i = 0; i < me.getLength (); i++) {', ' double diff = me.getItem (i) - toMe.me.getItem (i);', ' diff *= diff;', ' distance += diff;', ' }', ' } catch (OutOfBoundsException e) {', ' throw new IndexOutOfBoundsException ("Can\'t compare two MultiDimPoint objects with different dimensionality!"); ', ' }', ' return Math.sqrt(distance);', ' }', ' ', '}', '// this is a leaf node', 'class LeafMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements ', ' IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myData;', ' ', ' // contructor that takes a data list and builds a node out of it', ' private LeafMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myDataIn) {', ' myData = myDataIn; ', ' }', ' ', ' // constructor that creates an empty node', ' public LeafMTreeNodeABCD () {', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> (); ', ' }', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // just add in the new data', ' myData.add (new PointABCD <PointInMetricSpace> (keyToAdd), dataToAdd);', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> newOne = myData.splitInTwo ();', ' LeafMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' myQ.insert (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData (), ', ' query.getDistance (myData.get (i).getKey ().getPointInInterior ()));', ' }', ' }', ' }', ' ', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' returnVal.add (new DataWrapper <PointInMetricSpace, DataType> (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData ()));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return 1; ', ' }', '', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', '// this silly little class is just a wrapper for a key, data pair', 'class DataWrapper <Key, Data> {', ' ', ' Key key;', ' Data data;', ' ', ' public DataWrapper (Key keyIn, Data dataIn) {', ' key = keyIn;', ' data = dataIn;', ' }', ' ', ' public Key getKey () {', ' return key;', ' }', ' ', ' public Data getData () {', ' return data;', ' }', '}', '', '', '// this is an internal node', 'class InternalMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType>', ' implements IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> myData;', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' // this constructs a new internal node that holds precisely the two nodes that are passed in', ' public InternalMTreeNodeABCD (IMTreeNodeABCD <PointInMetricSpace, DataType> refOne,', ' IMTreeNodeABCD <PointInMetricSpace, DataType> refTwo) {', ' ', ' // create a necw list and add the two guys in', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> ();', ' myData.add (refOne.getBoundingSphere (), refOne);', ' myData.add (refTwo.getBoundingSphere (), refTwo);', ' }', ' ', ' // this constructs a new node that holds the list of data that we were passed in', ' public InternalMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> useMe) {', ' myData = useMe; ', ' }', ' ', ' // from the interface', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // find the best child; this is the one we are closest to', ' double bestDist = 9e99;', ' int bestIndex = 0;', ' for (int i = 0; i < myData.size (); i++) {', ' ', ' double newDist = myData.get (i).getKey ().getPointInInterior ().getDistance (keyToAdd);', ' if (newDist < bestDist) {', ' bestDist = newDist;', ' bestIndex = i;', ' }', ' }', ' ', ' // do the recursive insert', ' IMTreeNodeABCD <PointInMetricSpace, DataType> newRef = myData.get (bestIndex).getData ().insert (keyToAdd, dataToAdd);', ' ', ' // if we got something back, then there was a split, so add the new node into our list', ' if (newRef != null) {', ' myData.add (newRef.getBoundingSphere (), newRef);', ' }', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> newOne = myData.splitInTwo ();', ' InternalMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.intersects (myData.get (i).getKey ())) {', ' myData.get (i).getData ().findKClosest (query, myQ);', ' }', ' }', ' }', ' ', ' // from the interface', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.intersects (myData.get (i).getKey ())) {', ' returnVal.addAll (myData.get (i).getData ().find (query));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return myData.get (0).getData ().depth () + 1; ', ' }', ' ', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', 'abstract class AMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> implements IMetricDataListABCD <PointInMetricSpace,KeyType, DataType> {', '', ' // this is the data that is actually stored in the list', ' private ArrayList <DataWrapper <KeyType, DataType>> myData;', ' ', ' // this is the sphere that bounds everything in the list', ' private SphereABCD <PointInMetricSpace> myBoundingSphere;', ' ', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myBoundingSphere; ', ' }', ' ', ' public int size () {', ' if (myData != null)', ' return myData.size (); ', ' else', ' return 0;', ' }', ' ', ' public DataWrapper <KeyType, DataType> get (int pos) {', ' return myData.get (pos);', ' }', ' ', ' public void replaceKey (int pos, KeyType keyToAdd) {', ' DataWrapper <KeyType, DataType> temp = myData.remove (pos);', ' DataWrapper <KeyType, DataType> newOne = new DataWrapper <KeyType, DataType> (keyToAdd, temp.getData ());', ' myData.add (pos, newOne);', ' }', ' ', ' public void add (KeyType keyToAdd, DataType dataToAdd) {', ' ', ' // if this is the first add, then set everyone up', ' if (myData == null) {', ' PointInMetricSpace myCentroid = keyToAdd.getPointInInterior ();', ' myBoundingSphere = new SphereABCD <PointInMetricSpace> (myCentroid, keyToAdd.maxDistanceTo (myCentroid));', ' myData = new ArrayList <DataWrapper <KeyType, DataType>> ();', ' ', ' // otherwise, extend the sphere if needed', ' } else {', ' myBoundingSphere.swallow (keyToAdd);', ' }', ' ', ' // add the data', ' myData.add (new DataWrapper <KeyType, DataType> (keyToAdd, dataToAdd));', ' }', ' ', ' // we want to potentially allow many implementations of the splitting lalgorithm', ' abstract public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // this is here so the actual splitting algorithn can access the list and change the sphere', ' protected ArrayList <DataWrapper <KeyType, DataType>> getList () {', ' return myData;', ' }', ' ', ' // this is here so the splitting algorithm can modify the list and the sphere', ' protected void replaceGuts (AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> withMe) {', ' myData = withMe.myData;', ' myBoundingSphere = withMe.myBoundingSphere;', ' }', ' ', '}', '', '// this is a particular implementation of the metric data list that uses a simple quadratic clustering', '// algorithm to perform a list split. It picks two "seeds" (the most distant objects) and then repeatedly', '// adds to the two new lists by choosing the objects closest to the seeds', 'class ChrisMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> extends AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> {', '', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo () {', ' ', ' // first, we need to find the two most distant points in the list', ' ArrayList <DataWrapper <KeyType, DataType>> myData = getList ();', ' int bestI = 0, bestJ = 0;', ' double maxDist = -1.0;', ' for (int i = 0; i < myData.size (); i++) {', ' for (int j = i + 1; j < myData.size (); j++) {', ' ', ' // get the two keys', ' DataWrapper <KeyType, DataType> pointOne = myData.get (i);', ' DataWrapper <KeyType, DataType> pointTwo = myData.get (j);', ' ', ' // find the difference between them', ' double curDist = pointOne.getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', '', ' // see if it is the biggest', ' if (curDist > maxDist) {', ' maxDist = curDist;', ' bestI = i;', ' bestJ = j;', ' }', ' }', ' }', ' ', ' // now, we have the best two points; those are seeds for the clustering', ' DataWrapper <KeyType, DataType> pointOne = myData.remove (bestI);', ' DataWrapper <KeyType, DataType> pointTwo = myData.remove (bestJ - 1);', ' ', ' // these are the two new lists', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listOne = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listTwo = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' ', ' // put the two seeds in', ' listOne.add (pointOne.getKey (), pointOne.getData ());', ' listTwo.add (pointTwo.getKey (), pointTwo.getData ());', ' ', ' // and add everyone else in', ' while (myData.size () != 0) {', ' ', ' // find the one closest to the first seed', ' int bestIndex = 0;', ' double bestDist = 9e99;', ' ', ' // loop thru all of the candidate data objects', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listOne.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' ', ' // break if no more data', ' if (myData.size () == 0)', ' break;', ' ', ' // loop thru all of the candidate data objects', ' bestDist = 9e99;', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listTwo.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' }', ' ', ' // now we replace our own guts with the first list', ' replaceGuts (listOne);', ' ', ' // and return the other list', ' return listTwo;', ' }', '}', '', 'interface IMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> {', ' ', ' // add a new pair to the list', ' public void add (KeyType keyToAdd, DataType dataToAdd);', ' ', ' // replace a key at the indicated position', ' public void replaceKey (int pos, KeyType keyToAdd);', ' ', ' // get the key, data pair that resides at a particular position', ' public DataWrapper <KeyType, DataType> get (int pos);', ' ', ' // return the number of items in the list', ' public int size ();', ' ', ' // split the list in two, using some clutering algorithm', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // get a sphere that totally bounds all of the objects in the list', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class MTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public MTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class SCMTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public SCMTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', '', 'public class MTreeTester extends TestCase {', ' ', ' // compare two lists of strings to see if the contents are the same', ' private boolean compareStringSets (ArrayList <String> setOne, ArrayList <String> setTwo) {', ' ', ' // sort the sets and make sure they are the same', ' boolean returnVal = true;', ' if (setOne.size () == setTwo.size ()) {', ' Collections.sort (setOne);', ' Collections.sort (setTwo);', ' for (int i = 0; i < setOne.size (); i++) {', ' if (!setOne.get (i).equals (setTwo.get (i))) {', ' returnVal = false;', ' break; ', ' }', ' }', ' } else {', ' returnVal = false;', ' }', ' ', ' // print out the result', ' System.out.println ("**** Expected:");', ' for (int i = 0; i < setOne.size (); i++) {', ' System.out.format (setOne.get (i) + " ");', ' }', ' System.out.println ("\\n**** Got:");', ' for (int i = 0; i < setTwo.size (); i++) {', ' System.out.format (setTwo.get (i) + " ");', ' }', ' System.out.println ("");', ' ', ' return returnVal;', ' }', ' ', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST SIMPLE ONE DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testOneDimRangeQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.find (query, expectedQuerySize / 2);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.find (query, expectedQuerySize / 2);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (numPoints);', ' result1 = myTree.find (query, expectedQuerySize);', ' result2 = hisTree.find (query, expectedQuerySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // like the last one, but runs a top k', ' private void testOneDimTopKQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (167);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.findKClosest (query, querySize);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (0);', ' result1 = myTree.findKClosest (query, querySize);', ' result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST MULTI-DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimRangeQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' double dist1 = 0;', ' double dist2 = 0;', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' dist1 = Math.sqrt (numDims) * expectedQuerySize / 2.0;', ' dist2 = Math.sqrt (numDims) * expectedQuerySize;', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' // do a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, (int) expectedQuerySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = myTree.findKClosest (query2, (int) expectedQuerySize);', ' ', ' // find the distance to the furthest point in both cases', ' for (int i = 0; i < (int) expectedQuerySize; i++) {', ' double newDist = result1.get (i).getKey ().getDistance (query1);', ' if (newDist > dist1)', ' dist1 = newDist;', ' newDist = result2.get (i).getKey ().getDistance (query2);', ' if (newDist > dist2)', ' dist2 = newDist;', ' }', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.find (query1, dist1);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.find (query1, dist1);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.find (query2, dist2);', ' result2 = hisTree.find (query2, dist2);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimTopKQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, querySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.findKClosest (query1, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.findKClosest (query2, querySize);', ' result2 = hisTree.findKClosest (query2, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' ', ' /**', ' * "TIER 1" TESTS', ' * NONE OF THESE REQUIRE ANY SPLITS', ' */', ' public void testEasy1() {', ' testOneDimRangeQuery (true, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy2() {', ' testOneDimRangeQuery (false, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy3() {', ' testOneDimRangeQuery (true, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy4() {', ' testOneDimRangeQuery (false, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy5() {', ' testMultiDimRangeQuery (true, 1, 5, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy6() {', ' testMultiDimRangeQuery (false, 1, 10, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy7() {', ' testMultiDimRangeQuery (true, 1, 5, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy8() {', ' testMultiDimRangeQuery (false, 1, 15, 10000, 10000, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 2" TESTS', ' * NONE OF THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testMod1() {', ' testOneDimRangeQuery (true, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod2() {', ' testOneDimRangeQuery (false, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod3() {', ' testOneDimRangeQuery (true, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod4() {', ' testOneDimRangeQuery (false, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod5() {', ' testMultiDimRangeQuery (true, 2, 5, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod6() {', ' testMultiDimRangeQuery (false, 2, 10, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod7() {', ' testMultiDimRangeQuery (true, 2, 5, 10000, 100, 1000, 10);', ' }', ' ', ' public void testMod8() {', ' testMultiDimRangeQuery (false, 2, 15, 10000, 100, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 3" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testHard1() {', ' testOneDimRangeQuery (true, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard2() {', ' testOneDimRangeQuery (false, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard3() {', ' testOneDimRangeQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard4() {', ' testOneDimRangeQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard5() {', ' testMultiDimRangeQuery (true, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard6() {', ' testMultiDimRangeQuery (false, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard7() {', ' testMultiDimRangeQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard8() {', ' testMultiDimRangeQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', ' ', ' /**', ' * "TIER 4" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE AND THEY TEST THE TOPK FUNCTIONALITY', ' */', ' ', ' public void testTopK1() {', ' testOneDimTopKQuery (true, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK2() {', ' testOneDimTopKQuery (false, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK3() {', ' testOneDimTopKQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK4() {', ' testOneDimTopKQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK5() {', ' testMultiDimTopKQuery (true, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK6() {', ' testMultiDimTopKQuery (false, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK7() {', ' testMultiDimTopKQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK8() {', ' testMultiDimTopKQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', '}'] | [{'reason_category': 'If Condition', 'usage_line': 216}, {'reason_category': 'If Body', 'usage_line': 216}, {'reason_category': 'Loop Body', 'usage_line': 216}, {'reason_category': 'If Body', 'usage_line': 217}, {'reason_category': 'Loop Body', 'usage_line': 217}, {'reason_category': 'If Body', 'usage_line': 218}, {'reason_category': 'Loop Body', 'usage_line': 218}, {'reason_category': 'If Body', 'usage_line': 219}, {'reason_category': 'Loop Body', 'usage_line': 219}, {'reason_category': 'If Body', 'usage_line': 220}, {'reason_category': 'If Body', 'usage_line': 220}] | Global_Variable 'myList' used at line 216 is defined at line 186 and has a Medium-Range dependency.
Variable 'i' used at line 216 is defined at line 215 and has a Short-Range dependency.
Variable 'distance' used at line 216 is defined at line 208 and has a Short-Range dependency.
Variable 'maxDist' used at line 216 is defined at line 214 and has a Short-Range dependency.
Global_Variable 'myList' used at line 217 is defined at line 186 and has a Long-Range dependency.
Variable 'i' used at line 217 is defined at line 215 and has a Short-Range dependency.
Variable 'distance' used at line 217 is defined at line 208 and has a Short-Range dependency.
Variable 'maxDist' used at line 217 is defined at line 214 and has a Short-Range dependency.
Variable 'i' used at line 218 is defined at line 215 and has a Short-Range dependency.
Variable 'badIndex' used at line 218 is defined at line 213 and has a Short-Range dependency. | {'If Condition': 1, 'If Body': 6, 'Loop Body': 4} | {'Global_Variable Medium-Range': 1, 'Variable Short-Range': 8, 'Global_Variable Long-Range': 1} |
infilling_java | MTreeTester | 213 | 223 | ['import junit.framework.TestCase;', 'import java.util.ArrayList;', 'import java.util.Random;', 'import java.util.Collections;', '', '// this is a map from a set of keys of type PointInMetricSpace to a', '// set of data of type DataType', 'interface IMTree <Key extends IPointInMetricSpace <Key>, Data> {', ' ', ' // insert a new key/data pair into the map', ' void insert (Key keyToAdd, Data dataToAdd);', ' ', ' // find all of the key/data pairs in the map that fall within a', ' // particular distance of query point if no results are found, then', ' // an empty array is returned (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> find (Key query, double distance);', ' ', ' // find the k closest key/data pairs in the map to a particular', ' // query point ', ' //', ' // if the number of points in the map is less than k, then the', ' // returned list will have less than k pairs in it', ' //', ' // if the number of points is zero, then an empty array is returned', ' // (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> findKClosest (Key query, int k);', ' ', ' // returns the number of nodes that exist on a path from root to leaf in the tree...', ' // whtever the details of the implementation are, a tree with a single leaf node should return 1, and a tree', ' // with more than one lead node should return at least two (since it must have at least one internal node).', ' public int depth ();', ' ', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', '', 'interface IDoubleVector {', '', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '', '// this correponds to some geometric object in a metric space; the object is built out of', '// one or more points of type PointInMetricSpace', 'interface IObjectInMetricSpaceABCD <PointInMetricSpace extends IPointInMetricSpace<PointInMetricSpace>> {', ' ', ' // get the maximum distance from some point on the shape to a particular point in the metric space', ' double maxDistanceTo (PointInMetricSpace checkMe);', ' ', ' // return some arbitrary point on the interior of the geometric object', ' PointInMetricSpace getPointInInterior ();', '}', '', '', '// this interface corresponds to a point in some metric space', 'interface IPointInMetricSpace <PointInMetricSpace> {', ' ', ' // get the distance to another point', ' // ', ' // for this to work in an M-Tree, distances should be "metric" and', ' // obey the triangle inequality', ' double getDistance (PointInMetricSpace toMe);', '}', '', '// this is the basic node type in the structure', 'interface IMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> {', ' ', ' // insert a new key/data pair into the structure. The return value is a new MTreeNode if there was', ' // a split in response to the insertion, or a null if there was no split', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd);', ' ', ' // find all of the key/data pairs in the structure that fall within a particular query sphere', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query); ', ' ', ' // find the set of items closest to the given query point', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ);', ' ', ' // returns a sphere that totally encompasses everything in the node and its subtree', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', ' ', ' // returns the depth', ' public int depth ();', '}', '', '// this is a point in a particular metric space', 'class PointABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the point', ' private PointInMetricSpace me;', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return me; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return checkMe.getDistance (me); ', ' }', ' ', ' // contruct a point', ' public PointABCD (PointInMetricSpace useMe) {', ' me = useMe; ', ' }', '}', '', 'class PQueueABCD <PointInMetricSpace, DataType> {', ' ', ' // this is an object in the queue', ' private class Wrapper {', ' DataWrapper <PointInMetricSpace, DataType> myData;', ' double distance;', ' }', ' ', ' // this is the actual queue', ' ArrayList <Wrapper> myList;', ' ', ' // this is the largest distance value currently in the queue', ' double large;', ' ', ' // this is the max number of objects', ' int maxCount;', ' ', ' // create a priority queue with the speced number of slots', ' PQueueABCD (int maxCountIn) {', ' maxCount = maxCountIn;', ' myList = new ArrayList <Wrapper> ();', ' large = 9e99;', ' }', ' ', ' // get the largest distance in the queue', ' double getDist () {', ' return large;', ' }', ' ', ' // add a new object to the queue... the insertion is ignored if the distance value', ' // exceeds the largest that is in the queue and the queue is already full', ' void insert (PointInMetricSpace key, DataType data, double distance) {', ' ', ' // if we are full, remove the one with the largest distance', ' if (myList.size () == maxCount && distance < large) {', ' '] | [' int badIndex = 0;', ' double maxDist = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > maxDist) {', ' maxDist = myList.get (i).distance;', ' badIndex = i;', ' }', ' }', ' ', ' myList.remove (badIndex);', ' }'] | [' ', ' // see if there is room', ' if (myList.size () < maxCount) {', ' ', ' // add it ', ' Wrapper newOne = new Wrapper ();', ' newOne.myData = new DataWrapper <PointInMetricSpace, DataType> (key, data);', ' newOne.distance = distance;', ' myList.add (newOne); ', ' }', ' ', ' // if we are full, reset the max distance', ' if (myList.size () == maxCount) {', ' large = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > large) {', ' large = myList.get (i).distance;', ' }', ' }', ' }', ' ', ' }', ' ', ' // extracts the contents of the queue', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> done () {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' for (int i = 0; i < myList.size (); i++) {', ' returnVal.add (myList.get (i).myData); ', ' }', ' ', ' return returnVal;', ' }', ' ', '}', '', '// this is a sphere in a particular metric space', 'class SphereABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the center of the sphere and its radius', ' private PointInMetricSpace center;', ' private double radius;', ' ', ' // build a sphere out of its center and its radius', ' public SphereABCD (PointInMetricSpace centerIn, double radiusIn) {', ' center = centerIn;', ' radius = radiusIn;', ' }', ' ', ' // increase the size of the sphere so it contains the object swallowMe', ' public void swallow (IObjectInMetricSpaceABCD <PointInMetricSpace> swallowMe) {', ' ', ' // see if we need to increase the radius to swallow this guy', ' double dist = swallowMe.maxDistanceTo (center);', ' if (dist > radius)', ' radius = dist;', ' }', ' ', ' // check to see if a sphere intersects another sphere', ' public boolean intersects (SphereABCD <PointInMetricSpace> me) {', ' return (me.center.getDistance (center) <= me.radius + radius);', ' }', ' ', ' // check to see if the sphere contains a point', ' public boolean contains (PointInMetricSpace checkMe) {', ' return (checkMe.getDistance (center) <= radius);', ' }', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return center; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return radius + checkMe.getDistance (center); ', ' }', '}', '', '', '', 'class OneDimPoint implements IPointInMetricSpace <OneDimPoint> {', ' ', ' // this is the actual double', ' Double value;', ' ', ' // construct this out of a double value', ' public OneDimPoint (double makeFromMe) {', ' value = new Double (makeFromMe);', ' }', ' ', ' // get the distance to another point', ' public double getDistance (OneDimPoint toMe) {', ' if (value > toMe.value)', ' return value - toMe.value;', ' else', ' return toMe.value - value;', ' }', ' ', '}', '', 'class MultiDimPoint implements IPointInMetricSpace <MultiDimPoint> {', ' ', ' // this is the point in a multidimensional space', ' IDoubleVector me;', ' ', ' // make this out of an IDoubleVector', ' public MultiDimPoint (IDoubleVector useMe) {', ' me = useMe;', ' }', ' ', ' // get the Euclidean distance to another point', ' public double getDistance (MultiDimPoint toMe) {', ' double distance = 0.0;', ' try {', ' for (int i = 0; i < me.getLength (); i++) {', ' double diff = me.getItem (i) - toMe.me.getItem (i);', ' diff *= diff;', ' distance += diff;', ' }', ' } catch (OutOfBoundsException e) {', ' throw new IndexOutOfBoundsException ("Can\'t compare two MultiDimPoint objects with different dimensionality!"); ', ' }', ' return Math.sqrt(distance);', ' }', ' ', '}', '// this is a leaf node', 'class LeafMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements ', ' IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myData;', ' ', ' // contructor that takes a data list and builds a node out of it', ' private LeafMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myDataIn) {', ' myData = myDataIn; ', ' }', ' ', ' // constructor that creates an empty node', ' public LeafMTreeNodeABCD () {', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> (); ', ' }', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // just add in the new data', ' myData.add (new PointABCD <PointInMetricSpace> (keyToAdd), dataToAdd);', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> newOne = myData.splitInTwo ();', ' LeafMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' myQ.insert (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData (), ', ' query.getDistance (myData.get (i).getKey ().getPointInInterior ()));', ' }', ' }', ' }', ' ', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' returnVal.add (new DataWrapper <PointInMetricSpace, DataType> (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData ()));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return 1; ', ' }', '', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', '// this silly little class is just a wrapper for a key, data pair', 'class DataWrapper <Key, Data> {', ' ', ' Key key;', ' Data data;', ' ', ' public DataWrapper (Key keyIn, Data dataIn) {', ' key = keyIn;', ' data = dataIn;', ' }', ' ', ' public Key getKey () {', ' return key;', ' }', ' ', ' public Data getData () {', ' return data;', ' }', '}', '', '', '// this is an internal node', 'class InternalMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType>', ' implements IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> myData;', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' // this constructs a new internal node that holds precisely the two nodes that are passed in', ' public InternalMTreeNodeABCD (IMTreeNodeABCD <PointInMetricSpace, DataType> refOne,', ' IMTreeNodeABCD <PointInMetricSpace, DataType> refTwo) {', ' ', ' // create a necw list and add the two guys in', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> ();', ' myData.add (refOne.getBoundingSphere (), refOne);', ' myData.add (refTwo.getBoundingSphere (), refTwo);', ' }', ' ', ' // this constructs a new node that holds the list of data that we were passed in', ' public InternalMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> useMe) {', ' myData = useMe; ', ' }', ' ', ' // from the interface', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // find the best child; this is the one we are closest to', ' double bestDist = 9e99;', ' int bestIndex = 0;', ' for (int i = 0; i < myData.size (); i++) {', ' ', ' double newDist = myData.get (i).getKey ().getPointInInterior ().getDistance (keyToAdd);', ' if (newDist < bestDist) {', ' bestDist = newDist;', ' bestIndex = i;', ' }', ' }', ' ', ' // do the recursive insert', ' IMTreeNodeABCD <PointInMetricSpace, DataType> newRef = myData.get (bestIndex).getData ().insert (keyToAdd, dataToAdd);', ' ', ' // if we got something back, then there was a split, so add the new node into our list', ' if (newRef != null) {', ' myData.add (newRef.getBoundingSphere (), newRef);', ' }', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> newOne = myData.splitInTwo ();', ' InternalMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.intersects (myData.get (i).getKey ())) {', ' myData.get (i).getData ().findKClosest (query, myQ);', ' }', ' }', ' }', ' ', ' // from the interface', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.intersects (myData.get (i).getKey ())) {', ' returnVal.addAll (myData.get (i).getData ().find (query));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return myData.get (0).getData ().depth () + 1; ', ' }', ' ', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', 'abstract class AMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> implements IMetricDataListABCD <PointInMetricSpace,KeyType, DataType> {', '', ' // this is the data that is actually stored in the list', ' private ArrayList <DataWrapper <KeyType, DataType>> myData;', ' ', ' // this is the sphere that bounds everything in the list', ' private SphereABCD <PointInMetricSpace> myBoundingSphere;', ' ', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myBoundingSphere; ', ' }', ' ', ' public int size () {', ' if (myData != null)', ' return myData.size (); ', ' else', ' return 0;', ' }', ' ', ' public DataWrapper <KeyType, DataType> get (int pos) {', ' return myData.get (pos);', ' }', ' ', ' public void replaceKey (int pos, KeyType keyToAdd) {', ' DataWrapper <KeyType, DataType> temp = myData.remove (pos);', ' DataWrapper <KeyType, DataType> newOne = new DataWrapper <KeyType, DataType> (keyToAdd, temp.getData ());', ' myData.add (pos, newOne);', ' }', ' ', ' public void add (KeyType keyToAdd, DataType dataToAdd) {', ' ', ' // if this is the first add, then set everyone up', ' if (myData == null) {', ' PointInMetricSpace myCentroid = keyToAdd.getPointInInterior ();', ' myBoundingSphere = new SphereABCD <PointInMetricSpace> (myCentroid, keyToAdd.maxDistanceTo (myCentroid));', ' myData = new ArrayList <DataWrapper <KeyType, DataType>> ();', ' ', ' // otherwise, extend the sphere if needed', ' } else {', ' myBoundingSphere.swallow (keyToAdd);', ' }', ' ', ' // add the data', ' myData.add (new DataWrapper <KeyType, DataType> (keyToAdd, dataToAdd));', ' }', ' ', ' // we want to potentially allow many implementations of the splitting lalgorithm', ' abstract public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // this is here so the actual splitting algorithn can access the list and change the sphere', ' protected ArrayList <DataWrapper <KeyType, DataType>> getList () {', ' return myData;', ' }', ' ', ' // this is here so the splitting algorithm can modify the list and the sphere', ' protected void replaceGuts (AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> withMe) {', ' myData = withMe.myData;', ' myBoundingSphere = withMe.myBoundingSphere;', ' }', ' ', '}', '', '// this is a particular implementation of the metric data list that uses a simple quadratic clustering', '// algorithm to perform a list split. It picks two "seeds" (the most distant objects) and then repeatedly', '// adds to the two new lists by choosing the objects closest to the seeds', 'class ChrisMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> extends AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> {', '', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo () {', ' ', ' // first, we need to find the two most distant points in the list', ' ArrayList <DataWrapper <KeyType, DataType>> myData = getList ();', ' int bestI = 0, bestJ = 0;', ' double maxDist = -1.0;', ' for (int i = 0; i < myData.size (); i++) {', ' for (int j = i + 1; j < myData.size (); j++) {', ' ', ' // get the two keys', ' DataWrapper <KeyType, DataType> pointOne = myData.get (i);', ' DataWrapper <KeyType, DataType> pointTwo = myData.get (j);', ' ', ' // find the difference between them', ' double curDist = pointOne.getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', '', ' // see if it is the biggest', ' if (curDist > maxDist) {', ' maxDist = curDist;', ' bestI = i;', ' bestJ = j;', ' }', ' }', ' }', ' ', ' // now, we have the best two points; those are seeds for the clustering', ' DataWrapper <KeyType, DataType> pointOne = myData.remove (bestI);', ' DataWrapper <KeyType, DataType> pointTwo = myData.remove (bestJ - 1);', ' ', ' // these are the two new lists', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listOne = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listTwo = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' ', ' // put the two seeds in', ' listOne.add (pointOne.getKey (), pointOne.getData ());', ' listTwo.add (pointTwo.getKey (), pointTwo.getData ());', ' ', ' // and add everyone else in', ' while (myData.size () != 0) {', ' ', ' // find the one closest to the first seed', ' int bestIndex = 0;', ' double bestDist = 9e99;', ' ', ' // loop thru all of the candidate data objects', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listOne.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' ', ' // break if no more data', ' if (myData.size () == 0)', ' break;', ' ', ' // loop thru all of the candidate data objects', ' bestDist = 9e99;', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listTwo.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' }', ' ', ' // now we replace our own guts with the first list', ' replaceGuts (listOne);', ' ', ' // and return the other list', ' return listTwo;', ' }', '}', '', 'interface IMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> {', ' ', ' // add a new pair to the list', ' public void add (KeyType keyToAdd, DataType dataToAdd);', ' ', ' // replace a key at the indicated position', ' public void replaceKey (int pos, KeyType keyToAdd);', ' ', ' // get the key, data pair that resides at a particular position', ' public DataWrapper <KeyType, DataType> get (int pos);', ' ', ' // return the number of items in the list', ' public int size ();', ' ', ' // split the list in two, using some clutering algorithm', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // get a sphere that totally bounds all of the objects in the list', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class MTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public MTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class SCMTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public SCMTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', '', 'public class MTreeTester extends TestCase {', ' ', ' // compare two lists of strings to see if the contents are the same', ' private boolean compareStringSets (ArrayList <String> setOne, ArrayList <String> setTwo) {', ' ', ' // sort the sets and make sure they are the same', ' boolean returnVal = true;', ' if (setOne.size () == setTwo.size ()) {', ' Collections.sort (setOne);', ' Collections.sort (setTwo);', ' for (int i = 0; i < setOne.size (); i++) {', ' if (!setOne.get (i).equals (setTwo.get (i))) {', ' returnVal = false;', ' break; ', ' }', ' }', ' } else {', ' returnVal = false;', ' }', ' ', ' // print out the result', ' System.out.println ("**** Expected:");', ' for (int i = 0; i < setOne.size (); i++) {', ' System.out.format (setOne.get (i) + " ");', ' }', ' System.out.println ("\\n**** Got:");', ' for (int i = 0; i < setTwo.size (); i++) {', ' System.out.format (setTwo.get (i) + " ");', ' }', ' System.out.println ("");', ' ', ' return returnVal;', ' }', ' ', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST SIMPLE ONE DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testOneDimRangeQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.find (query, expectedQuerySize / 2);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.find (query, expectedQuerySize / 2);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (numPoints);', ' result1 = myTree.find (query, expectedQuerySize);', ' result2 = hisTree.find (query, expectedQuerySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // like the last one, but runs a top k', ' private void testOneDimTopKQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (167);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.findKClosest (query, querySize);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (0);', ' result1 = myTree.findKClosest (query, querySize);', ' result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST MULTI-DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimRangeQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' double dist1 = 0;', ' double dist2 = 0;', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' dist1 = Math.sqrt (numDims) * expectedQuerySize / 2.0;', ' dist2 = Math.sqrt (numDims) * expectedQuerySize;', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' // do a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, (int) expectedQuerySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = myTree.findKClosest (query2, (int) expectedQuerySize);', ' ', ' // find the distance to the furthest point in both cases', ' for (int i = 0; i < (int) expectedQuerySize; i++) {', ' double newDist = result1.get (i).getKey ().getDistance (query1);', ' if (newDist > dist1)', ' dist1 = newDist;', ' newDist = result2.get (i).getKey ().getDistance (query2);', ' if (newDist > dist2)', ' dist2 = newDist;', ' }', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.find (query1, dist1);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.find (query1, dist1);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.find (query2, dist2);', ' result2 = hisTree.find (query2, dist2);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimTopKQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, querySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.findKClosest (query1, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.findKClosest (query2, querySize);', ' result2 = hisTree.findKClosest (query2, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' ', ' /**', ' * "TIER 1" TESTS', ' * NONE OF THESE REQUIRE ANY SPLITS', ' */', ' public void testEasy1() {', ' testOneDimRangeQuery (true, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy2() {', ' testOneDimRangeQuery (false, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy3() {', ' testOneDimRangeQuery (true, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy4() {', ' testOneDimRangeQuery (false, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy5() {', ' testMultiDimRangeQuery (true, 1, 5, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy6() {', ' testMultiDimRangeQuery (false, 1, 10, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy7() {', ' testMultiDimRangeQuery (true, 1, 5, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy8() {', ' testMultiDimRangeQuery (false, 1, 15, 10000, 10000, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 2" TESTS', ' * NONE OF THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testMod1() {', ' testOneDimRangeQuery (true, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod2() {', ' testOneDimRangeQuery (false, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod3() {', ' testOneDimRangeQuery (true, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod4() {', ' testOneDimRangeQuery (false, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod5() {', ' testMultiDimRangeQuery (true, 2, 5, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod6() {', ' testMultiDimRangeQuery (false, 2, 10, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod7() {', ' testMultiDimRangeQuery (true, 2, 5, 10000, 100, 1000, 10);', ' }', ' ', ' public void testMod8() {', ' testMultiDimRangeQuery (false, 2, 15, 10000, 100, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 3" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testHard1() {', ' testOneDimRangeQuery (true, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard2() {', ' testOneDimRangeQuery (false, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard3() {', ' testOneDimRangeQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard4() {', ' testOneDimRangeQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard5() {', ' testMultiDimRangeQuery (true, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard6() {', ' testMultiDimRangeQuery (false, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard7() {', ' testMultiDimRangeQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard8() {', ' testMultiDimRangeQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', ' ', ' /**', ' * "TIER 4" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE AND THEY TEST THE TOPK FUNCTIONALITY', ' */', ' ', ' public void testTopK1() {', ' testOneDimTopKQuery (true, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK2() {', ' testOneDimTopKQuery (false, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK3() {', ' testOneDimTopKQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK4() {', ' testOneDimTopKQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK5() {', ' testMultiDimTopKQuery (true, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK6() {', ' testMultiDimTopKQuery (false, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK7() {', ' testMultiDimTopKQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK8() {', ' testMultiDimTopKQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', '}'] | [{'reason_category': 'If Body', 'usage_line': 213}, {'reason_category': 'If Body', 'usage_line': 214}, {'reason_category': 'If Body', 'usage_line': 215}, {'reason_category': 'Define Stop Criteria', 'usage_line': 215}, {'reason_category': 'If Condition', 'usage_line': 216}, {'reason_category': 'If Body', 'usage_line': 216}, {'reason_category': 'Loop Body', 'usage_line': 216}, {'reason_category': 'If Body', 'usage_line': 217}, {'reason_category': 'Loop Body', 'usage_line': 217}, {'reason_category': 'If Body', 'usage_line': 218}, {'reason_category': 'Loop Body', 'usage_line': 218}, {'reason_category': 'If Body', 'usage_line': 219}, {'reason_category': 'Loop Body', 'usage_line': 219}, {'reason_category': 'If Body', 'usage_line': 220}, {'reason_category': 'If Body', 'usage_line': 220}, {'reason_category': 'If Body', 'usage_line': 221}, {'reason_category': 'If Body', 'usage_line': 222}, {'reason_category': 'If Body', 'usage_line': 223}] | Variable 'i' used at line 215 is defined at line 215 and has a Short-Range dependency.
Global_Variable 'myList' used at line 215 is defined at line 186 and has a Medium-Range dependency.
Global_Variable 'myList' used at line 216 is defined at line 186 and has a Medium-Range dependency.
Variable 'i' used at line 216 is defined at line 215 and has a Short-Range dependency.
Variable 'distance' used at line 216 is defined at line 208 and has a Short-Range dependency.
Variable 'maxDist' used at line 216 is defined at line 214 and has a Short-Range dependency.
Global_Variable 'myList' used at line 217 is defined at line 186 and has a Long-Range dependency.
Variable 'i' used at line 217 is defined at line 215 and has a Short-Range dependency.
Variable 'distance' used at line 217 is defined at line 208 and has a Short-Range dependency.
Variable 'maxDist' used at line 217 is defined at line 214 and has a Short-Range dependency.
Variable 'i' used at line 218 is defined at line 215 and has a Short-Range dependency.
Variable 'badIndex' used at line 218 is defined at line 213 and has a Short-Range dependency.
Global_Variable 'myList' used at line 222 is defined at line 186 and has a Long-Range dependency.
Variable 'badIndex' used at line 222 is defined at line 213 and has a Short-Range dependency. | {'If Body': 12, 'Define Stop Criteria': 1, 'If Condition': 1, 'Loop Body': 4} | {'Variable Short-Range': 10, 'Global_Variable Medium-Range': 2, 'Global_Variable Long-Range': 2} |
infilling_java | MTreeTester | 229 | 233 | ['import junit.framework.TestCase;', 'import java.util.ArrayList;', 'import java.util.Random;', 'import java.util.Collections;', '', '// this is a map from a set of keys of type PointInMetricSpace to a', '// set of data of type DataType', 'interface IMTree <Key extends IPointInMetricSpace <Key>, Data> {', ' ', ' // insert a new key/data pair into the map', ' void insert (Key keyToAdd, Data dataToAdd);', ' ', ' // find all of the key/data pairs in the map that fall within a', ' // particular distance of query point if no results are found, then', ' // an empty array is returned (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> find (Key query, double distance);', ' ', ' // find the k closest key/data pairs in the map to a particular', ' // query point ', ' //', ' // if the number of points in the map is less than k, then the', ' // returned list will have less than k pairs in it', ' //', ' // if the number of points is zero, then an empty array is returned', ' // (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> findKClosest (Key query, int k);', ' ', ' // returns the number of nodes that exist on a path from root to leaf in the tree...', ' // whtever the details of the implementation are, a tree with a single leaf node should return 1, and a tree', ' // with more than one lead node should return at least two (since it must have at least one internal node).', ' public int depth ();', ' ', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', '', 'interface IDoubleVector {', '', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '', '// this correponds to some geometric object in a metric space; the object is built out of', '// one or more points of type PointInMetricSpace', 'interface IObjectInMetricSpaceABCD <PointInMetricSpace extends IPointInMetricSpace<PointInMetricSpace>> {', ' ', ' // get the maximum distance from some point on the shape to a particular point in the metric space', ' double maxDistanceTo (PointInMetricSpace checkMe);', ' ', ' // return some arbitrary point on the interior of the geometric object', ' PointInMetricSpace getPointInInterior ();', '}', '', '', '// this interface corresponds to a point in some metric space', 'interface IPointInMetricSpace <PointInMetricSpace> {', ' ', ' // get the distance to another point', ' // ', ' // for this to work in an M-Tree, distances should be "metric" and', ' // obey the triangle inequality', ' double getDistance (PointInMetricSpace toMe);', '}', '', '// this is the basic node type in the structure', 'interface IMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> {', ' ', ' // insert a new key/data pair into the structure. The return value is a new MTreeNode if there was', ' // a split in response to the insertion, or a null if there was no split', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd);', ' ', ' // find all of the key/data pairs in the structure that fall within a particular query sphere', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query); ', ' ', ' // find the set of items closest to the given query point', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ);', ' ', ' // returns a sphere that totally encompasses everything in the node and its subtree', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', ' ', ' // returns the depth', ' public int depth ();', '}', '', '// this is a point in a particular metric space', 'class PointABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the point', ' private PointInMetricSpace me;', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return me; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return checkMe.getDistance (me); ', ' }', ' ', ' // contruct a point', ' public PointABCD (PointInMetricSpace useMe) {', ' me = useMe; ', ' }', '}', '', 'class PQueueABCD <PointInMetricSpace, DataType> {', ' ', ' // this is an object in the queue', ' private class Wrapper {', ' DataWrapper <PointInMetricSpace, DataType> myData;', ' double distance;', ' }', ' ', ' // this is the actual queue', ' ArrayList <Wrapper> myList;', ' ', ' // this is the largest distance value currently in the queue', ' double large;', ' ', ' // this is the max number of objects', ' int maxCount;', ' ', ' // create a priority queue with the speced number of slots', ' PQueueABCD (int maxCountIn) {', ' maxCount = maxCountIn;', ' myList = new ArrayList <Wrapper> ();', ' large = 9e99;', ' }', ' ', ' // get the largest distance in the queue', ' double getDist () {', ' return large;', ' }', ' ', ' // add a new object to the queue... the insertion is ignored if the distance value', ' // exceeds the largest that is in the queue and the queue is already full', ' void insert (PointInMetricSpace key, DataType data, double distance) {', ' ', ' // if we are full, remove the one with the largest distance', ' if (myList.size () == maxCount && distance < large) {', ' ', ' int badIndex = 0;', ' double maxDist = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > maxDist) {', ' maxDist = myList.get (i).distance;', ' badIndex = i;', ' }', ' }', ' ', ' myList.remove (badIndex);', ' }', ' ', ' // see if there is room', ' if (myList.size () < maxCount) {', ' ', ' // add it '] | [' Wrapper newOne = new Wrapper ();', ' newOne.myData = new DataWrapper <PointInMetricSpace, DataType> (key, data);', ' newOne.distance = distance;', ' myList.add (newOne); ', ' }'] | [' ', ' // if we are full, reset the max distance', ' if (myList.size () == maxCount) {', ' large = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > large) {', ' large = myList.get (i).distance;', ' }', ' }', ' }', ' ', ' }', ' ', ' // extracts the contents of the queue', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> done () {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' for (int i = 0; i < myList.size (); i++) {', ' returnVal.add (myList.get (i).myData); ', ' }', ' ', ' return returnVal;', ' }', ' ', '}', '', '// this is a sphere in a particular metric space', 'class SphereABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the center of the sphere and its radius', ' private PointInMetricSpace center;', ' private double radius;', ' ', ' // build a sphere out of its center and its radius', ' public SphereABCD (PointInMetricSpace centerIn, double radiusIn) {', ' center = centerIn;', ' radius = radiusIn;', ' }', ' ', ' // increase the size of the sphere so it contains the object swallowMe', ' public void swallow (IObjectInMetricSpaceABCD <PointInMetricSpace> swallowMe) {', ' ', ' // see if we need to increase the radius to swallow this guy', ' double dist = swallowMe.maxDistanceTo (center);', ' if (dist > radius)', ' radius = dist;', ' }', ' ', ' // check to see if a sphere intersects another sphere', ' public boolean intersects (SphereABCD <PointInMetricSpace> me) {', ' return (me.center.getDistance (center) <= me.radius + radius);', ' }', ' ', ' // check to see if the sphere contains a point', ' public boolean contains (PointInMetricSpace checkMe) {', ' return (checkMe.getDistance (center) <= radius);', ' }', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return center; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return radius + checkMe.getDistance (center); ', ' }', '}', '', '', '', 'class OneDimPoint implements IPointInMetricSpace <OneDimPoint> {', ' ', ' // this is the actual double', ' Double value;', ' ', ' // construct this out of a double value', ' public OneDimPoint (double makeFromMe) {', ' value = new Double (makeFromMe);', ' }', ' ', ' // get the distance to another point', ' public double getDistance (OneDimPoint toMe) {', ' if (value > toMe.value)', ' return value - toMe.value;', ' else', ' return toMe.value - value;', ' }', ' ', '}', '', 'class MultiDimPoint implements IPointInMetricSpace <MultiDimPoint> {', ' ', ' // this is the point in a multidimensional space', ' IDoubleVector me;', ' ', ' // make this out of an IDoubleVector', ' public MultiDimPoint (IDoubleVector useMe) {', ' me = useMe;', ' }', ' ', ' // get the Euclidean distance to another point', ' public double getDistance (MultiDimPoint toMe) {', ' double distance = 0.0;', ' try {', ' for (int i = 0; i < me.getLength (); i++) {', ' double diff = me.getItem (i) - toMe.me.getItem (i);', ' diff *= diff;', ' distance += diff;', ' }', ' } catch (OutOfBoundsException e) {', ' throw new IndexOutOfBoundsException ("Can\'t compare two MultiDimPoint objects with different dimensionality!"); ', ' }', ' return Math.sqrt(distance);', ' }', ' ', '}', '// this is a leaf node', 'class LeafMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements ', ' IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myData;', ' ', ' // contructor that takes a data list and builds a node out of it', ' private LeafMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myDataIn) {', ' myData = myDataIn; ', ' }', ' ', ' // constructor that creates an empty node', ' public LeafMTreeNodeABCD () {', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> (); ', ' }', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // just add in the new data', ' myData.add (new PointABCD <PointInMetricSpace> (keyToAdd), dataToAdd);', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> newOne = myData.splitInTwo ();', ' LeafMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' myQ.insert (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData (), ', ' query.getDistance (myData.get (i).getKey ().getPointInInterior ()));', ' }', ' }', ' }', ' ', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' returnVal.add (new DataWrapper <PointInMetricSpace, DataType> (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData ()));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return 1; ', ' }', '', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', '// this silly little class is just a wrapper for a key, data pair', 'class DataWrapper <Key, Data> {', ' ', ' Key key;', ' Data data;', ' ', ' public DataWrapper (Key keyIn, Data dataIn) {', ' key = keyIn;', ' data = dataIn;', ' }', ' ', ' public Key getKey () {', ' return key;', ' }', ' ', ' public Data getData () {', ' return data;', ' }', '}', '', '', '// this is an internal node', 'class InternalMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType>', ' implements IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> myData;', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' // this constructs a new internal node that holds precisely the two nodes that are passed in', ' public InternalMTreeNodeABCD (IMTreeNodeABCD <PointInMetricSpace, DataType> refOne,', ' IMTreeNodeABCD <PointInMetricSpace, DataType> refTwo) {', ' ', ' // create a necw list and add the two guys in', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> ();', ' myData.add (refOne.getBoundingSphere (), refOne);', ' myData.add (refTwo.getBoundingSphere (), refTwo);', ' }', ' ', ' // this constructs a new node that holds the list of data that we were passed in', ' public InternalMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> useMe) {', ' myData = useMe; ', ' }', ' ', ' // from the interface', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // find the best child; this is the one we are closest to', ' double bestDist = 9e99;', ' int bestIndex = 0;', ' for (int i = 0; i < myData.size (); i++) {', ' ', ' double newDist = myData.get (i).getKey ().getPointInInterior ().getDistance (keyToAdd);', ' if (newDist < bestDist) {', ' bestDist = newDist;', ' bestIndex = i;', ' }', ' }', ' ', ' // do the recursive insert', ' IMTreeNodeABCD <PointInMetricSpace, DataType> newRef = myData.get (bestIndex).getData ().insert (keyToAdd, dataToAdd);', ' ', ' // if we got something back, then there was a split, so add the new node into our list', ' if (newRef != null) {', ' myData.add (newRef.getBoundingSphere (), newRef);', ' }', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> newOne = myData.splitInTwo ();', ' InternalMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.intersects (myData.get (i).getKey ())) {', ' myData.get (i).getData ().findKClosest (query, myQ);', ' }', ' }', ' }', ' ', ' // from the interface', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.intersects (myData.get (i).getKey ())) {', ' returnVal.addAll (myData.get (i).getData ().find (query));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return myData.get (0).getData ().depth () + 1; ', ' }', ' ', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', 'abstract class AMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> implements IMetricDataListABCD <PointInMetricSpace,KeyType, DataType> {', '', ' // this is the data that is actually stored in the list', ' private ArrayList <DataWrapper <KeyType, DataType>> myData;', ' ', ' // this is the sphere that bounds everything in the list', ' private SphereABCD <PointInMetricSpace> myBoundingSphere;', ' ', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myBoundingSphere; ', ' }', ' ', ' public int size () {', ' if (myData != null)', ' return myData.size (); ', ' else', ' return 0;', ' }', ' ', ' public DataWrapper <KeyType, DataType> get (int pos) {', ' return myData.get (pos);', ' }', ' ', ' public void replaceKey (int pos, KeyType keyToAdd) {', ' DataWrapper <KeyType, DataType> temp = myData.remove (pos);', ' DataWrapper <KeyType, DataType> newOne = new DataWrapper <KeyType, DataType> (keyToAdd, temp.getData ());', ' myData.add (pos, newOne);', ' }', ' ', ' public void add (KeyType keyToAdd, DataType dataToAdd) {', ' ', ' // if this is the first add, then set everyone up', ' if (myData == null) {', ' PointInMetricSpace myCentroid = keyToAdd.getPointInInterior ();', ' myBoundingSphere = new SphereABCD <PointInMetricSpace> (myCentroid, keyToAdd.maxDistanceTo (myCentroid));', ' myData = new ArrayList <DataWrapper <KeyType, DataType>> ();', ' ', ' // otherwise, extend the sphere if needed', ' } else {', ' myBoundingSphere.swallow (keyToAdd);', ' }', ' ', ' // add the data', ' myData.add (new DataWrapper <KeyType, DataType> (keyToAdd, dataToAdd));', ' }', ' ', ' // we want to potentially allow many implementations of the splitting lalgorithm', ' abstract public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // this is here so the actual splitting algorithn can access the list and change the sphere', ' protected ArrayList <DataWrapper <KeyType, DataType>> getList () {', ' return myData;', ' }', ' ', ' // this is here so the splitting algorithm can modify the list and the sphere', ' protected void replaceGuts (AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> withMe) {', ' myData = withMe.myData;', ' myBoundingSphere = withMe.myBoundingSphere;', ' }', ' ', '}', '', '// this is a particular implementation of the metric data list that uses a simple quadratic clustering', '// algorithm to perform a list split. It picks two "seeds" (the most distant objects) and then repeatedly', '// adds to the two new lists by choosing the objects closest to the seeds', 'class ChrisMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> extends AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> {', '', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo () {', ' ', ' // first, we need to find the two most distant points in the list', ' ArrayList <DataWrapper <KeyType, DataType>> myData = getList ();', ' int bestI = 0, bestJ = 0;', ' double maxDist = -1.0;', ' for (int i = 0; i < myData.size (); i++) {', ' for (int j = i + 1; j < myData.size (); j++) {', ' ', ' // get the two keys', ' DataWrapper <KeyType, DataType> pointOne = myData.get (i);', ' DataWrapper <KeyType, DataType> pointTwo = myData.get (j);', ' ', ' // find the difference between them', ' double curDist = pointOne.getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', '', ' // see if it is the biggest', ' if (curDist > maxDist) {', ' maxDist = curDist;', ' bestI = i;', ' bestJ = j;', ' }', ' }', ' }', ' ', ' // now, we have the best two points; those are seeds for the clustering', ' DataWrapper <KeyType, DataType> pointOne = myData.remove (bestI);', ' DataWrapper <KeyType, DataType> pointTwo = myData.remove (bestJ - 1);', ' ', ' // these are the two new lists', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listOne = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listTwo = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' ', ' // put the two seeds in', ' listOne.add (pointOne.getKey (), pointOne.getData ());', ' listTwo.add (pointTwo.getKey (), pointTwo.getData ());', ' ', ' // and add everyone else in', ' while (myData.size () != 0) {', ' ', ' // find the one closest to the first seed', ' int bestIndex = 0;', ' double bestDist = 9e99;', ' ', ' // loop thru all of the candidate data objects', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listOne.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' ', ' // break if no more data', ' if (myData.size () == 0)', ' break;', ' ', ' // loop thru all of the candidate data objects', ' bestDist = 9e99;', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listTwo.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' }', ' ', ' // now we replace our own guts with the first list', ' replaceGuts (listOne);', ' ', ' // and return the other list', ' return listTwo;', ' }', '}', '', 'interface IMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> {', ' ', ' // add a new pair to the list', ' public void add (KeyType keyToAdd, DataType dataToAdd);', ' ', ' // replace a key at the indicated position', ' public void replaceKey (int pos, KeyType keyToAdd);', ' ', ' // get the key, data pair that resides at a particular position', ' public DataWrapper <KeyType, DataType> get (int pos);', ' ', ' // return the number of items in the list', ' public int size ();', ' ', ' // split the list in two, using some clutering algorithm', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // get a sphere that totally bounds all of the objects in the list', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class MTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public MTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class SCMTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public SCMTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', '', 'public class MTreeTester extends TestCase {', ' ', ' // compare two lists of strings to see if the contents are the same', ' private boolean compareStringSets (ArrayList <String> setOne, ArrayList <String> setTwo) {', ' ', ' // sort the sets and make sure they are the same', ' boolean returnVal = true;', ' if (setOne.size () == setTwo.size ()) {', ' Collections.sort (setOne);', ' Collections.sort (setTwo);', ' for (int i = 0; i < setOne.size (); i++) {', ' if (!setOne.get (i).equals (setTwo.get (i))) {', ' returnVal = false;', ' break; ', ' }', ' }', ' } else {', ' returnVal = false;', ' }', ' ', ' // print out the result', ' System.out.println ("**** Expected:");', ' for (int i = 0; i < setOne.size (); i++) {', ' System.out.format (setOne.get (i) + " ");', ' }', ' System.out.println ("\\n**** Got:");', ' for (int i = 0; i < setTwo.size (); i++) {', ' System.out.format (setTwo.get (i) + " ");', ' }', ' System.out.println ("");', ' ', ' return returnVal;', ' }', ' ', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST SIMPLE ONE DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testOneDimRangeQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.find (query, expectedQuerySize / 2);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.find (query, expectedQuerySize / 2);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (numPoints);', ' result1 = myTree.find (query, expectedQuerySize);', ' result2 = hisTree.find (query, expectedQuerySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // like the last one, but runs a top k', ' private void testOneDimTopKQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (167);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.findKClosest (query, querySize);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (0);', ' result1 = myTree.findKClosest (query, querySize);', ' result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST MULTI-DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimRangeQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' double dist1 = 0;', ' double dist2 = 0;', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' dist1 = Math.sqrt (numDims) * expectedQuerySize / 2.0;', ' dist2 = Math.sqrt (numDims) * expectedQuerySize;', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' // do a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, (int) expectedQuerySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = myTree.findKClosest (query2, (int) expectedQuerySize);', ' ', ' // find the distance to the furthest point in both cases', ' for (int i = 0; i < (int) expectedQuerySize; i++) {', ' double newDist = result1.get (i).getKey ().getDistance (query1);', ' if (newDist > dist1)', ' dist1 = newDist;', ' newDist = result2.get (i).getKey ().getDistance (query2);', ' if (newDist > dist2)', ' dist2 = newDist;', ' }', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.find (query1, dist1);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.find (query1, dist1);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.find (query2, dist2);', ' result2 = hisTree.find (query2, dist2);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimTopKQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, querySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.findKClosest (query1, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.findKClosest (query2, querySize);', ' result2 = hisTree.findKClosest (query2, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' ', ' /**', ' * "TIER 1" TESTS', ' * NONE OF THESE REQUIRE ANY SPLITS', ' */', ' public void testEasy1() {', ' testOneDimRangeQuery (true, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy2() {', ' testOneDimRangeQuery (false, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy3() {', ' testOneDimRangeQuery (true, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy4() {', ' testOneDimRangeQuery (false, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy5() {', ' testMultiDimRangeQuery (true, 1, 5, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy6() {', ' testMultiDimRangeQuery (false, 1, 10, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy7() {', ' testMultiDimRangeQuery (true, 1, 5, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy8() {', ' testMultiDimRangeQuery (false, 1, 15, 10000, 10000, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 2" TESTS', ' * NONE OF THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testMod1() {', ' testOneDimRangeQuery (true, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod2() {', ' testOneDimRangeQuery (false, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod3() {', ' testOneDimRangeQuery (true, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod4() {', ' testOneDimRangeQuery (false, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod5() {', ' testMultiDimRangeQuery (true, 2, 5, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod6() {', ' testMultiDimRangeQuery (false, 2, 10, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod7() {', ' testMultiDimRangeQuery (true, 2, 5, 10000, 100, 1000, 10);', ' }', ' ', ' public void testMod8() {', ' testMultiDimRangeQuery (false, 2, 15, 10000, 100, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 3" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testHard1() {', ' testOneDimRangeQuery (true, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard2() {', ' testOneDimRangeQuery (false, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard3() {', ' testOneDimRangeQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard4() {', ' testOneDimRangeQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard5() {', ' testMultiDimRangeQuery (true, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard6() {', ' testMultiDimRangeQuery (false, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard7() {', ' testMultiDimRangeQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard8() {', ' testMultiDimRangeQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', ' ', ' /**', ' * "TIER 4" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE AND THEY TEST THE TOPK FUNCTIONALITY', ' */', ' ', ' public void testTopK1() {', ' testOneDimTopKQuery (true, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK2() {', ' testOneDimTopKQuery (false, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK3() {', ' testOneDimTopKQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK4() {', ' testOneDimTopKQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK5() {', ' testMultiDimTopKQuery (true, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK6() {', ' testMultiDimTopKQuery (false, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK7() {', ' testMultiDimTopKQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK8() {', ' testMultiDimTopKQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', '}'] | [{'reason_category': 'If Body', 'usage_line': 229}, {'reason_category': 'If Body', 'usage_line': 230}, {'reason_category': 'If Body', 'usage_line': 231}, {'reason_category': 'If Body', 'usage_line': 232}, {'reason_category': 'If Body', 'usage_line': 233}] | Class 'Wrapper' used at line 229 is defined at line 180 and has a Long-Range dependency.
Class 'DataWrapper' used at line 230 is defined at line 429 and has a Long-Range dependency.
Variable 'key' used at line 230 is defined at line 208 and has a Medium-Range dependency.
Variable 'data' used at line 230 is defined at line 208 and has a Medium-Range dependency.
Variable 'newOne' used at line 230 is defined at line 229 and has a Short-Range dependency.
Variable 'distance' used at line 231 is defined at line 208 and has a Medium-Range dependency.
Variable 'newOne' used at line 231 is defined at line 229 and has a Short-Range dependency.
Global_Variable 'myList' used at line 232 is defined at line 186 and has a Long-Range dependency.
Variable 'newOne' used at line 232 is defined at line 229 and has a Short-Range dependency. | {'If Body': 5} | {'Class Long-Range': 2, 'Variable Medium-Range': 3, 'Variable Short-Range': 3, 'Global_Variable Long-Range': 1} |
infilling_java | MTreeTester | 240 | 241 | ['import junit.framework.TestCase;', 'import java.util.ArrayList;', 'import java.util.Random;', 'import java.util.Collections;', '', '// this is a map from a set of keys of type PointInMetricSpace to a', '// set of data of type DataType', 'interface IMTree <Key extends IPointInMetricSpace <Key>, Data> {', ' ', ' // insert a new key/data pair into the map', ' void insert (Key keyToAdd, Data dataToAdd);', ' ', ' // find all of the key/data pairs in the map that fall within a', ' // particular distance of query point if no results are found, then', ' // an empty array is returned (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> find (Key query, double distance);', ' ', ' // find the k closest key/data pairs in the map to a particular', ' // query point ', ' //', ' // if the number of points in the map is less than k, then the', ' // returned list will have less than k pairs in it', ' //', ' // if the number of points is zero, then an empty array is returned', ' // (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> findKClosest (Key query, int k);', ' ', ' // returns the number of nodes that exist on a path from root to leaf in the tree...', ' // whtever the details of the implementation are, a tree with a single leaf node should return 1, and a tree', ' // with more than one lead node should return at least two (since it must have at least one internal node).', ' public int depth ();', ' ', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', '', 'interface IDoubleVector {', '', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '', '// this correponds to some geometric object in a metric space; the object is built out of', '// one or more points of type PointInMetricSpace', 'interface IObjectInMetricSpaceABCD <PointInMetricSpace extends IPointInMetricSpace<PointInMetricSpace>> {', ' ', ' // get the maximum distance from some point on the shape to a particular point in the metric space', ' double maxDistanceTo (PointInMetricSpace checkMe);', ' ', ' // return some arbitrary point on the interior of the geometric object', ' PointInMetricSpace getPointInInterior ();', '}', '', '', '// this interface corresponds to a point in some metric space', 'interface IPointInMetricSpace <PointInMetricSpace> {', ' ', ' // get the distance to another point', ' // ', ' // for this to work in an M-Tree, distances should be "metric" and', ' // obey the triangle inequality', ' double getDistance (PointInMetricSpace toMe);', '}', '', '// this is the basic node type in the structure', 'interface IMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> {', ' ', ' // insert a new key/data pair into the structure. The return value is a new MTreeNode if there was', ' // a split in response to the insertion, or a null if there was no split', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd);', ' ', ' // find all of the key/data pairs in the structure that fall within a particular query sphere', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query); ', ' ', ' // find the set of items closest to the given query point', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ);', ' ', ' // returns a sphere that totally encompasses everything in the node and its subtree', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', ' ', ' // returns the depth', ' public int depth ();', '}', '', '// this is a point in a particular metric space', 'class PointABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the point', ' private PointInMetricSpace me;', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return me; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return checkMe.getDistance (me); ', ' }', ' ', ' // contruct a point', ' public PointABCD (PointInMetricSpace useMe) {', ' me = useMe; ', ' }', '}', '', 'class PQueueABCD <PointInMetricSpace, DataType> {', ' ', ' // this is an object in the queue', ' private class Wrapper {', ' DataWrapper <PointInMetricSpace, DataType> myData;', ' double distance;', ' }', ' ', ' // this is the actual queue', ' ArrayList <Wrapper> myList;', ' ', ' // this is the largest distance value currently in the queue', ' double large;', ' ', ' // this is the max number of objects', ' int maxCount;', ' ', ' // create a priority queue with the speced number of slots', ' PQueueABCD (int maxCountIn) {', ' maxCount = maxCountIn;', ' myList = new ArrayList <Wrapper> ();', ' large = 9e99;', ' }', ' ', ' // get the largest distance in the queue', ' double getDist () {', ' return large;', ' }', ' ', ' // add a new object to the queue... the insertion is ignored if the distance value', ' // exceeds the largest that is in the queue and the queue is already full', ' void insert (PointInMetricSpace key, DataType data, double distance) {', ' ', ' // if we are full, remove the one with the largest distance', ' if (myList.size () == maxCount && distance < large) {', ' ', ' int badIndex = 0;', ' double maxDist = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > maxDist) {', ' maxDist = myList.get (i).distance;', ' badIndex = i;', ' }', ' }', ' ', ' myList.remove (badIndex);', ' }', ' ', ' // see if there is room', ' if (myList.size () < maxCount) {', ' ', ' // add it ', ' Wrapper newOne = new Wrapper ();', ' newOne.myData = new DataWrapper <PointInMetricSpace, DataType> (key, data);', ' newOne.distance = distance;', ' myList.add (newOne); ', ' }', ' ', ' // if we are full, reset the max distance', ' if (myList.size () == maxCount) {', ' large = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > large) {'] | [' large = myList.get (i).distance;', ' }'] | [' }', ' }', ' ', ' }', ' ', ' // extracts the contents of the queue', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> done () {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' for (int i = 0; i < myList.size (); i++) {', ' returnVal.add (myList.get (i).myData); ', ' }', ' ', ' return returnVal;', ' }', ' ', '}', '', '// this is a sphere in a particular metric space', 'class SphereABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the center of the sphere and its radius', ' private PointInMetricSpace center;', ' private double radius;', ' ', ' // build a sphere out of its center and its radius', ' public SphereABCD (PointInMetricSpace centerIn, double radiusIn) {', ' center = centerIn;', ' radius = radiusIn;', ' }', ' ', ' // increase the size of the sphere so it contains the object swallowMe', ' public void swallow (IObjectInMetricSpaceABCD <PointInMetricSpace> swallowMe) {', ' ', ' // see if we need to increase the radius to swallow this guy', ' double dist = swallowMe.maxDistanceTo (center);', ' if (dist > radius)', ' radius = dist;', ' }', ' ', ' // check to see if a sphere intersects another sphere', ' public boolean intersects (SphereABCD <PointInMetricSpace> me) {', ' return (me.center.getDistance (center) <= me.radius + radius);', ' }', ' ', ' // check to see if the sphere contains a point', ' public boolean contains (PointInMetricSpace checkMe) {', ' return (checkMe.getDistance (center) <= radius);', ' }', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return center; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return radius + checkMe.getDistance (center); ', ' }', '}', '', '', '', 'class OneDimPoint implements IPointInMetricSpace <OneDimPoint> {', ' ', ' // this is the actual double', ' Double value;', ' ', ' // construct this out of a double value', ' public OneDimPoint (double makeFromMe) {', ' value = new Double (makeFromMe);', ' }', ' ', ' // get the distance to another point', ' public double getDistance (OneDimPoint toMe) {', ' if (value > toMe.value)', ' return value - toMe.value;', ' else', ' return toMe.value - value;', ' }', ' ', '}', '', 'class MultiDimPoint implements IPointInMetricSpace <MultiDimPoint> {', ' ', ' // this is the point in a multidimensional space', ' IDoubleVector me;', ' ', ' // make this out of an IDoubleVector', ' public MultiDimPoint (IDoubleVector useMe) {', ' me = useMe;', ' }', ' ', ' // get the Euclidean distance to another point', ' public double getDistance (MultiDimPoint toMe) {', ' double distance = 0.0;', ' try {', ' for (int i = 0; i < me.getLength (); i++) {', ' double diff = me.getItem (i) - toMe.me.getItem (i);', ' diff *= diff;', ' distance += diff;', ' }', ' } catch (OutOfBoundsException e) {', ' throw new IndexOutOfBoundsException ("Can\'t compare two MultiDimPoint objects with different dimensionality!"); ', ' }', ' return Math.sqrt(distance);', ' }', ' ', '}', '// this is a leaf node', 'class LeafMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements ', ' IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myData;', ' ', ' // contructor that takes a data list and builds a node out of it', ' private LeafMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myDataIn) {', ' myData = myDataIn; ', ' }', ' ', ' // constructor that creates an empty node', ' public LeafMTreeNodeABCD () {', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> (); ', ' }', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // just add in the new data', ' myData.add (new PointABCD <PointInMetricSpace> (keyToAdd), dataToAdd);', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> newOne = myData.splitInTwo ();', ' LeafMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' myQ.insert (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData (), ', ' query.getDistance (myData.get (i).getKey ().getPointInInterior ()));', ' }', ' }', ' }', ' ', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' returnVal.add (new DataWrapper <PointInMetricSpace, DataType> (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData ()));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return 1; ', ' }', '', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', '// this silly little class is just a wrapper for a key, data pair', 'class DataWrapper <Key, Data> {', ' ', ' Key key;', ' Data data;', ' ', ' public DataWrapper (Key keyIn, Data dataIn) {', ' key = keyIn;', ' data = dataIn;', ' }', ' ', ' public Key getKey () {', ' return key;', ' }', ' ', ' public Data getData () {', ' return data;', ' }', '}', '', '', '// this is an internal node', 'class InternalMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType>', ' implements IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> myData;', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' // this constructs a new internal node that holds precisely the two nodes that are passed in', ' public InternalMTreeNodeABCD (IMTreeNodeABCD <PointInMetricSpace, DataType> refOne,', ' IMTreeNodeABCD <PointInMetricSpace, DataType> refTwo) {', ' ', ' // create a necw list and add the two guys in', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> ();', ' myData.add (refOne.getBoundingSphere (), refOne);', ' myData.add (refTwo.getBoundingSphere (), refTwo);', ' }', ' ', ' // this constructs a new node that holds the list of data that we were passed in', ' public InternalMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> useMe) {', ' myData = useMe; ', ' }', ' ', ' // from the interface', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // find the best child; this is the one we are closest to', ' double bestDist = 9e99;', ' int bestIndex = 0;', ' for (int i = 0; i < myData.size (); i++) {', ' ', ' double newDist = myData.get (i).getKey ().getPointInInterior ().getDistance (keyToAdd);', ' if (newDist < bestDist) {', ' bestDist = newDist;', ' bestIndex = i;', ' }', ' }', ' ', ' // do the recursive insert', ' IMTreeNodeABCD <PointInMetricSpace, DataType> newRef = myData.get (bestIndex).getData ().insert (keyToAdd, dataToAdd);', ' ', ' // if we got something back, then there was a split, so add the new node into our list', ' if (newRef != null) {', ' myData.add (newRef.getBoundingSphere (), newRef);', ' }', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> newOne = myData.splitInTwo ();', ' InternalMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.intersects (myData.get (i).getKey ())) {', ' myData.get (i).getData ().findKClosest (query, myQ);', ' }', ' }', ' }', ' ', ' // from the interface', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.intersects (myData.get (i).getKey ())) {', ' returnVal.addAll (myData.get (i).getData ().find (query));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return myData.get (0).getData ().depth () + 1; ', ' }', ' ', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', 'abstract class AMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> implements IMetricDataListABCD <PointInMetricSpace,KeyType, DataType> {', '', ' // this is the data that is actually stored in the list', ' private ArrayList <DataWrapper <KeyType, DataType>> myData;', ' ', ' // this is the sphere that bounds everything in the list', ' private SphereABCD <PointInMetricSpace> myBoundingSphere;', ' ', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myBoundingSphere; ', ' }', ' ', ' public int size () {', ' if (myData != null)', ' return myData.size (); ', ' else', ' return 0;', ' }', ' ', ' public DataWrapper <KeyType, DataType> get (int pos) {', ' return myData.get (pos);', ' }', ' ', ' public void replaceKey (int pos, KeyType keyToAdd) {', ' DataWrapper <KeyType, DataType> temp = myData.remove (pos);', ' DataWrapper <KeyType, DataType> newOne = new DataWrapper <KeyType, DataType> (keyToAdd, temp.getData ());', ' myData.add (pos, newOne);', ' }', ' ', ' public void add (KeyType keyToAdd, DataType dataToAdd) {', ' ', ' // if this is the first add, then set everyone up', ' if (myData == null) {', ' PointInMetricSpace myCentroid = keyToAdd.getPointInInterior ();', ' myBoundingSphere = new SphereABCD <PointInMetricSpace> (myCentroid, keyToAdd.maxDistanceTo (myCentroid));', ' myData = new ArrayList <DataWrapper <KeyType, DataType>> ();', ' ', ' // otherwise, extend the sphere if needed', ' } else {', ' myBoundingSphere.swallow (keyToAdd);', ' }', ' ', ' // add the data', ' myData.add (new DataWrapper <KeyType, DataType> (keyToAdd, dataToAdd));', ' }', ' ', ' // we want to potentially allow many implementations of the splitting lalgorithm', ' abstract public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // this is here so the actual splitting algorithn can access the list and change the sphere', ' protected ArrayList <DataWrapper <KeyType, DataType>> getList () {', ' return myData;', ' }', ' ', ' // this is here so the splitting algorithm can modify the list and the sphere', ' protected void replaceGuts (AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> withMe) {', ' myData = withMe.myData;', ' myBoundingSphere = withMe.myBoundingSphere;', ' }', ' ', '}', '', '// this is a particular implementation of the metric data list that uses a simple quadratic clustering', '// algorithm to perform a list split. It picks two "seeds" (the most distant objects) and then repeatedly', '// adds to the two new lists by choosing the objects closest to the seeds', 'class ChrisMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> extends AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> {', '', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo () {', ' ', ' // first, we need to find the two most distant points in the list', ' ArrayList <DataWrapper <KeyType, DataType>> myData = getList ();', ' int bestI = 0, bestJ = 0;', ' double maxDist = -1.0;', ' for (int i = 0; i < myData.size (); i++) {', ' for (int j = i + 1; j < myData.size (); j++) {', ' ', ' // get the two keys', ' DataWrapper <KeyType, DataType> pointOne = myData.get (i);', ' DataWrapper <KeyType, DataType> pointTwo = myData.get (j);', ' ', ' // find the difference between them', ' double curDist = pointOne.getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', '', ' // see if it is the biggest', ' if (curDist > maxDist) {', ' maxDist = curDist;', ' bestI = i;', ' bestJ = j;', ' }', ' }', ' }', ' ', ' // now, we have the best two points; those are seeds for the clustering', ' DataWrapper <KeyType, DataType> pointOne = myData.remove (bestI);', ' DataWrapper <KeyType, DataType> pointTwo = myData.remove (bestJ - 1);', ' ', ' // these are the two new lists', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listOne = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listTwo = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' ', ' // put the two seeds in', ' listOne.add (pointOne.getKey (), pointOne.getData ());', ' listTwo.add (pointTwo.getKey (), pointTwo.getData ());', ' ', ' // and add everyone else in', ' while (myData.size () != 0) {', ' ', ' // find the one closest to the first seed', ' int bestIndex = 0;', ' double bestDist = 9e99;', ' ', ' // loop thru all of the candidate data objects', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listOne.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' ', ' // break if no more data', ' if (myData.size () == 0)', ' break;', ' ', ' // loop thru all of the candidate data objects', ' bestDist = 9e99;', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listTwo.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' }', ' ', ' // now we replace our own guts with the first list', ' replaceGuts (listOne);', ' ', ' // and return the other list', ' return listTwo;', ' }', '}', '', 'interface IMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> {', ' ', ' // add a new pair to the list', ' public void add (KeyType keyToAdd, DataType dataToAdd);', ' ', ' // replace a key at the indicated position', ' public void replaceKey (int pos, KeyType keyToAdd);', ' ', ' // get the key, data pair that resides at a particular position', ' public DataWrapper <KeyType, DataType> get (int pos);', ' ', ' // return the number of items in the list', ' public int size ();', ' ', ' // split the list in two, using some clutering algorithm', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // get a sphere that totally bounds all of the objects in the list', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class MTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public MTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class SCMTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public SCMTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', '', 'public class MTreeTester extends TestCase {', ' ', ' // compare two lists of strings to see if the contents are the same', ' private boolean compareStringSets (ArrayList <String> setOne, ArrayList <String> setTwo) {', ' ', ' // sort the sets and make sure they are the same', ' boolean returnVal = true;', ' if (setOne.size () == setTwo.size ()) {', ' Collections.sort (setOne);', ' Collections.sort (setTwo);', ' for (int i = 0; i < setOne.size (); i++) {', ' if (!setOne.get (i).equals (setTwo.get (i))) {', ' returnVal = false;', ' break; ', ' }', ' }', ' } else {', ' returnVal = false;', ' }', ' ', ' // print out the result', ' System.out.println ("**** Expected:");', ' for (int i = 0; i < setOne.size (); i++) {', ' System.out.format (setOne.get (i) + " ");', ' }', ' System.out.println ("\\n**** Got:");', ' for (int i = 0; i < setTwo.size (); i++) {', ' System.out.format (setTwo.get (i) + " ");', ' }', ' System.out.println ("");', ' ', ' return returnVal;', ' }', ' ', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST SIMPLE ONE DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testOneDimRangeQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.find (query, expectedQuerySize / 2);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.find (query, expectedQuerySize / 2);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (numPoints);', ' result1 = myTree.find (query, expectedQuerySize);', ' result2 = hisTree.find (query, expectedQuerySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // like the last one, but runs a top k', ' private void testOneDimTopKQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (167);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.findKClosest (query, querySize);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (0);', ' result1 = myTree.findKClosest (query, querySize);', ' result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST MULTI-DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimRangeQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' double dist1 = 0;', ' double dist2 = 0;', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' dist1 = Math.sqrt (numDims) * expectedQuerySize / 2.0;', ' dist2 = Math.sqrt (numDims) * expectedQuerySize;', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' // do a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, (int) expectedQuerySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = myTree.findKClosest (query2, (int) expectedQuerySize);', ' ', ' // find the distance to the furthest point in both cases', ' for (int i = 0; i < (int) expectedQuerySize; i++) {', ' double newDist = result1.get (i).getKey ().getDistance (query1);', ' if (newDist > dist1)', ' dist1 = newDist;', ' newDist = result2.get (i).getKey ().getDistance (query2);', ' if (newDist > dist2)', ' dist2 = newDist;', ' }', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.find (query1, dist1);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.find (query1, dist1);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.find (query2, dist2);', ' result2 = hisTree.find (query2, dist2);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimTopKQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, querySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.findKClosest (query1, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.findKClosest (query2, querySize);', ' result2 = hisTree.findKClosest (query2, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' ', ' /**', ' * "TIER 1" TESTS', ' * NONE OF THESE REQUIRE ANY SPLITS', ' */', ' public void testEasy1() {', ' testOneDimRangeQuery (true, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy2() {', ' testOneDimRangeQuery (false, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy3() {', ' testOneDimRangeQuery (true, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy4() {', ' testOneDimRangeQuery (false, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy5() {', ' testMultiDimRangeQuery (true, 1, 5, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy6() {', ' testMultiDimRangeQuery (false, 1, 10, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy7() {', ' testMultiDimRangeQuery (true, 1, 5, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy8() {', ' testMultiDimRangeQuery (false, 1, 15, 10000, 10000, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 2" TESTS', ' * NONE OF THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testMod1() {', ' testOneDimRangeQuery (true, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod2() {', ' testOneDimRangeQuery (false, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod3() {', ' testOneDimRangeQuery (true, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod4() {', ' testOneDimRangeQuery (false, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod5() {', ' testMultiDimRangeQuery (true, 2, 5, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod6() {', ' testMultiDimRangeQuery (false, 2, 10, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod7() {', ' testMultiDimRangeQuery (true, 2, 5, 10000, 100, 1000, 10);', ' }', ' ', ' public void testMod8() {', ' testMultiDimRangeQuery (false, 2, 15, 10000, 100, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 3" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testHard1() {', ' testOneDimRangeQuery (true, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard2() {', ' testOneDimRangeQuery (false, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard3() {', ' testOneDimRangeQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard4() {', ' testOneDimRangeQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard5() {', ' testMultiDimRangeQuery (true, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard6() {', ' testMultiDimRangeQuery (false, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard7() {', ' testMultiDimRangeQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard8() {', ' testMultiDimRangeQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', ' ', ' /**', ' * "TIER 4" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE AND THEY TEST THE TOPK FUNCTIONALITY', ' */', ' ', ' public void testTopK1() {', ' testOneDimTopKQuery (true, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK2() {', ' testOneDimTopKQuery (false, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK3() {', ' testOneDimTopKQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK4() {', ' testOneDimTopKQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK5() {', ' testMultiDimTopKQuery (true, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK6() {', ' testMultiDimTopKQuery (false, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK7() {', ' testMultiDimTopKQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK8() {', ' testMultiDimTopKQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', '}'] | [{'reason_category': 'Loop Body', 'usage_line': 240}, {'reason_category': 'If Body', 'usage_line': 240}, {'reason_category': 'Loop Body', 'usage_line': 241}, {'reason_category': 'If Body', 'usage_line': 241}] | Global_Variable 'myList' used at line 240 is defined at line 186 and has a Long-Range dependency.
Variable 'i' used at line 240 is defined at line 238 and has a Short-Range dependency.
Variable 'distance' used at line 240 is defined at line 208 and has a Long-Range dependency.
Global_Variable 'large' used at line 240 is defined at line 237 and has a Short-Range dependency. | {'Loop Body': 2, 'If Body': 2} | {'Global_Variable Long-Range': 1, 'Variable Short-Range': 1, 'Variable Long-Range': 1, 'Global_Variable Short-Range': 1} |
infilling_java | MTreeTester | 239 | 242 | ['import junit.framework.TestCase;', 'import java.util.ArrayList;', 'import java.util.Random;', 'import java.util.Collections;', '', '// this is a map from a set of keys of type PointInMetricSpace to a', '// set of data of type DataType', 'interface IMTree <Key extends IPointInMetricSpace <Key>, Data> {', ' ', ' // insert a new key/data pair into the map', ' void insert (Key keyToAdd, Data dataToAdd);', ' ', ' // find all of the key/data pairs in the map that fall within a', ' // particular distance of query point if no results are found, then', ' // an empty array is returned (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> find (Key query, double distance);', ' ', ' // find the k closest key/data pairs in the map to a particular', ' // query point ', ' //', ' // if the number of points in the map is less than k, then the', ' // returned list will have less than k pairs in it', ' //', ' // if the number of points is zero, then an empty array is returned', ' // (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> findKClosest (Key query, int k);', ' ', ' // returns the number of nodes that exist on a path from root to leaf in the tree...', ' // whtever the details of the implementation are, a tree with a single leaf node should return 1, and a tree', ' // with more than one lead node should return at least two (since it must have at least one internal node).', ' public int depth ();', ' ', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', '', 'interface IDoubleVector {', '', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '', '// this correponds to some geometric object in a metric space; the object is built out of', '// one or more points of type PointInMetricSpace', 'interface IObjectInMetricSpaceABCD <PointInMetricSpace extends IPointInMetricSpace<PointInMetricSpace>> {', ' ', ' // get the maximum distance from some point on the shape to a particular point in the metric space', ' double maxDistanceTo (PointInMetricSpace checkMe);', ' ', ' // return some arbitrary point on the interior of the geometric object', ' PointInMetricSpace getPointInInterior ();', '}', '', '', '// this interface corresponds to a point in some metric space', 'interface IPointInMetricSpace <PointInMetricSpace> {', ' ', ' // get the distance to another point', ' // ', ' // for this to work in an M-Tree, distances should be "metric" and', ' // obey the triangle inequality', ' double getDistance (PointInMetricSpace toMe);', '}', '', '// this is the basic node type in the structure', 'interface IMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> {', ' ', ' // insert a new key/data pair into the structure. The return value is a new MTreeNode if there was', ' // a split in response to the insertion, or a null if there was no split', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd);', ' ', ' // find all of the key/data pairs in the structure that fall within a particular query sphere', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query); ', ' ', ' // find the set of items closest to the given query point', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ);', ' ', ' // returns a sphere that totally encompasses everything in the node and its subtree', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', ' ', ' // returns the depth', ' public int depth ();', '}', '', '// this is a point in a particular metric space', 'class PointABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the point', ' private PointInMetricSpace me;', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return me; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return checkMe.getDistance (me); ', ' }', ' ', ' // contruct a point', ' public PointABCD (PointInMetricSpace useMe) {', ' me = useMe; ', ' }', '}', '', 'class PQueueABCD <PointInMetricSpace, DataType> {', ' ', ' // this is an object in the queue', ' private class Wrapper {', ' DataWrapper <PointInMetricSpace, DataType> myData;', ' double distance;', ' }', ' ', ' // this is the actual queue', ' ArrayList <Wrapper> myList;', ' ', ' // this is the largest distance value currently in the queue', ' double large;', ' ', ' // this is the max number of objects', ' int maxCount;', ' ', ' // create a priority queue with the speced number of slots', ' PQueueABCD (int maxCountIn) {', ' maxCount = maxCountIn;', ' myList = new ArrayList <Wrapper> ();', ' large = 9e99;', ' }', ' ', ' // get the largest distance in the queue', ' double getDist () {', ' return large;', ' }', ' ', ' // add a new object to the queue... the insertion is ignored if the distance value', ' // exceeds the largest that is in the queue and the queue is already full', ' void insert (PointInMetricSpace key, DataType data, double distance) {', ' ', ' // if we are full, remove the one with the largest distance', ' if (myList.size () == maxCount && distance < large) {', ' ', ' int badIndex = 0;', ' double maxDist = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > maxDist) {', ' maxDist = myList.get (i).distance;', ' badIndex = i;', ' }', ' }', ' ', ' myList.remove (badIndex);', ' }', ' ', ' // see if there is room', ' if (myList.size () < maxCount) {', ' ', ' // add it ', ' Wrapper newOne = new Wrapper ();', ' newOne.myData = new DataWrapper <PointInMetricSpace, DataType> (key, data);', ' newOne.distance = distance;', ' myList.add (newOne); ', ' }', ' ', ' // if we are full, reset the max distance', ' if (myList.size () == maxCount) {', ' large = 0.0;', ' for (int i = 0; i < myList.size (); i++) {'] | [' if (myList.get (i).distance > large) {', ' large = myList.get (i).distance;', ' }', ' }'] | [' }', ' ', ' }', ' ', ' // extracts the contents of the queue', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> done () {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' for (int i = 0; i < myList.size (); i++) {', ' returnVal.add (myList.get (i).myData); ', ' }', ' ', ' return returnVal;', ' }', ' ', '}', '', '// this is a sphere in a particular metric space', 'class SphereABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the center of the sphere and its radius', ' private PointInMetricSpace center;', ' private double radius;', ' ', ' // build a sphere out of its center and its radius', ' public SphereABCD (PointInMetricSpace centerIn, double radiusIn) {', ' center = centerIn;', ' radius = radiusIn;', ' }', ' ', ' // increase the size of the sphere so it contains the object swallowMe', ' public void swallow (IObjectInMetricSpaceABCD <PointInMetricSpace> swallowMe) {', ' ', ' // see if we need to increase the radius to swallow this guy', ' double dist = swallowMe.maxDistanceTo (center);', ' if (dist > radius)', ' radius = dist;', ' }', ' ', ' // check to see if a sphere intersects another sphere', ' public boolean intersects (SphereABCD <PointInMetricSpace> me) {', ' return (me.center.getDistance (center) <= me.radius + radius);', ' }', ' ', ' // check to see if the sphere contains a point', ' public boolean contains (PointInMetricSpace checkMe) {', ' return (checkMe.getDistance (center) <= radius);', ' }', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return center; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return radius + checkMe.getDistance (center); ', ' }', '}', '', '', '', 'class OneDimPoint implements IPointInMetricSpace <OneDimPoint> {', ' ', ' // this is the actual double', ' Double value;', ' ', ' // construct this out of a double value', ' public OneDimPoint (double makeFromMe) {', ' value = new Double (makeFromMe);', ' }', ' ', ' // get the distance to another point', ' public double getDistance (OneDimPoint toMe) {', ' if (value > toMe.value)', ' return value - toMe.value;', ' else', ' return toMe.value - value;', ' }', ' ', '}', '', 'class MultiDimPoint implements IPointInMetricSpace <MultiDimPoint> {', ' ', ' // this is the point in a multidimensional space', ' IDoubleVector me;', ' ', ' // make this out of an IDoubleVector', ' public MultiDimPoint (IDoubleVector useMe) {', ' me = useMe;', ' }', ' ', ' // get the Euclidean distance to another point', ' public double getDistance (MultiDimPoint toMe) {', ' double distance = 0.0;', ' try {', ' for (int i = 0; i < me.getLength (); i++) {', ' double diff = me.getItem (i) - toMe.me.getItem (i);', ' diff *= diff;', ' distance += diff;', ' }', ' } catch (OutOfBoundsException e) {', ' throw new IndexOutOfBoundsException ("Can\'t compare two MultiDimPoint objects with different dimensionality!"); ', ' }', ' return Math.sqrt(distance);', ' }', ' ', '}', '// this is a leaf node', 'class LeafMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements ', ' IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myData;', ' ', ' // contructor that takes a data list and builds a node out of it', ' private LeafMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myDataIn) {', ' myData = myDataIn; ', ' }', ' ', ' // constructor that creates an empty node', ' public LeafMTreeNodeABCD () {', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> (); ', ' }', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // just add in the new data', ' myData.add (new PointABCD <PointInMetricSpace> (keyToAdd), dataToAdd);', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> newOne = myData.splitInTwo ();', ' LeafMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' myQ.insert (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData (), ', ' query.getDistance (myData.get (i).getKey ().getPointInInterior ()));', ' }', ' }', ' }', ' ', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' returnVal.add (new DataWrapper <PointInMetricSpace, DataType> (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData ()));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return 1; ', ' }', '', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', '// this silly little class is just a wrapper for a key, data pair', 'class DataWrapper <Key, Data> {', ' ', ' Key key;', ' Data data;', ' ', ' public DataWrapper (Key keyIn, Data dataIn) {', ' key = keyIn;', ' data = dataIn;', ' }', ' ', ' public Key getKey () {', ' return key;', ' }', ' ', ' public Data getData () {', ' return data;', ' }', '}', '', '', '// this is an internal node', 'class InternalMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType>', ' implements IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> myData;', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' // this constructs a new internal node that holds precisely the two nodes that are passed in', ' public InternalMTreeNodeABCD (IMTreeNodeABCD <PointInMetricSpace, DataType> refOne,', ' IMTreeNodeABCD <PointInMetricSpace, DataType> refTwo) {', ' ', ' // create a necw list and add the two guys in', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> ();', ' myData.add (refOne.getBoundingSphere (), refOne);', ' myData.add (refTwo.getBoundingSphere (), refTwo);', ' }', ' ', ' // this constructs a new node that holds the list of data that we were passed in', ' public InternalMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> useMe) {', ' myData = useMe; ', ' }', ' ', ' // from the interface', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // find the best child; this is the one we are closest to', ' double bestDist = 9e99;', ' int bestIndex = 0;', ' for (int i = 0; i < myData.size (); i++) {', ' ', ' double newDist = myData.get (i).getKey ().getPointInInterior ().getDistance (keyToAdd);', ' if (newDist < bestDist) {', ' bestDist = newDist;', ' bestIndex = i;', ' }', ' }', ' ', ' // do the recursive insert', ' IMTreeNodeABCD <PointInMetricSpace, DataType> newRef = myData.get (bestIndex).getData ().insert (keyToAdd, dataToAdd);', ' ', ' // if we got something back, then there was a split, so add the new node into our list', ' if (newRef != null) {', ' myData.add (newRef.getBoundingSphere (), newRef);', ' }', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> newOne = myData.splitInTwo ();', ' InternalMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.intersects (myData.get (i).getKey ())) {', ' myData.get (i).getData ().findKClosest (query, myQ);', ' }', ' }', ' }', ' ', ' // from the interface', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.intersects (myData.get (i).getKey ())) {', ' returnVal.addAll (myData.get (i).getData ().find (query));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return myData.get (0).getData ().depth () + 1; ', ' }', ' ', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', 'abstract class AMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> implements IMetricDataListABCD <PointInMetricSpace,KeyType, DataType> {', '', ' // this is the data that is actually stored in the list', ' private ArrayList <DataWrapper <KeyType, DataType>> myData;', ' ', ' // this is the sphere that bounds everything in the list', ' private SphereABCD <PointInMetricSpace> myBoundingSphere;', ' ', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myBoundingSphere; ', ' }', ' ', ' public int size () {', ' if (myData != null)', ' return myData.size (); ', ' else', ' return 0;', ' }', ' ', ' public DataWrapper <KeyType, DataType> get (int pos) {', ' return myData.get (pos);', ' }', ' ', ' public void replaceKey (int pos, KeyType keyToAdd) {', ' DataWrapper <KeyType, DataType> temp = myData.remove (pos);', ' DataWrapper <KeyType, DataType> newOne = new DataWrapper <KeyType, DataType> (keyToAdd, temp.getData ());', ' myData.add (pos, newOne);', ' }', ' ', ' public void add (KeyType keyToAdd, DataType dataToAdd) {', ' ', ' // if this is the first add, then set everyone up', ' if (myData == null) {', ' PointInMetricSpace myCentroid = keyToAdd.getPointInInterior ();', ' myBoundingSphere = new SphereABCD <PointInMetricSpace> (myCentroid, keyToAdd.maxDistanceTo (myCentroid));', ' myData = new ArrayList <DataWrapper <KeyType, DataType>> ();', ' ', ' // otherwise, extend the sphere if needed', ' } else {', ' myBoundingSphere.swallow (keyToAdd);', ' }', ' ', ' // add the data', ' myData.add (new DataWrapper <KeyType, DataType> (keyToAdd, dataToAdd));', ' }', ' ', ' // we want to potentially allow many implementations of the splitting lalgorithm', ' abstract public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // this is here so the actual splitting algorithn can access the list and change the sphere', ' protected ArrayList <DataWrapper <KeyType, DataType>> getList () {', ' return myData;', ' }', ' ', ' // this is here so the splitting algorithm can modify the list and the sphere', ' protected void replaceGuts (AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> withMe) {', ' myData = withMe.myData;', ' myBoundingSphere = withMe.myBoundingSphere;', ' }', ' ', '}', '', '// this is a particular implementation of the metric data list that uses a simple quadratic clustering', '// algorithm to perform a list split. It picks two "seeds" (the most distant objects) and then repeatedly', '// adds to the two new lists by choosing the objects closest to the seeds', 'class ChrisMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> extends AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> {', '', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo () {', ' ', ' // first, we need to find the two most distant points in the list', ' ArrayList <DataWrapper <KeyType, DataType>> myData = getList ();', ' int bestI = 0, bestJ = 0;', ' double maxDist = -1.0;', ' for (int i = 0; i < myData.size (); i++) {', ' for (int j = i + 1; j < myData.size (); j++) {', ' ', ' // get the two keys', ' DataWrapper <KeyType, DataType> pointOne = myData.get (i);', ' DataWrapper <KeyType, DataType> pointTwo = myData.get (j);', ' ', ' // find the difference between them', ' double curDist = pointOne.getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', '', ' // see if it is the biggest', ' if (curDist > maxDist) {', ' maxDist = curDist;', ' bestI = i;', ' bestJ = j;', ' }', ' }', ' }', ' ', ' // now, we have the best two points; those are seeds for the clustering', ' DataWrapper <KeyType, DataType> pointOne = myData.remove (bestI);', ' DataWrapper <KeyType, DataType> pointTwo = myData.remove (bestJ - 1);', ' ', ' // these are the two new lists', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listOne = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listTwo = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' ', ' // put the two seeds in', ' listOne.add (pointOne.getKey (), pointOne.getData ());', ' listTwo.add (pointTwo.getKey (), pointTwo.getData ());', ' ', ' // and add everyone else in', ' while (myData.size () != 0) {', ' ', ' // find the one closest to the first seed', ' int bestIndex = 0;', ' double bestDist = 9e99;', ' ', ' // loop thru all of the candidate data objects', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listOne.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' ', ' // break if no more data', ' if (myData.size () == 0)', ' break;', ' ', ' // loop thru all of the candidate data objects', ' bestDist = 9e99;', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listTwo.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' }', ' ', ' // now we replace our own guts with the first list', ' replaceGuts (listOne);', ' ', ' // and return the other list', ' return listTwo;', ' }', '}', '', 'interface IMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> {', ' ', ' // add a new pair to the list', ' public void add (KeyType keyToAdd, DataType dataToAdd);', ' ', ' // replace a key at the indicated position', ' public void replaceKey (int pos, KeyType keyToAdd);', ' ', ' // get the key, data pair that resides at a particular position', ' public DataWrapper <KeyType, DataType> get (int pos);', ' ', ' // return the number of items in the list', ' public int size ();', ' ', ' // split the list in two, using some clutering algorithm', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // get a sphere that totally bounds all of the objects in the list', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class MTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public MTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class SCMTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public SCMTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', '', 'public class MTreeTester extends TestCase {', ' ', ' // compare two lists of strings to see if the contents are the same', ' private boolean compareStringSets (ArrayList <String> setOne, ArrayList <String> setTwo) {', ' ', ' // sort the sets and make sure they are the same', ' boolean returnVal = true;', ' if (setOne.size () == setTwo.size ()) {', ' Collections.sort (setOne);', ' Collections.sort (setTwo);', ' for (int i = 0; i < setOne.size (); i++) {', ' if (!setOne.get (i).equals (setTwo.get (i))) {', ' returnVal = false;', ' break; ', ' }', ' }', ' } else {', ' returnVal = false;', ' }', ' ', ' // print out the result', ' System.out.println ("**** Expected:");', ' for (int i = 0; i < setOne.size (); i++) {', ' System.out.format (setOne.get (i) + " ");', ' }', ' System.out.println ("\\n**** Got:");', ' for (int i = 0; i < setTwo.size (); i++) {', ' System.out.format (setTwo.get (i) + " ");', ' }', ' System.out.println ("");', ' ', ' return returnVal;', ' }', ' ', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST SIMPLE ONE DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testOneDimRangeQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.find (query, expectedQuerySize / 2);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.find (query, expectedQuerySize / 2);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (numPoints);', ' result1 = myTree.find (query, expectedQuerySize);', ' result2 = hisTree.find (query, expectedQuerySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // like the last one, but runs a top k', ' private void testOneDimTopKQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (167);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.findKClosest (query, querySize);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (0);', ' result1 = myTree.findKClosest (query, querySize);', ' result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST MULTI-DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimRangeQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' double dist1 = 0;', ' double dist2 = 0;', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' dist1 = Math.sqrt (numDims) * expectedQuerySize / 2.0;', ' dist2 = Math.sqrt (numDims) * expectedQuerySize;', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' // do a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, (int) expectedQuerySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = myTree.findKClosest (query2, (int) expectedQuerySize);', ' ', ' // find the distance to the furthest point in both cases', ' for (int i = 0; i < (int) expectedQuerySize; i++) {', ' double newDist = result1.get (i).getKey ().getDistance (query1);', ' if (newDist > dist1)', ' dist1 = newDist;', ' newDist = result2.get (i).getKey ().getDistance (query2);', ' if (newDist > dist2)', ' dist2 = newDist;', ' }', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.find (query1, dist1);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.find (query1, dist1);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.find (query2, dist2);', ' result2 = hisTree.find (query2, dist2);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimTopKQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, querySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.findKClosest (query1, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.findKClosest (query2, querySize);', ' result2 = hisTree.findKClosest (query2, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' ', ' /**', ' * "TIER 1" TESTS', ' * NONE OF THESE REQUIRE ANY SPLITS', ' */', ' public void testEasy1() {', ' testOneDimRangeQuery (true, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy2() {', ' testOneDimRangeQuery (false, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy3() {', ' testOneDimRangeQuery (true, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy4() {', ' testOneDimRangeQuery (false, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy5() {', ' testMultiDimRangeQuery (true, 1, 5, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy6() {', ' testMultiDimRangeQuery (false, 1, 10, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy7() {', ' testMultiDimRangeQuery (true, 1, 5, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy8() {', ' testMultiDimRangeQuery (false, 1, 15, 10000, 10000, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 2" TESTS', ' * NONE OF THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testMod1() {', ' testOneDimRangeQuery (true, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod2() {', ' testOneDimRangeQuery (false, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod3() {', ' testOneDimRangeQuery (true, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod4() {', ' testOneDimRangeQuery (false, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod5() {', ' testMultiDimRangeQuery (true, 2, 5, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod6() {', ' testMultiDimRangeQuery (false, 2, 10, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod7() {', ' testMultiDimRangeQuery (true, 2, 5, 10000, 100, 1000, 10);', ' }', ' ', ' public void testMod8() {', ' testMultiDimRangeQuery (false, 2, 15, 10000, 100, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 3" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testHard1() {', ' testOneDimRangeQuery (true, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard2() {', ' testOneDimRangeQuery (false, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard3() {', ' testOneDimRangeQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard4() {', ' testOneDimRangeQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard5() {', ' testMultiDimRangeQuery (true, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard6() {', ' testMultiDimRangeQuery (false, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard7() {', ' testMultiDimRangeQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard8() {', ' testMultiDimRangeQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', ' ', ' /**', ' * "TIER 4" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE AND THEY TEST THE TOPK FUNCTIONALITY', ' */', ' ', ' public void testTopK1() {', ' testOneDimTopKQuery (true, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK2() {', ' testOneDimTopKQuery (false, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK3() {', ' testOneDimTopKQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK4() {', ' testOneDimTopKQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK5() {', ' testMultiDimTopKQuery (true, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK6() {', ' testMultiDimTopKQuery (false, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK7() {', ' testMultiDimTopKQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK8() {', ' testMultiDimTopKQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', '}'] | [{'reason_category': 'If Body', 'usage_line': 239}, {'reason_category': 'Loop Body', 'usage_line': 239}, {'reason_category': 'If Condition', 'usage_line': 239}, {'reason_category': 'Loop Body', 'usage_line': 240}, {'reason_category': 'If Body', 'usage_line': 240}, {'reason_category': 'Loop Body', 'usage_line': 241}, {'reason_category': 'If Body', 'usage_line': 241}, {'reason_category': 'Loop Body', 'usage_line': 242}, {'reason_category': 'If Body', 'usage_line': 242}] | Global_Variable 'myList' used at line 239 is defined at line 186 and has a Long-Range dependency.
Variable 'i' used at line 239 is defined at line 238 and has a Short-Range dependency.
Variable 'distance' used at line 239 is defined at line 208 and has a Long-Range dependency.
Global_Variable 'large' used at line 239 is defined at line 237 and has a Short-Range dependency.
Global_Variable 'myList' used at line 240 is defined at line 186 and has a Long-Range dependency.
Variable 'i' used at line 240 is defined at line 238 and has a Short-Range dependency.
Variable 'distance' used at line 240 is defined at line 208 and has a Long-Range dependency.
Global_Variable 'large' used at line 240 is defined at line 237 and has a Short-Range dependency. | {'If Body': 4, 'Loop Body': 4, 'If Condition': 1} | {'Global_Variable Long-Range': 2, 'Variable Short-Range': 2, 'Variable Long-Range': 2, 'Global_Variable Short-Range': 2} |
infilling_java | MTreeTester | 238 | 243 | ['import junit.framework.TestCase;', 'import java.util.ArrayList;', 'import java.util.Random;', 'import java.util.Collections;', '', '// this is a map from a set of keys of type PointInMetricSpace to a', '// set of data of type DataType', 'interface IMTree <Key extends IPointInMetricSpace <Key>, Data> {', ' ', ' // insert a new key/data pair into the map', ' void insert (Key keyToAdd, Data dataToAdd);', ' ', ' // find all of the key/data pairs in the map that fall within a', ' // particular distance of query point if no results are found, then', ' // an empty array is returned (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> find (Key query, double distance);', ' ', ' // find the k closest key/data pairs in the map to a particular', ' // query point ', ' //', ' // if the number of points in the map is less than k, then the', ' // returned list will have less than k pairs in it', ' //', ' // if the number of points is zero, then an empty array is returned', ' // (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> findKClosest (Key query, int k);', ' ', ' // returns the number of nodes that exist on a path from root to leaf in the tree...', ' // whtever the details of the implementation are, a tree with a single leaf node should return 1, and a tree', ' // with more than one lead node should return at least two (since it must have at least one internal node).', ' public int depth ();', ' ', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', '', 'interface IDoubleVector {', '', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '', '// this correponds to some geometric object in a metric space; the object is built out of', '// one or more points of type PointInMetricSpace', 'interface IObjectInMetricSpaceABCD <PointInMetricSpace extends IPointInMetricSpace<PointInMetricSpace>> {', ' ', ' // get the maximum distance from some point on the shape to a particular point in the metric space', ' double maxDistanceTo (PointInMetricSpace checkMe);', ' ', ' // return some arbitrary point on the interior of the geometric object', ' PointInMetricSpace getPointInInterior ();', '}', '', '', '// this interface corresponds to a point in some metric space', 'interface IPointInMetricSpace <PointInMetricSpace> {', ' ', ' // get the distance to another point', ' // ', ' // for this to work in an M-Tree, distances should be "metric" and', ' // obey the triangle inequality', ' double getDistance (PointInMetricSpace toMe);', '}', '', '// this is the basic node type in the structure', 'interface IMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> {', ' ', ' // insert a new key/data pair into the structure. The return value is a new MTreeNode if there was', ' // a split in response to the insertion, or a null if there was no split', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd);', ' ', ' // find all of the key/data pairs in the structure that fall within a particular query sphere', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query); ', ' ', ' // find the set of items closest to the given query point', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ);', ' ', ' // returns a sphere that totally encompasses everything in the node and its subtree', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', ' ', ' // returns the depth', ' public int depth ();', '}', '', '// this is a point in a particular metric space', 'class PointABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the point', ' private PointInMetricSpace me;', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return me; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return checkMe.getDistance (me); ', ' }', ' ', ' // contruct a point', ' public PointABCD (PointInMetricSpace useMe) {', ' me = useMe; ', ' }', '}', '', 'class PQueueABCD <PointInMetricSpace, DataType> {', ' ', ' // this is an object in the queue', ' private class Wrapper {', ' DataWrapper <PointInMetricSpace, DataType> myData;', ' double distance;', ' }', ' ', ' // this is the actual queue', ' ArrayList <Wrapper> myList;', ' ', ' // this is the largest distance value currently in the queue', ' double large;', ' ', ' // this is the max number of objects', ' int maxCount;', ' ', ' // create a priority queue with the speced number of slots', ' PQueueABCD (int maxCountIn) {', ' maxCount = maxCountIn;', ' myList = new ArrayList <Wrapper> ();', ' large = 9e99;', ' }', ' ', ' // get the largest distance in the queue', ' double getDist () {', ' return large;', ' }', ' ', ' // add a new object to the queue... the insertion is ignored if the distance value', ' // exceeds the largest that is in the queue and the queue is already full', ' void insert (PointInMetricSpace key, DataType data, double distance) {', ' ', ' // if we are full, remove the one with the largest distance', ' if (myList.size () == maxCount && distance < large) {', ' ', ' int badIndex = 0;', ' double maxDist = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > maxDist) {', ' maxDist = myList.get (i).distance;', ' badIndex = i;', ' }', ' }', ' ', ' myList.remove (badIndex);', ' }', ' ', ' // see if there is room', ' if (myList.size () < maxCount) {', ' ', ' // add it ', ' Wrapper newOne = new Wrapper ();', ' newOne.myData = new DataWrapper <PointInMetricSpace, DataType> (key, data);', ' newOne.distance = distance;', ' myList.add (newOne); ', ' }', ' ', ' // if we are full, reset the max distance', ' if (myList.size () == maxCount) {', ' large = 0.0;'] | [' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > large) {', ' large = myList.get (i).distance;', ' }', ' }', ' }'] | [' ', ' }', ' ', ' // extracts the contents of the queue', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> done () {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' for (int i = 0; i < myList.size (); i++) {', ' returnVal.add (myList.get (i).myData); ', ' }', ' ', ' return returnVal;', ' }', ' ', '}', '', '// this is a sphere in a particular metric space', 'class SphereABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the center of the sphere and its radius', ' private PointInMetricSpace center;', ' private double radius;', ' ', ' // build a sphere out of its center and its radius', ' public SphereABCD (PointInMetricSpace centerIn, double radiusIn) {', ' center = centerIn;', ' radius = radiusIn;', ' }', ' ', ' // increase the size of the sphere so it contains the object swallowMe', ' public void swallow (IObjectInMetricSpaceABCD <PointInMetricSpace> swallowMe) {', ' ', ' // see if we need to increase the radius to swallow this guy', ' double dist = swallowMe.maxDistanceTo (center);', ' if (dist > radius)', ' radius = dist;', ' }', ' ', ' // check to see if a sphere intersects another sphere', ' public boolean intersects (SphereABCD <PointInMetricSpace> me) {', ' return (me.center.getDistance (center) <= me.radius + radius);', ' }', ' ', ' // check to see if the sphere contains a point', ' public boolean contains (PointInMetricSpace checkMe) {', ' return (checkMe.getDistance (center) <= radius);', ' }', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return center; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return radius + checkMe.getDistance (center); ', ' }', '}', '', '', '', 'class OneDimPoint implements IPointInMetricSpace <OneDimPoint> {', ' ', ' // this is the actual double', ' Double value;', ' ', ' // construct this out of a double value', ' public OneDimPoint (double makeFromMe) {', ' value = new Double (makeFromMe);', ' }', ' ', ' // get the distance to another point', ' public double getDistance (OneDimPoint toMe) {', ' if (value > toMe.value)', ' return value - toMe.value;', ' else', ' return toMe.value - value;', ' }', ' ', '}', '', 'class MultiDimPoint implements IPointInMetricSpace <MultiDimPoint> {', ' ', ' // this is the point in a multidimensional space', ' IDoubleVector me;', ' ', ' // make this out of an IDoubleVector', ' public MultiDimPoint (IDoubleVector useMe) {', ' me = useMe;', ' }', ' ', ' // get the Euclidean distance to another point', ' public double getDistance (MultiDimPoint toMe) {', ' double distance = 0.0;', ' try {', ' for (int i = 0; i < me.getLength (); i++) {', ' double diff = me.getItem (i) - toMe.me.getItem (i);', ' diff *= diff;', ' distance += diff;', ' }', ' } catch (OutOfBoundsException e) {', ' throw new IndexOutOfBoundsException ("Can\'t compare two MultiDimPoint objects with different dimensionality!"); ', ' }', ' return Math.sqrt(distance);', ' }', ' ', '}', '// this is a leaf node', 'class LeafMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements ', ' IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myData;', ' ', ' // contructor that takes a data list and builds a node out of it', ' private LeafMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myDataIn) {', ' myData = myDataIn; ', ' }', ' ', ' // constructor that creates an empty node', ' public LeafMTreeNodeABCD () {', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> (); ', ' }', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // just add in the new data', ' myData.add (new PointABCD <PointInMetricSpace> (keyToAdd), dataToAdd);', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> newOne = myData.splitInTwo ();', ' LeafMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' myQ.insert (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData (), ', ' query.getDistance (myData.get (i).getKey ().getPointInInterior ()));', ' }', ' }', ' }', ' ', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' returnVal.add (new DataWrapper <PointInMetricSpace, DataType> (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData ()));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return 1; ', ' }', '', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', '// this silly little class is just a wrapper for a key, data pair', 'class DataWrapper <Key, Data> {', ' ', ' Key key;', ' Data data;', ' ', ' public DataWrapper (Key keyIn, Data dataIn) {', ' key = keyIn;', ' data = dataIn;', ' }', ' ', ' public Key getKey () {', ' return key;', ' }', ' ', ' public Data getData () {', ' return data;', ' }', '}', '', '', '// this is an internal node', 'class InternalMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType>', ' implements IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> myData;', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' // this constructs a new internal node that holds precisely the two nodes that are passed in', ' public InternalMTreeNodeABCD (IMTreeNodeABCD <PointInMetricSpace, DataType> refOne,', ' IMTreeNodeABCD <PointInMetricSpace, DataType> refTwo) {', ' ', ' // create a necw list and add the two guys in', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> ();', ' myData.add (refOne.getBoundingSphere (), refOne);', ' myData.add (refTwo.getBoundingSphere (), refTwo);', ' }', ' ', ' // this constructs a new node that holds the list of data that we were passed in', ' public InternalMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> useMe) {', ' myData = useMe; ', ' }', ' ', ' // from the interface', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // find the best child; this is the one we are closest to', ' double bestDist = 9e99;', ' int bestIndex = 0;', ' for (int i = 0; i < myData.size (); i++) {', ' ', ' double newDist = myData.get (i).getKey ().getPointInInterior ().getDistance (keyToAdd);', ' if (newDist < bestDist) {', ' bestDist = newDist;', ' bestIndex = i;', ' }', ' }', ' ', ' // do the recursive insert', ' IMTreeNodeABCD <PointInMetricSpace, DataType> newRef = myData.get (bestIndex).getData ().insert (keyToAdd, dataToAdd);', ' ', ' // if we got something back, then there was a split, so add the new node into our list', ' if (newRef != null) {', ' myData.add (newRef.getBoundingSphere (), newRef);', ' }', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> newOne = myData.splitInTwo ();', ' InternalMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.intersects (myData.get (i).getKey ())) {', ' myData.get (i).getData ().findKClosest (query, myQ);', ' }', ' }', ' }', ' ', ' // from the interface', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.intersects (myData.get (i).getKey ())) {', ' returnVal.addAll (myData.get (i).getData ().find (query));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return myData.get (0).getData ().depth () + 1; ', ' }', ' ', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', 'abstract class AMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> implements IMetricDataListABCD <PointInMetricSpace,KeyType, DataType> {', '', ' // this is the data that is actually stored in the list', ' private ArrayList <DataWrapper <KeyType, DataType>> myData;', ' ', ' // this is the sphere that bounds everything in the list', ' private SphereABCD <PointInMetricSpace> myBoundingSphere;', ' ', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myBoundingSphere; ', ' }', ' ', ' public int size () {', ' if (myData != null)', ' return myData.size (); ', ' else', ' return 0;', ' }', ' ', ' public DataWrapper <KeyType, DataType> get (int pos) {', ' return myData.get (pos);', ' }', ' ', ' public void replaceKey (int pos, KeyType keyToAdd) {', ' DataWrapper <KeyType, DataType> temp = myData.remove (pos);', ' DataWrapper <KeyType, DataType> newOne = new DataWrapper <KeyType, DataType> (keyToAdd, temp.getData ());', ' myData.add (pos, newOne);', ' }', ' ', ' public void add (KeyType keyToAdd, DataType dataToAdd) {', ' ', ' // if this is the first add, then set everyone up', ' if (myData == null) {', ' PointInMetricSpace myCentroid = keyToAdd.getPointInInterior ();', ' myBoundingSphere = new SphereABCD <PointInMetricSpace> (myCentroid, keyToAdd.maxDistanceTo (myCentroid));', ' myData = new ArrayList <DataWrapper <KeyType, DataType>> ();', ' ', ' // otherwise, extend the sphere if needed', ' } else {', ' myBoundingSphere.swallow (keyToAdd);', ' }', ' ', ' // add the data', ' myData.add (new DataWrapper <KeyType, DataType> (keyToAdd, dataToAdd));', ' }', ' ', ' // we want to potentially allow many implementations of the splitting lalgorithm', ' abstract public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // this is here so the actual splitting algorithn can access the list and change the sphere', ' protected ArrayList <DataWrapper <KeyType, DataType>> getList () {', ' return myData;', ' }', ' ', ' // this is here so the splitting algorithm can modify the list and the sphere', ' protected void replaceGuts (AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> withMe) {', ' myData = withMe.myData;', ' myBoundingSphere = withMe.myBoundingSphere;', ' }', ' ', '}', '', '// this is a particular implementation of the metric data list that uses a simple quadratic clustering', '// algorithm to perform a list split. It picks two "seeds" (the most distant objects) and then repeatedly', '// adds to the two new lists by choosing the objects closest to the seeds', 'class ChrisMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> extends AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> {', '', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo () {', ' ', ' // first, we need to find the two most distant points in the list', ' ArrayList <DataWrapper <KeyType, DataType>> myData = getList ();', ' int bestI = 0, bestJ = 0;', ' double maxDist = -1.0;', ' for (int i = 0; i < myData.size (); i++) {', ' for (int j = i + 1; j < myData.size (); j++) {', ' ', ' // get the two keys', ' DataWrapper <KeyType, DataType> pointOne = myData.get (i);', ' DataWrapper <KeyType, DataType> pointTwo = myData.get (j);', ' ', ' // find the difference between them', ' double curDist = pointOne.getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', '', ' // see if it is the biggest', ' if (curDist > maxDist) {', ' maxDist = curDist;', ' bestI = i;', ' bestJ = j;', ' }', ' }', ' }', ' ', ' // now, we have the best two points; those are seeds for the clustering', ' DataWrapper <KeyType, DataType> pointOne = myData.remove (bestI);', ' DataWrapper <KeyType, DataType> pointTwo = myData.remove (bestJ - 1);', ' ', ' // these are the two new lists', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listOne = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listTwo = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' ', ' // put the two seeds in', ' listOne.add (pointOne.getKey (), pointOne.getData ());', ' listTwo.add (pointTwo.getKey (), pointTwo.getData ());', ' ', ' // and add everyone else in', ' while (myData.size () != 0) {', ' ', ' // find the one closest to the first seed', ' int bestIndex = 0;', ' double bestDist = 9e99;', ' ', ' // loop thru all of the candidate data objects', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listOne.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' ', ' // break if no more data', ' if (myData.size () == 0)', ' break;', ' ', ' // loop thru all of the candidate data objects', ' bestDist = 9e99;', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listTwo.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' }', ' ', ' // now we replace our own guts with the first list', ' replaceGuts (listOne);', ' ', ' // and return the other list', ' return listTwo;', ' }', '}', '', 'interface IMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> {', ' ', ' // add a new pair to the list', ' public void add (KeyType keyToAdd, DataType dataToAdd);', ' ', ' // replace a key at the indicated position', ' public void replaceKey (int pos, KeyType keyToAdd);', ' ', ' // get the key, data pair that resides at a particular position', ' public DataWrapper <KeyType, DataType> get (int pos);', ' ', ' // return the number of items in the list', ' public int size ();', ' ', ' // split the list in two, using some clutering algorithm', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // get a sphere that totally bounds all of the objects in the list', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class MTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public MTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class SCMTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public SCMTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', '', 'public class MTreeTester extends TestCase {', ' ', ' // compare two lists of strings to see if the contents are the same', ' private boolean compareStringSets (ArrayList <String> setOne, ArrayList <String> setTwo) {', ' ', ' // sort the sets and make sure they are the same', ' boolean returnVal = true;', ' if (setOne.size () == setTwo.size ()) {', ' Collections.sort (setOne);', ' Collections.sort (setTwo);', ' for (int i = 0; i < setOne.size (); i++) {', ' if (!setOne.get (i).equals (setTwo.get (i))) {', ' returnVal = false;', ' break; ', ' }', ' }', ' } else {', ' returnVal = false;', ' }', ' ', ' // print out the result', ' System.out.println ("**** Expected:");', ' for (int i = 0; i < setOne.size (); i++) {', ' System.out.format (setOne.get (i) + " ");', ' }', ' System.out.println ("\\n**** Got:");', ' for (int i = 0; i < setTwo.size (); i++) {', ' System.out.format (setTwo.get (i) + " ");', ' }', ' System.out.println ("");', ' ', ' return returnVal;', ' }', ' ', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST SIMPLE ONE DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testOneDimRangeQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.find (query, expectedQuerySize / 2);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.find (query, expectedQuerySize / 2);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (numPoints);', ' result1 = myTree.find (query, expectedQuerySize);', ' result2 = hisTree.find (query, expectedQuerySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // like the last one, but runs a top k', ' private void testOneDimTopKQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (167);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.findKClosest (query, querySize);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (0);', ' result1 = myTree.findKClosest (query, querySize);', ' result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST MULTI-DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimRangeQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' double dist1 = 0;', ' double dist2 = 0;', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' dist1 = Math.sqrt (numDims) * expectedQuerySize / 2.0;', ' dist2 = Math.sqrt (numDims) * expectedQuerySize;', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' // do a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, (int) expectedQuerySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = myTree.findKClosest (query2, (int) expectedQuerySize);', ' ', ' // find the distance to the furthest point in both cases', ' for (int i = 0; i < (int) expectedQuerySize; i++) {', ' double newDist = result1.get (i).getKey ().getDistance (query1);', ' if (newDist > dist1)', ' dist1 = newDist;', ' newDist = result2.get (i).getKey ().getDistance (query2);', ' if (newDist > dist2)', ' dist2 = newDist;', ' }', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.find (query1, dist1);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.find (query1, dist1);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.find (query2, dist2);', ' result2 = hisTree.find (query2, dist2);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimTopKQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, querySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.findKClosest (query1, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.findKClosest (query2, querySize);', ' result2 = hisTree.findKClosest (query2, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' ', ' /**', ' * "TIER 1" TESTS', ' * NONE OF THESE REQUIRE ANY SPLITS', ' */', ' public void testEasy1() {', ' testOneDimRangeQuery (true, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy2() {', ' testOneDimRangeQuery (false, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy3() {', ' testOneDimRangeQuery (true, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy4() {', ' testOneDimRangeQuery (false, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy5() {', ' testMultiDimRangeQuery (true, 1, 5, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy6() {', ' testMultiDimRangeQuery (false, 1, 10, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy7() {', ' testMultiDimRangeQuery (true, 1, 5, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy8() {', ' testMultiDimRangeQuery (false, 1, 15, 10000, 10000, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 2" TESTS', ' * NONE OF THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testMod1() {', ' testOneDimRangeQuery (true, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod2() {', ' testOneDimRangeQuery (false, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod3() {', ' testOneDimRangeQuery (true, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod4() {', ' testOneDimRangeQuery (false, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod5() {', ' testMultiDimRangeQuery (true, 2, 5, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod6() {', ' testMultiDimRangeQuery (false, 2, 10, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod7() {', ' testMultiDimRangeQuery (true, 2, 5, 10000, 100, 1000, 10);', ' }', ' ', ' public void testMod8() {', ' testMultiDimRangeQuery (false, 2, 15, 10000, 100, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 3" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testHard1() {', ' testOneDimRangeQuery (true, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard2() {', ' testOneDimRangeQuery (false, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard3() {', ' testOneDimRangeQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard4() {', ' testOneDimRangeQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard5() {', ' testMultiDimRangeQuery (true, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard6() {', ' testMultiDimRangeQuery (false, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard7() {', ' testMultiDimRangeQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard8() {', ' testMultiDimRangeQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', ' ', ' /**', ' * "TIER 4" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE AND THEY TEST THE TOPK FUNCTIONALITY', ' */', ' ', ' public void testTopK1() {', ' testOneDimTopKQuery (true, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK2() {', ' testOneDimTopKQuery (false, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK3() {', ' testOneDimTopKQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK4() {', ' testOneDimTopKQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK5() {', ' testMultiDimTopKQuery (true, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK6() {', ' testMultiDimTopKQuery (false, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK7() {', ' testMultiDimTopKQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK8() {', ' testMultiDimTopKQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', '}'] | [{'reason_category': 'If Body', 'usage_line': 238}, {'reason_category': 'Define Stop Criteria', 'usage_line': 238}, {'reason_category': 'If Body', 'usage_line': 239}, {'reason_category': 'Loop Body', 'usage_line': 239}, {'reason_category': 'If Condition', 'usage_line': 239}, {'reason_category': 'Loop Body', 'usage_line': 240}, {'reason_category': 'If Body', 'usage_line': 240}, {'reason_category': 'Loop Body', 'usage_line': 241}, {'reason_category': 'If Body', 'usage_line': 241}, {'reason_category': 'Loop Body', 'usage_line': 242}, {'reason_category': 'If Body', 'usage_line': 242}, {'reason_category': 'If Body', 'usage_line': 243}] | Variable 'i' used at line 238 is defined at line 238 and has a Short-Range dependency.
Global_Variable 'myList' used at line 238 is defined at line 186 and has a Long-Range dependency.
Global_Variable 'myList' used at line 239 is defined at line 186 and has a Long-Range dependency.
Variable 'i' used at line 239 is defined at line 238 and has a Short-Range dependency.
Variable 'distance' used at line 239 is defined at line 208 and has a Long-Range dependency.
Global_Variable 'large' used at line 239 is defined at line 237 and has a Short-Range dependency.
Global_Variable 'myList' used at line 240 is defined at line 186 and has a Long-Range dependency.
Variable 'i' used at line 240 is defined at line 238 and has a Short-Range dependency.
Variable 'distance' used at line 240 is defined at line 208 and has a Long-Range dependency.
Global_Variable 'large' used at line 240 is defined at line 237 and has a Short-Range dependency. | {'If Body': 6, 'Define Stop Criteria': 1, 'Loop Body': 4, 'If Condition': 1} | {'Variable Short-Range': 3, 'Global_Variable Long-Range': 3, 'Variable Long-Range': 2, 'Global_Variable Short-Range': 2} |
infilling_java | MTreeTester | 252 | 253 | ['import junit.framework.TestCase;', 'import java.util.ArrayList;', 'import java.util.Random;', 'import java.util.Collections;', '', '// this is a map from a set of keys of type PointInMetricSpace to a', '// set of data of type DataType', 'interface IMTree <Key extends IPointInMetricSpace <Key>, Data> {', ' ', ' // insert a new key/data pair into the map', ' void insert (Key keyToAdd, Data dataToAdd);', ' ', ' // find all of the key/data pairs in the map that fall within a', ' // particular distance of query point if no results are found, then', ' // an empty array is returned (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> find (Key query, double distance);', ' ', ' // find the k closest key/data pairs in the map to a particular', ' // query point ', ' //', ' // if the number of points in the map is less than k, then the', ' // returned list will have less than k pairs in it', ' //', ' // if the number of points is zero, then an empty array is returned', ' // (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> findKClosest (Key query, int k);', ' ', ' // returns the number of nodes that exist on a path from root to leaf in the tree...', ' // whtever the details of the implementation are, a tree with a single leaf node should return 1, and a tree', ' // with more than one lead node should return at least two (since it must have at least one internal node).', ' public int depth ();', ' ', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', '', 'interface IDoubleVector {', '', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '', '// this correponds to some geometric object in a metric space; the object is built out of', '// one or more points of type PointInMetricSpace', 'interface IObjectInMetricSpaceABCD <PointInMetricSpace extends IPointInMetricSpace<PointInMetricSpace>> {', ' ', ' // get the maximum distance from some point on the shape to a particular point in the metric space', ' double maxDistanceTo (PointInMetricSpace checkMe);', ' ', ' // return some arbitrary point on the interior of the geometric object', ' PointInMetricSpace getPointInInterior ();', '}', '', '', '// this interface corresponds to a point in some metric space', 'interface IPointInMetricSpace <PointInMetricSpace> {', ' ', ' // get the distance to another point', ' // ', ' // for this to work in an M-Tree, distances should be "metric" and', ' // obey the triangle inequality', ' double getDistance (PointInMetricSpace toMe);', '}', '', '// this is the basic node type in the structure', 'interface IMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> {', ' ', ' // insert a new key/data pair into the structure. The return value is a new MTreeNode if there was', ' // a split in response to the insertion, or a null if there was no split', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd);', ' ', ' // find all of the key/data pairs in the structure that fall within a particular query sphere', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query); ', ' ', ' // find the set of items closest to the given query point', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ);', ' ', ' // returns a sphere that totally encompasses everything in the node and its subtree', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', ' ', ' // returns the depth', ' public int depth ();', '}', '', '// this is a point in a particular metric space', 'class PointABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the point', ' private PointInMetricSpace me;', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return me; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return checkMe.getDistance (me); ', ' }', ' ', ' // contruct a point', ' public PointABCD (PointInMetricSpace useMe) {', ' me = useMe; ', ' }', '}', '', 'class PQueueABCD <PointInMetricSpace, DataType> {', ' ', ' // this is an object in the queue', ' private class Wrapper {', ' DataWrapper <PointInMetricSpace, DataType> myData;', ' double distance;', ' }', ' ', ' // this is the actual queue', ' ArrayList <Wrapper> myList;', ' ', ' // this is the largest distance value currently in the queue', ' double large;', ' ', ' // this is the max number of objects', ' int maxCount;', ' ', ' // create a priority queue with the speced number of slots', ' PQueueABCD (int maxCountIn) {', ' maxCount = maxCountIn;', ' myList = new ArrayList <Wrapper> ();', ' large = 9e99;', ' }', ' ', ' // get the largest distance in the queue', ' double getDist () {', ' return large;', ' }', ' ', ' // add a new object to the queue... the insertion is ignored if the distance value', ' // exceeds the largest that is in the queue and the queue is already full', ' void insert (PointInMetricSpace key, DataType data, double distance) {', ' ', ' // if we are full, remove the one with the largest distance', ' if (myList.size () == maxCount && distance < large) {', ' ', ' int badIndex = 0;', ' double maxDist = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > maxDist) {', ' maxDist = myList.get (i).distance;', ' badIndex = i;', ' }', ' }', ' ', ' myList.remove (badIndex);', ' }', ' ', ' // see if there is room', ' if (myList.size () < maxCount) {', ' ', ' // add it ', ' Wrapper newOne = new Wrapper ();', ' newOne.myData = new DataWrapper <PointInMetricSpace, DataType> (key, data);', ' newOne.distance = distance;', ' myList.add (newOne); ', ' }', ' ', ' // if we are full, reset the max distance', ' if (myList.size () == maxCount) {', ' large = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > large) {', ' large = myList.get (i).distance;', ' }', ' }', ' }', ' ', ' }', ' ', ' // extracts the contents of the queue', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> done () {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' for (int i = 0; i < myList.size (); i++) {'] | [' returnVal.add (myList.get (i).myData); ', ' }'] | [' ', ' return returnVal;', ' }', ' ', '}', '', '// this is a sphere in a particular metric space', 'class SphereABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the center of the sphere and its radius', ' private PointInMetricSpace center;', ' private double radius;', ' ', ' // build a sphere out of its center and its radius', ' public SphereABCD (PointInMetricSpace centerIn, double radiusIn) {', ' center = centerIn;', ' radius = radiusIn;', ' }', ' ', ' // increase the size of the sphere so it contains the object swallowMe', ' public void swallow (IObjectInMetricSpaceABCD <PointInMetricSpace> swallowMe) {', ' ', ' // see if we need to increase the radius to swallow this guy', ' double dist = swallowMe.maxDistanceTo (center);', ' if (dist > radius)', ' radius = dist;', ' }', ' ', ' // check to see if a sphere intersects another sphere', ' public boolean intersects (SphereABCD <PointInMetricSpace> me) {', ' return (me.center.getDistance (center) <= me.radius + radius);', ' }', ' ', ' // check to see if the sphere contains a point', ' public boolean contains (PointInMetricSpace checkMe) {', ' return (checkMe.getDistance (center) <= radius);', ' }', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return center; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return radius + checkMe.getDistance (center); ', ' }', '}', '', '', '', 'class OneDimPoint implements IPointInMetricSpace <OneDimPoint> {', ' ', ' // this is the actual double', ' Double value;', ' ', ' // construct this out of a double value', ' public OneDimPoint (double makeFromMe) {', ' value = new Double (makeFromMe);', ' }', ' ', ' // get the distance to another point', ' public double getDistance (OneDimPoint toMe) {', ' if (value > toMe.value)', ' return value - toMe.value;', ' else', ' return toMe.value - value;', ' }', ' ', '}', '', 'class MultiDimPoint implements IPointInMetricSpace <MultiDimPoint> {', ' ', ' // this is the point in a multidimensional space', ' IDoubleVector me;', ' ', ' // make this out of an IDoubleVector', ' public MultiDimPoint (IDoubleVector useMe) {', ' me = useMe;', ' }', ' ', ' // get the Euclidean distance to another point', ' public double getDistance (MultiDimPoint toMe) {', ' double distance = 0.0;', ' try {', ' for (int i = 0; i < me.getLength (); i++) {', ' double diff = me.getItem (i) - toMe.me.getItem (i);', ' diff *= diff;', ' distance += diff;', ' }', ' } catch (OutOfBoundsException e) {', ' throw new IndexOutOfBoundsException ("Can\'t compare two MultiDimPoint objects with different dimensionality!"); ', ' }', ' return Math.sqrt(distance);', ' }', ' ', '}', '// this is a leaf node', 'class LeafMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements ', ' IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myData;', ' ', ' // contructor that takes a data list and builds a node out of it', ' private LeafMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myDataIn) {', ' myData = myDataIn; ', ' }', ' ', ' // constructor that creates an empty node', ' public LeafMTreeNodeABCD () {', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> (); ', ' }', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // just add in the new data', ' myData.add (new PointABCD <PointInMetricSpace> (keyToAdd), dataToAdd);', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> newOne = myData.splitInTwo ();', ' LeafMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' myQ.insert (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData (), ', ' query.getDistance (myData.get (i).getKey ().getPointInInterior ()));', ' }', ' }', ' }', ' ', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' returnVal.add (new DataWrapper <PointInMetricSpace, DataType> (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData ()));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return 1; ', ' }', '', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', '// this silly little class is just a wrapper for a key, data pair', 'class DataWrapper <Key, Data> {', ' ', ' Key key;', ' Data data;', ' ', ' public DataWrapper (Key keyIn, Data dataIn) {', ' key = keyIn;', ' data = dataIn;', ' }', ' ', ' public Key getKey () {', ' return key;', ' }', ' ', ' public Data getData () {', ' return data;', ' }', '}', '', '', '// this is an internal node', 'class InternalMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType>', ' implements IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> myData;', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' // this constructs a new internal node that holds precisely the two nodes that are passed in', ' public InternalMTreeNodeABCD (IMTreeNodeABCD <PointInMetricSpace, DataType> refOne,', ' IMTreeNodeABCD <PointInMetricSpace, DataType> refTwo) {', ' ', ' // create a necw list and add the two guys in', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> ();', ' myData.add (refOne.getBoundingSphere (), refOne);', ' myData.add (refTwo.getBoundingSphere (), refTwo);', ' }', ' ', ' // this constructs a new node that holds the list of data that we were passed in', ' public InternalMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> useMe) {', ' myData = useMe; ', ' }', ' ', ' // from the interface', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // find the best child; this is the one we are closest to', ' double bestDist = 9e99;', ' int bestIndex = 0;', ' for (int i = 0; i < myData.size (); i++) {', ' ', ' double newDist = myData.get (i).getKey ().getPointInInterior ().getDistance (keyToAdd);', ' if (newDist < bestDist) {', ' bestDist = newDist;', ' bestIndex = i;', ' }', ' }', ' ', ' // do the recursive insert', ' IMTreeNodeABCD <PointInMetricSpace, DataType> newRef = myData.get (bestIndex).getData ().insert (keyToAdd, dataToAdd);', ' ', ' // if we got something back, then there was a split, so add the new node into our list', ' if (newRef != null) {', ' myData.add (newRef.getBoundingSphere (), newRef);', ' }', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> newOne = myData.splitInTwo ();', ' InternalMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.intersects (myData.get (i).getKey ())) {', ' myData.get (i).getData ().findKClosest (query, myQ);', ' }', ' }', ' }', ' ', ' // from the interface', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.intersects (myData.get (i).getKey ())) {', ' returnVal.addAll (myData.get (i).getData ().find (query));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return myData.get (0).getData ().depth () + 1; ', ' }', ' ', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', 'abstract class AMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> implements IMetricDataListABCD <PointInMetricSpace,KeyType, DataType> {', '', ' // this is the data that is actually stored in the list', ' private ArrayList <DataWrapper <KeyType, DataType>> myData;', ' ', ' // this is the sphere that bounds everything in the list', ' private SphereABCD <PointInMetricSpace> myBoundingSphere;', ' ', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myBoundingSphere; ', ' }', ' ', ' public int size () {', ' if (myData != null)', ' return myData.size (); ', ' else', ' return 0;', ' }', ' ', ' public DataWrapper <KeyType, DataType> get (int pos) {', ' return myData.get (pos);', ' }', ' ', ' public void replaceKey (int pos, KeyType keyToAdd) {', ' DataWrapper <KeyType, DataType> temp = myData.remove (pos);', ' DataWrapper <KeyType, DataType> newOne = new DataWrapper <KeyType, DataType> (keyToAdd, temp.getData ());', ' myData.add (pos, newOne);', ' }', ' ', ' public void add (KeyType keyToAdd, DataType dataToAdd) {', ' ', ' // if this is the first add, then set everyone up', ' if (myData == null) {', ' PointInMetricSpace myCentroid = keyToAdd.getPointInInterior ();', ' myBoundingSphere = new SphereABCD <PointInMetricSpace> (myCentroid, keyToAdd.maxDistanceTo (myCentroid));', ' myData = new ArrayList <DataWrapper <KeyType, DataType>> ();', ' ', ' // otherwise, extend the sphere if needed', ' } else {', ' myBoundingSphere.swallow (keyToAdd);', ' }', ' ', ' // add the data', ' myData.add (new DataWrapper <KeyType, DataType> (keyToAdd, dataToAdd));', ' }', ' ', ' // we want to potentially allow many implementations of the splitting lalgorithm', ' abstract public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // this is here so the actual splitting algorithn can access the list and change the sphere', ' protected ArrayList <DataWrapper <KeyType, DataType>> getList () {', ' return myData;', ' }', ' ', ' // this is here so the splitting algorithm can modify the list and the sphere', ' protected void replaceGuts (AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> withMe) {', ' myData = withMe.myData;', ' myBoundingSphere = withMe.myBoundingSphere;', ' }', ' ', '}', '', '// this is a particular implementation of the metric data list that uses a simple quadratic clustering', '// algorithm to perform a list split. It picks two "seeds" (the most distant objects) and then repeatedly', '// adds to the two new lists by choosing the objects closest to the seeds', 'class ChrisMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> extends AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> {', '', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo () {', ' ', ' // first, we need to find the two most distant points in the list', ' ArrayList <DataWrapper <KeyType, DataType>> myData = getList ();', ' int bestI = 0, bestJ = 0;', ' double maxDist = -1.0;', ' for (int i = 0; i < myData.size (); i++) {', ' for (int j = i + 1; j < myData.size (); j++) {', ' ', ' // get the two keys', ' DataWrapper <KeyType, DataType> pointOne = myData.get (i);', ' DataWrapper <KeyType, DataType> pointTwo = myData.get (j);', ' ', ' // find the difference between them', ' double curDist = pointOne.getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', '', ' // see if it is the biggest', ' if (curDist > maxDist) {', ' maxDist = curDist;', ' bestI = i;', ' bestJ = j;', ' }', ' }', ' }', ' ', ' // now, we have the best two points; those are seeds for the clustering', ' DataWrapper <KeyType, DataType> pointOne = myData.remove (bestI);', ' DataWrapper <KeyType, DataType> pointTwo = myData.remove (bestJ - 1);', ' ', ' // these are the two new lists', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listOne = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listTwo = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' ', ' // put the two seeds in', ' listOne.add (pointOne.getKey (), pointOne.getData ());', ' listTwo.add (pointTwo.getKey (), pointTwo.getData ());', ' ', ' // and add everyone else in', ' while (myData.size () != 0) {', ' ', ' // find the one closest to the first seed', ' int bestIndex = 0;', ' double bestDist = 9e99;', ' ', ' // loop thru all of the candidate data objects', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listOne.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' ', ' // break if no more data', ' if (myData.size () == 0)', ' break;', ' ', ' // loop thru all of the candidate data objects', ' bestDist = 9e99;', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listTwo.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' }', ' ', ' // now we replace our own guts with the first list', ' replaceGuts (listOne);', ' ', ' // and return the other list', ' return listTwo;', ' }', '}', '', 'interface IMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> {', ' ', ' // add a new pair to the list', ' public void add (KeyType keyToAdd, DataType dataToAdd);', ' ', ' // replace a key at the indicated position', ' public void replaceKey (int pos, KeyType keyToAdd);', ' ', ' // get the key, data pair that resides at a particular position', ' public DataWrapper <KeyType, DataType> get (int pos);', ' ', ' // return the number of items in the list', ' public int size ();', ' ', ' // split the list in two, using some clutering algorithm', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // get a sphere that totally bounds all of the objects in the list', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class MTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public MTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class SCMTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public SCMTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', '', 'public class MTreeTester extends TestCase {', ' ', ' // compare two lists of strings to see if the contents are the same', ' private boolean compareStringSets (ArrayList <String> setOne, ArrayList <String> setTwo) {', ' ', ' // sort the sets and make sure they are the same', ' boolean returnVal = true;', ' if (setOne.size () == setTwo.size ()) {', ' Collections.sort (setOne);', ' Collections.sort (setTwo);', ' for (int i = 0; i < setOne.size (); i++) {', ' if (!setOne.get (i).equals (setTwo.get (i))) {', ' returnVal = false;', ' break; ', ' }', ' }', ' } else {', ' returnVal = false;', ' }', ' ', ' // print out the result', ' System.out.println ("**** Expected:");', ' for (int i = 0; i < setOne.size (); i++) {', ' System.out.format (setOne.get (i) + " ");', ' }', ' System.out.println ("\\n**** Got:");', ' for (int i = 0; i < setTwo.size (); i++) {', ' System.out.format (setTwo.get (i) + " ");', ' }', ' System.out.println ("");', ' ', ' return returnVal;', ' }', ' ', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST SIMPLE ONE DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testOneDimRangeQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.find (query, expectedQuerySize / 2);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.find (query, expectedQuerySize / 2);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (numPoints);', ' result1 = myTree.find (query, expectedQuerySize);', ' result2 = hisTree.find (query, expectedQuerySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // like the last one, but runs a top k', ' private void testOneDimTopKQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (167);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.findKClosest (query, querySize);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (0);', ' result1 = myTree.findKClosest (query, querySize);', ' result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST MULTI-DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimRangeQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' double dist1 = 0;', ' double dist2 = 0;', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' dist1 = Math.sqrt (numDims) * expectedQuerySize / 2.0;', ' dist2 = Math.sqrt (numDims) * expectedQuerySize;', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' // do a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, (int) expectedQuerySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = myTree.findKClosest (query2, (int) expectedQuerySize);', ' ', ' // find the distance to the furthest point in both cases', ' for (int i = 0; i < (int) expectedQuerySize; i++) {', ' double newDist = result1.get (i).getKey ().getDistance (query1);', ' if (newDist > dist1)', ' dist1 = newDist;', ' newDist = result2.get (i).getKey ().getDistance (query2);', ' if (newDist > dist2)', ' dist2 = newDist;', ' }', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.find (query1, dist1);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.find (query1, dist1);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.find (query2, dist2);', ' result2 = hisTree.find (query2, dist2);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimTopKQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, querySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.findKClosest (query1, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.findKClosest (query2, querySize);', ' result2 = hisTree.findKClosest (query2, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' ', ' /**', ' * "TIER 1" TESTS', ' * NONE OF THESE REQUIRE ANY SPLITS', ' */', ' public void testEasy1() {', ' testOneDimRangeQuery (true, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy2() {', ' testOneDimRangeQuery (false, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy3() {', ' testOneDimRangeQuery (true, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy4() {', ' testOneDimRangeQuery (false, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy5() {', ' testMultiDimRangeQuery (true, 1, 5, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy6() {', ' testMultiDimRangeQuery (false, 1, 10, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy7() {', ' testMultiDimRangeQuery (true, 1, 5, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy8() {', ' testMultiDimRangeQuery (false, 1, 15, 10000, 10000, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 2" TESTS', ' * NONE OF THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testMod1() {', ' testOneDimRangeQuery (true, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod2() {', ' testOneDimRangeQuery (false, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod3() {', ' testOneDimRangeQuery (true, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod4() {', ' testOneDimRangeQuery (false, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod5() {', ' testMultiDimRangeQuery (true, 2, 5, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod6() {', ' testMultiDimRangeQuery (false, 2, 10, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod7() {', ' testMultiDimRangeQuery (true, 2, 5, 10000, 100, 1000, 10);', ' }', ' ', ' public void testMod8() {', ' testMultiDimRangeQuery (false, 2, 15, 10000, 100, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 3" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testHard1() {', ' testOneDimRangeQuery (true, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard2() {', ' testOneDimRangeQuery (false, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard3() {', ' testOneDimRangeQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard4() {', ' testOneDimRangeQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard5() {', ' testMultiDimRangeQuery (true, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard6() {', ' testMultiDimRangeQuery (false, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard7() {', ' testMultiDimRangeQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard8() {', ' testMultiDimRangeQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', ' ', ' /**', ' * "TIER 4" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE AND THEY TEST THE TOPK FUNCTIONALITY', ' */', ' ', ' public void testTopK1() {', ' testOneDimTopKQuery (true, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK2() {', ' testOneDimTopKQuery (false, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK3() {', ' testOneDimTopKQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK4() {', ' testOneDimTopKQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK5() {', ' testMultiDimTopKQuery (true, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK6() {', ' testMultiDimTopKQuery (false, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK7() {', ' testMultiDimTopKQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK8() {', ' testMultiDimTopKQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', '}'] | [{'reason_category': 'Loop Body', 'usage_line': 252}, {'reason_category': 'Loop Body', 'usage_line': 253}] | Variable 'returnVal' used at line 252 is defined at line 250 and has a Short-Range dependency.
Global_Variable 'myList' used at line 252 is defined at line 186 and has a Long-Range dependency.
Variable 'i' used at line 252 is defined at line 251 and has a Short-Range dependency. | {'Loop Body': 2} | {'Variable Short-Range': 2, 'Global_Variable Long-Range': 1} |
infilling_java | MTreeTester | 251 | 256 | ['import junit.framework.TestCase;', 'import java.util.ArrayList;', 'import java.util.Random;', 'import java.util.Collections;', '', '// this is a map from a set of keys of type PointInMetricSpace to a', '// set of data of type DataType', 'interface IMTree <Key extends IPointInMetricSpace <Key>, Data> {', ' ', ' // insert a new key/data pair into the map', ' void insert (Key keyToAdd, Data dataToAdd);', ' ', ' // find all of the key/data pairs in the map that fall within a', ' // particular distance of query point if no results are found, then', ' // an empty array is returned (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> find (Key query, double distance);', ' ', ' // find the k closest key/data pairs in the map to a particular', ' // query point ', ' //', ' // if the number of points in the map is less than k, then the', ' // returned list will have less than k pairs in it', ' //', ' // if the number of points is zero, then an empty array is returned', ' // (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> findKClosest (Key query, int k);', ' ', ' // returns the number of nodes that exist on a path from root to leaf in the tree...', ' // whtever the details of the implementation are, a tree with a single leaf node should return 1, and a tree', ' // with more than one lead node should return at least two (since it must have at least one internal node).', ' public int depth ();', ' ', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', '', 'interface IDoubleVector {', '', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '', '// this correponds to some geometric object in a metric space; the object is built out of', '// one or more points of type PointInMetricSpace', 'interface IObjectInMetricSpaceABCD <PointInMetricSpace extends IPointInMetricSpace<PointInMetricSpace>> {', ' ', ' // get the maximum distance from some point on the shape to a particular point in the metric space', ' double maxDistanceTo (PointInMetricSpace checkMe);', ' ', ' // return some arbitrary point on the interior of the geometric object', ' PointInMetricSpace getPointInInterior ();', '}', '', '', '// this interface corresponds to a point in some metric space', 'interface IPointInMetricSpace <PointInMetricSpace> {', ' ', ' // get the distance to another point', ' // ', ' // for this to work in an M-Tree, distances should be "metric" and', ' // obey the triangle inequality', ' double getDistance (PointInMetricSpace toMe);', '}', '', '// this is the basic node type in the structure', 'interface IMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> {', ' ', ' // insert a new key/data pair into the structure. The return value is a new MTreeNode if there was', ' // a split in response to the insertion, or a null if there was no split', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd);', ' ', ' // find all of the key/data pairs in the structure that fall within a particular query sphere', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query); ', ' ', ' // find the set of items closest to the given query point', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ);', ' ', ' // returns a sphere that totally encompasses everything in the node and its subtree', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', ' ', ' // returns the depth', ' public int depth ();', '}', '', '// this is a point in a particular metric space', 'class PointABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the point', ' private PointInMetricSpace me;', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return me; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return checkMe.getDistance (me); ', ' }', ' ', ' // contruct a point', ' public PointABCD (PointInMetricSpace useMe) {', ' me = useMe; ', ' }', '}', '', 'class PQueueABCD <PointInMetricSpace, DataType> {', ' ', ' // this is an object in the queue', ' private class Wrapper {', ' DataWrapper <PointInMetricSpace, DataType> myData;', ' double distance;', ' }', ' ', ' // this is the actual queue', ' ArrayList <Wrapper> myList;', ' ', ' // this is the largest distance value currently in the queue', ' double large;', ' ', ' // this is the max number of objects', ' int maxCount;', ' ', ' // create a priority queue with the speced number of slots', ' PQueueABCD (int maxCountIn) {', ' maxCount = maxCountIn;', ' myList = new ArrayList <Wrapper> ();', ' large = 9e99;', ' }', ' ', ' // get the largest distance in the queue', ' double getDist () {', ' return large;', ' }', ' ', ' // add a new object to the queue... the insertion is ignored if the distance value', ' // exceeds the largest that is in the queue and the queue is already full', ' void insert (PointInMetricSpace key, DataType data, double distance) {', ' ', ' // if we are full, remove the one with the largest distance', ' if (myList.size () == maxCount && distance < large) {', ' ', ' int badIndex = 0;', ' double maxDist = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > maxDist) {', ' maxDist = myList.get (i).distance;', ' badIndex = i;', ' }', ' }', ' ', ' myList.remove (badIndex);', ' }', ' ', ' // see if there is room', ' if (myList.size () < maxCount) {', ' ', ' // add it ', ' Wrapper newOne = new Wrapper ();', ' newOne.myData = new DataWrapper <PointInMetricSpace, DataType> (key, data);', ' newOne.distance = distance;', ' myList.add (newOne); ', ' }', ' ', ' // if we are full, reset the max distance', ' if (myList.size () == maxCount) {', ' large = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > large) {', ' large = myList.get (i).distance;', ' }', ' }', ' }', ' ', ' }', ' ', ' // extracts the contents of the queue', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> done () {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();'] | [' for (int i = 0; i < myList.size (); i++) {', ' returnVal.add (myList.get (i).myData); ', ' }', ' ', ' return returnVal;', ' }'] | [' ', '}', '', '// this is a sphere in a particular metric space', 'class SphereABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the center of the sphere and its radius', ' private PointInMetricSpace center;', ' private double radius;', ' ', ' // build a sphere out of its center and its radius', ' public SphereABCD (PointInMetricSpace centerIn, double radiusIn) {', ' center = centerIn;', ' radius = radiusIn;', ' }', ' ', ' // increase the size of the sphere so it contains the object swallowMe', ' public void swallow (IObjectInMetricSpaceABCD <PointInMetricSpace> swallowMe) {', ' ', ' // see if we need to increase the radius to swallow this guy', ' double dist = swallowMe.maxDistanceTo (center);', ' if (dist > radius)', ' radius = dist;', ' }', ' ', ' // check to see if a sphere intersects another sphere', ' public boolean intersects (SphereABCD <PointInMetricSpace> me) {', ' return (me.center.getDistance (center) <= me.radius + radius);', ' }', ' ', ' // check to see if the sphere contains a point', ' public boolean contains (PointInMetricSpace checkMe) {', ' return (checkMe.getDistance (center) <= radius);', ' }', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return center; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return radius + checkMe.getDistance (center); ', ' }', '}', '', '', '', 'class OneDimPoint implements IPointInMetricSpace <OneDimPoint> {', ' ', ' // this is the actual double', ' Double value;', ' ', ' // construct this out of a double value', ' public OneDimPoint (double makeFromMe) {', ' value = new Double (makeFromMe);', ' }', ' ', ' // get the distance to another point', ' public double getDistance (OneDimPoint toMe) {', ' if (value > toMe.value)', ' return value - toMe.value;', ' else', ' return toMe.value - value;', ' }', ' ', '}', '', 'class MultiDimPoint implements IPointInMetricSpace <MultiDimPoint> {', ' ', ' // this is the point in a multidimensional space', ' IDoubleVector me;', ' ', ' // make this out of an IDoubleVector', ' public MultiDimPoint (IDoubleVector useMe) {', ' me = useMe;', ' }', ' ', ' // get the Euclidean distance to another point', ' public double getDistance (MultiDimPoint toMe) {', ' double distance = 0.0;', ' try {', ' for (int i = 0; i < me.getLength (); i++) {', ' double diff = me.getItem (i) - toMe.me.getItem (i);', ' diff *= diff;', ' distance += diff;', ' }', ' } catch (OutOfBoundsException e) {', ' throw new IndexOutOfBoundsException ("Can\'t compare two MultiDimPoint objects with different dimensionality!"); ', ' }', ' return Math.sqrt(distance);', ' }', ' ', '}', '// this is a leaf node', 'class LeafMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements ', ' IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myData;', ' ', ' // contructor that takes a data list and builds a node out of it', ' private LeafMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myDataIn) {', ' myData = myDataIn; ', ' }', ' ', ' // constructor that creates an empty node', ' public LeafMTreeNodeABCD () {', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> (); ', ' }', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // just add in the new data', ' myData.add (new PointABCD <PointInMetricSpace> (keyToAdd), dataToAdd);', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> newOne = myData.splitInTwo ();', ' LeafMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' myQ.insert (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData (), ', ' query.getDistance (myData.get (i).getKey ().getPointInInterior ()));', ' }', ' }', ' }', ' ', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' returnVal.add (new DataWrapper <PointInMetricSpace, DataType> (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData ()));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return 1; ', ' }', '', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', '// this silly little class is just a wrapper for a key, data pair', 'class DataWrapper <Key, Data> {', ' ', ' Key key;', ' Data data;', ' ', ' public DataWrapper (Key keyIn, Data dataIn) {', ' key = keyIn;', ' data = dataIn;', ' }', ' ', ' public Key getKey () {', ' return key;', ' }', ' ', ' public Data getData () {', ' return data;', ' }', '}', '', '', '// this is an internal node', 'class InternalMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType>', ' implements IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> myData;', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' // this constructs a new internal node that holds precisely the two nodes that are passed in', ' public InternalMTreeNodeABCD (IMTreeNodeABCD <PointInMetricSpace, DataType> refOne,', ' IMTreeNodeABCD <PointInMetricSpace, DataType> refTwo) {', ' ', ' // create a necw list and add the two guys in', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> ();', ' myData.add (refOne.getBoundingSphere (), refOne);', ' myData.add (refTwo.getBoundingSphere (), refTwo);', ' }', ' ', ' // this constructs a new node that holds the list of data that we were passed in', ' public InternalMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> useMe) {', ' myData = useMe; ', ' }', ' ', ' // from the interface', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // find the best child; this is the one we are closest to', ' double bestDist = 9e99;', ' int bestIndex = 0;', ' for (int i = 0; i < myData.size (); i++) {', ' ', ' double newDist = myData.get (i).getKey ().getPointInInterior ().getDistance (keyToAdd);', ' if (newDist < bestDist) {', ' bestDist = newDist;', ' bestIndex = i;', ' }', ' }', ' ', ' // do the recursive insert', ' IMTreeNodeABCD <PointInMetricSpace, DataType> newRef = myData.get (bestIndex).getData ().insert (keyToAdd, dataToAdd);', ' ', ' // if we got something back, then there was a split, so add the new node into our list', ' if (newRef != null) {', ' myData.add (newRef.getBoundingSphere (), newRef);', ' }', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> newOne = myData.splitInTwo ();', ' InternalMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.intersects (myData.get (i).getKey ())) {', ' myData.get (i).getData ().findKClosest (query, myQ);', ' }', ' }', ' }', ' ', ' // from the interface', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.intersects (myData.get (i).getKey ())) {', ' returnVal.addAll (myData.get (i).getData ().find (query));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return myData.get (0).getData ().depth () + 1; ', ' }', ' ', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', 'abstract class AMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> implements IMetricDataListABCD <PointInMetricSpace,KeyType, DataType> {', '', ' // this is the data that is actually stored in the list', ' private ArrayList <DataWrapper <KeyType, DataType>> myData;', ' ', ' // this is the sphere that bounds everything in the list', ' private SphereABCD <PointInMetricSpace> myBoundingSphere;', ' ', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myBoundingSphere; ', ' }', ' ', ' public int size () {', ' if (myData != null)', ' return myData.size (); ', ' else', ' return 0;', ' }', ' ', ' public DataWrapper <KeyType, DataType> get (int pos) {', ' return myData.get (pos);', ' }', ' ', ' public void replaceKey (int pos, KeyType keyToAdd) {', ' DataWrapper <KeyType, DataType> temp = myData.remove (pos);', ' DataWrapper <KeyType, DataType> newOne = new DataWrapper <KeyType, DataType> (keyToAdd, temp.getData ());', ' myData.add (pos, newOne);', ' }', ' ', ' public void add (KeyType keyToAdd, DataType dataToAdd) {', ' ', ' // if this is the first add, then set everyone up', ' if (myData == null) {', ' PointInMetricSpace myCentroid = keyToAdd.getPointInInterior ();', ' myBoundingSphere = new SphereABCD <PointInMetricSpace> (myCentroid, keyToAdd.maxDistanceTo (myCentroid));', ' myData = new ArrayList <DataWrapper <KeyType, DataType>> ();', ' ', ' // otherwise, extend the sphere if needed', ' } else {', ' myBoundingSphere.swallow (keyToAdd);', ' }', ' ', ' // add the data', ' myData.add (new DataWrapper <KeyType, DataType> (keyToAdd, dataToAdd));', ' }', ' ', ' // we want to potentially allow many implementations of the splitting lalgorithm', ' abstract public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // this is here so the actual splitting algorithn can access the list and change the sphere', ' protected ArrayList <DataWrapper <KeyType, DataType>> getList () {', ' return myData;', ' }', ' ', ' // this is here so the splitting algorithm can modify the list and the sphere', ' protected void replaceGuts (AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> withMe) {', ' myData = withMe.myData;', ' myBoundingSphere = withMe.myBoundingSphere;', ' }', ' ', '}', '', '// this is a particular implementation of the metric data list that uses a simple quadratic clustering', '// algorithm to perform a list split. It picks two "seeds" (the most distant objects) and then repeatedly', '// adds to the two new lists by choosing the objects closest to the seeds', 'class ChrisMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> extends AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> {', '', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo () {', ' ', ' // first, we need to find the two most distant points in the list', ' ArrayList <DataWrapper <KeyType, DataType>> myData = getList ();', ' int bestI = 0, bestJ = 0;', ' double maxDist = -1.0;', ' for (int i = 0; i < myData.size (); i++) {', ' for (int j = i + 1; j < myData.size (); j++) {', ' ', ' // get the two keys', ' DataWrapper <KeyType, DataType> pointOne = myData.get (i);', ' DataWrapper <KeyType, DataType> pointTwo = myData.get (j);', ' ', ' // find the difference between them', ' double curDist = pointOne.getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', '', ' // see if it is the biggest', ' if (curDist > maxDist) {', ' maxDist = curDist;', ' bestI = i;', ' bestJ = j;', ' }', ' }', ' }', ' ', ' // now, we have the best two points; those are seeds for the clustering', ' DataWrapper <KeyType, DataType> pointOne = myData.remove (bestI);', ' DataWrapper <KeyType, DataType> pointTwo = myData.remove (bestJ - 1);', ' ', ' // these are the two new lists', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listOne = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listTwo = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' ', ' // put the two seeds in', ' listOne.add (pointOne.getKey (), pointOne.getData ());', ' listTwo.add (pointTwo.getKey (), pointTwo.getData ());', ' ', ' // and add everyone else in', ' while (myData.size () != 0) {', ' ', ' // find the one closest to the first seed', ' int bestIndex = 0;', ' double bestDist = 9e99;', ' ', ' // loop thru all of the candidate data objects', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listOne.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' ', ' // break if no more data', ' if (myData.size () == 0)', ' break;', ' ', ' // loop thru all of the candidate data objects', ' bestDist = 9e99;', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listTwo.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' }', ' ', ' // now we replace our own guts with the first list', ' replaceGuts (listOne);', ' ', ' // and return the other list', ' return listTwo;', ' }', '}', '', 'interface IMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> {', ' ', ' // add a new pair to the list', ' public void add (KeyType keyToAdd, DataType dataToAdd);', ' ', ' // replace a key at the indicated position', ' public void replaceKey (int pos, KeyType keyToAdd);', ' ', ' // get the key, data pair that resides at a particular position', ' public DataWrapper <KeyType, DataType> get (int pos);', ' ', ' // return the number of items in the list', ' public int size ();', ' ', ' // split the list in two, using some clutering algorithm', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // get a sphere that totally bounds all of the objects in the list', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class MTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public MTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class SCMTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public SCMTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', '', 'public class MTreeTester extends TestCase {', ' ', ' // compare two lists of strings to see if the contents are the same', ' private boolean compareStringSets (ArrayList <String> setOne, ArrayList <String> setTwo) {', ' ', ' // sort the sets and make sure they are the same', ' boolean returnVal = true;', ' if (setOne.size () == setTwo.size ()) {', ' Collections.sort (setOne);', ' Collections.sort (setTwo);', ' for (int i = 0; i < setOne.size (); i++) {', ' if (!setOne.get (i).equals (setTwo.get (i))) {', ' returnVal = false;', ' break; ', ' }', ' }', ' } else {', ' returnVal = false;', ' }', ' ', ' // print out the result', ' System.out.println ("**** Expected:");', ' for (int i = 0; i < setOne.size (); i++) {', ' System.out.format (setOne.get (i) + " ");', ' }', ' System.out.println ("\\n**** Got:");', ' for (int i = 0; i < setTwo.size (); i++) {', ' System.out.format (setTwo.get (i) + " ");', ' }', ' System.out.println ("");', ' ', ' return returnVal;', ' }', ' ', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST SIMPLE ONE DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testOneDimRangeQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.find (query, expectedQuerySize / 2);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.find (query, expectedQuerySize / 2);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (numPoints);', ' result1 = myTree.find (query, expectedQuerySize);', ' result2 = hisTree.find (query, expectedQuerySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // like the last one, but runs a top k', ' private void testOneDimTopKQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (167);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.findKClosest (query, querySize);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (0);', ' result1 = myTree.findKClosest (query, querySize);', ' result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST MULTI-DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimRangeQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' double dist1 = 0;', ' double dist2 = 0;', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' dist1 = Math.sqrt (numDims) * expectedQuerySize / 2.0;', ' dist2 = Math.sqrt (numDims) * expectedQuerySize;', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' // do a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, (int) expectedQuerySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = myTree.findKClosest (query2, (int) expectedQuerySize);', ' ', ' // find the distance to the furthest point in both cases', ' for (int i = 0; i < (int) expectedQuerySize; i++) {', ' double newDist = result1.get (i).getKey ().getDistance (query1);', ' if (newDist > dist1)', ' dist1 = newDist;', ' newDist = result2.get (i).getKey ().getDistance (query2);', ' if (newDist > dist2)', ' dist2 = newDist;', ' }', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.find (query1, dist1);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.find (query1, dist1);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.find (query2, dist2);', ' result2 = hisTree.find (query2, dist2);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimTopKQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, querySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.findKClosest (query1, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.findKClosest (query2, querySize);', ' result2 = hisTree.findKClosest (query2, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' ', ' /**', ' * "TIER 1" TESTS', ' * NONE OF THESE REQUIRE ANY SPLITS', ' */', ' public void testEasy1() {', ' testOneDimRangeQuery (true, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy2() {', ' testOneDimRangeQuery (false, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy3() {', ' testOneDimRangeQuery (true, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy4() {', ' testOneDimRangeQuery (false, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy5() {', ' testMultiDimRangeQuery (true, 1, 5, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy6() {', ' testMultiDimRangeQuery (false, 1, 10, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy7() {', ' testMultiDimRangeQuery (true, 1, 5, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy8() {', ' testMultiDimRangeQuery (false, 1, 15, 10000, 10000, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 2" TESTS', ' * NONE OF THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testMod1() {', ' testOneDimRangeQuery (true, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod2() {', ' testOneDimRangeQuery (false, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod3() {', ' testOneDimRangeQuery (true, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod4() {', ' testOneDimRangeQuery (false, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod5() {', ' testMultiDimRangeQuery (true, 2, 5, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod6() {', ' testMultiDimRangeQuery (false, 2, 10, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod7() {', ' testMultiDimRangeQuery (true, 2, 5, 10000, 100, 1000, 10);', ' }', ' ', ' public void testMod8() {', ' testMultiDimRangeQuery (false, 2, 15, 10000, 100, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 3" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testHard1() {', ' testOneDimRangeQuery (true, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard2() {', ' testOneDimRangeQuery (false, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard3() {', ' testOneDimRangeQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard4() {', ' testOneDimRangeQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard5() {', ' testMultiDimRangeQuery (true, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard6() {', ' testMultiDimRangeQuery (false, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard7() {', ' testMultiDimRangeQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard8() {', ' testMultiDimRangeQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', ' ', ' /**', ' * "TIER 4" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE AND THEY TEST THE TOPK FUNCTIONALITY', ' */', ' ', ' public void testTopK1() {', ' testOneDimTopKQuery (true, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK2() {', ' testOneDimTopKQuery (false, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK3() {', ' testOneDimTopKQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK4() {', ' testOneDimTopKQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK5() {', ' testMultiDimTopKQuery (true, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK6() {', ' testMultiDimTopKQuery (false, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK7() {', ' testMultiDimTopKQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK8() {', ' testMultiDimTopKQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', '}'] | [{'reason_category': 'Define Stop Criteria', 'usage_line': 251}, {'reason_category': 'Loop Body', 'usage_line': 252}, {'reason_category': 'Loop Body', 'usage_line': 253}] | Variable 'i' used at line 251 is defined at line 251 and has a Short-Range dependency.
Global_Variable 'myList' used at line 251 is defined at line 186 and has a Long-Range dependency.
Variable 'returnVal' used at line 252 is defined at line 250 and has a Short-Range dependency.
Global_Variable 'myList' used at line 252 is defined at line 186 and has a Long-Range dependency.
Variable 'i' used at line 252 is defined at line 251 and has a Short-Range dependency.
Variable 'returnVal' used at line 255 is defined at line 250 and has a Short-Range dependency. | {'Define Stop Criteria': 1, 'Loop Body': 2} | {'Variable Short-Range': 4, 'Global_Variable Long-Range': 2} |
infilling_java | MTreeTester | 270 | 272 | ['import junit.framework.TestCase;', 'import java.util.ArrayList;', 'import java.util.Random;', 'import java.util.Collections;', '', '// this is a map from a set of keys of type PointInMetricSpace to a', '// set of data of type DataType', 'interface IMTree <Key extends IPointInMetricSpace <Key>, Data> {', ' ', ' // insert a new key/data pair into the map', ' void insert (Key keyToAdd, Data dataToAdd);', ' ', ' // find all of the key/data pairs in the map that fall within a', ' // particular distance of query point if no results are found, then', ' // an empty array is returned (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> find (Key query, double distance);', ' ', ' // find the k closest key/data pairs in the map to a particular', ' // query point ', ' //', ' // if the number of points in the map is less than k, then the', ' // returned list will have less than k pairs in it', ' //', ' // if the number of points is zero, then an empty array is returned', ' // (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> findKClosest (Key query, int k);', ' ', ' // returns the number of nodes that exist on a path from root to leaf in the tree...', ' // whtever the details of the implementation are, a tree with a single leaf node should return 1, and a tree', ' // with more than one lead node should return at least two (since it must have at least one internal node).', ' public int depth ();', ' ', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', '', 'interface IDoubleVector {', '', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '', '// this correponds to some geometric object in a metric space; the object is built out of', '// one or more points of type PointInMetricSpace', 'interface IObjectInMetricSpaceABCD <PointInMetricSpace extends IPointInMetricSpace<PointInMetricSpace>> {', ' ', ' // get the maximum distance from some point on the shape to a particular point in the metric space', ' double maxDistanceTo (PointInMetricSpace checkMe);', ' ', ' // return some arbitrary point on the interior of the geometric object', ' PointInMetricSpace getPointInInterior ();', '}', '', '', '// this interface corresponds to a point in some metric space', 'interface IPointInMetricSpace <PointInMetricSpace> {', ' ', ' // get the distance to another point', ' // ', ' // for this to work in an M-Tree, distances should be "metric" and', ' // obey the triangle inequality', ' double getDistance (PointInMetricSpace toMe);', '}', '', '// this is the basic node type in the structure', 'interface IMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> {', ' ', ' // insert a new key/data pair into the structure. The return value is a new MTreeNode if there was', ' // a split in response to the insertion, or a null if there was no split', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd);', ' ', ' // find all of the key/data pairs in the structure that fall within a particular query sphere', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query); ', ' ', ' // find the set of items closest to the given query point', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ);', ' ', ' // returns a sphere that totally encompasses everything in the node and its subtree', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', ' ', ' // returns the depth', ' public int depth ();', '}', '', '// this is a point in a particular metric space', 'class PointABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the point', ' private PointInMetricSpace me;', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return me; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return checkMe.getDistance (me); ', ' }', ' ', ' // contruct a point', ' public PointABCD (PointInMetricSpace useMe) {', ' me = useMe; ', ' }', '}', '', 'class PQueueABCD <PointInMetricSpace, DataType> {', ' ', ' // this is an object in the queue', ' private class Wrapper {', ' DataWrapper <PointInMetricSpace, DataType> myData;', ' double distance;', ' }', ' ', ' // this is the actual queue', ' ArrayList <Wrapper> myList;', ' ', ' // this is the largest distance value currently in the queue', ' double large;', ' ', ' // this is the max number of objects', ' int maxCount;', ' ', ' // create a priority queue with the speced number of slots', ' PQueueABCD (int maxCountIn) {', ' maxCount = maxCountIn;', ' myList = new ArrayList <Wrapper> ();', ' large = 9e99;', ' }', ' ', ' // get the largest distance in the queue', ' double getDist () {', ' return large;', ' }', ' ', ' // add a new object to the queue... the insertion is ignored if the distance value', ' // exceeds the largest that is in the queue and the queue is already full', ' void insert (PointInMetricSpace key, DataType data, double distance) {', ' ', ' // if we are full, remove the one with the largest distance', ' if (myList.size () == maxCount && distance < large) {', ' ', ' int badIndex = 0;', ' double maxDist = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > maxDist) {', ' maxDist = myList.get (i).distance;', ' badIndex = i;', ' }', ' }', ' ', ' myList.remove (badIndex);', ' }', ' ', ' // see if there is room', ' if (myList.size () < maxCount) {', ' ', ' // add it ', ' Wrapper newOne = new Wrapper ();', ' newOne.myData = new DataWrapper <PointInMetricSpace, DataType> (key, data);', ' newOne.distance = distance;', ' myList.add (newOne); ', ' }', ' ', ' // if we are full, reset the max distance', ' if (myList.size () == maxCount) {', ' large = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > large) {', ' large = myList.get (i).distance;', ' }', ' }', ' }', ' ', ' }', ' ', ' // extracts the contents of the queue', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> done () {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' for (int i = 0; i < myList.size (); i++) {', ' returnVal.add (myList.get (i).myData); ', ' }', ' ', ' return returnVal;', ' }', ' ', '}', '', '// this is a sphere in a particular metric space', 'class SphereABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the center of the sphere and its radius', ' private PointInMetricSpace center;', ' private double radius;', ' ', ' // build a sphere out of its center and its radius', ' public SphereABCD (PointInMetricSpace centerIn, double radiusIn) {'] | [' center = centerIn;', ' radius = radiusIn;', ' }'] | [' ', ' // increase the size of the sphere so it contains the object swallowMe', ' public void swallow (IObjectInMetricSpaceABCD <PointInMetricSpace> swallowMe) {', ' ', ' // see if we need to increase the radius to swallow this guy', ' double dist = swallowMe.maxDistanceTo (center);', ' if (dist > radius)', ' radius = dist;', ' }', ' ', ' // check to see if a sphere intersects another sphere', ' public boolean intersects (SphereABCD <PointInMetricSpace> me) {', ' return (me.center.getDistance (center) <= me.radius + radius);', ' }', ' ', ' // check to see if the sphere contains a point', ' public boolean contains (PointInMetricSpace checkMe) {', ' return (checkMe.getDistance (center) <= radius);', ' }', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return center; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return radius + checkMe.getDistance (center); ', ' }', '}', '', '', '', 'class OneDimPoint implements IPointInMetricSpace <OneDimPoint> {', ' ', ' // this is the actual double', ' Double value;', ' ', ' // construct this out of a double value', ' public OneDimPoint (double makeFromMe) {', ' value = new Double (makeFromMe);', ' }', ' ', ' // get the distance to another point', ' public double getDistance (OneDimPoint toMe) {', ' if (value > toMe.value)', ' return value - toMe.value;', ' else', ' return toMe.value - value;', ' }', ' ', '}', '', 'class MultiDimPoint implements IPointInMetricSpace <MultiDimPoint> {', ' ', ' // this is the point in a multidimensional space', ' IDoubleVector me;', ' ', ' // make this out of an IDoubleVector', ' public MultiDimPoint (IDoubleVector useMe) {', ' me = useMe;', ' }', ' ', ' // get the Euclidean distance to another point', ' public double getDistance (MultiDimPoint toMe) {', ' double distance = 0.0;', ' try {', ' for (int i = 0; i < me.getLength (); i++) {', ' double diff = me.getItem (i) - toMe.me.getItem (i);', ' diff *= diff;', ' distance += diff;', ' }', ' } catch (OutOfBoundsException e) {', ' throw new IndexOutOfBoundsException ("Can\'t compare two MultiDimPoint objects with different dimensionality!"); ', ' }', ' return Math.sqrt(distance);', ' }', ' ', '}', '// this is a leaf node', 'class LeafMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements ', ' IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myData;', ' ', ' // contructor that takes a data list and builds a node out of it', ' private LeafMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myDataIn) {', ' myData = myDataIn; ', ' }', ' ', ' // constructor that creates an empty node', ' public LeafMTreeNodeABCD () {', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> (); ', ' }', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // just add in the new data', ' myData.add (new PointABCD <PointInMetricSpace> (keyToAdd), dataToAdd);', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> newOne = myData.splitInTwo ();', ' LeafMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' myQ.insert (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData (), ', ' query.getDistance (myData.get (i).getKey ().getPointInInterior ()));', ' }', ' }', ' }', ' ', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' returnVal.add (new DataWrapper <PointInMetricSpace, DataType> (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData ()));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return 1; ', ' }', '', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', '// this silly little class is just a wrapper for a key, data pair', 'class DataWrapper <Key, Data> {', ' ', ' Key key;', ' Data data;', ' ', ' public DataWrapper (Key keyIn, Data dataIn) {', ' key = keyIn;', ' data = dataIn;', ' }', ' ', ' public Key getKey () {', ' return key;', ' }', ' ', ' public Data getData () {', ' return data;', ' }', '}', '', '', '// this is an internal node', 'class InternalMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType>', ' implements IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> myData;', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' // this constructs a new internal node that holds precisely the two nodes that are passed in', ' public InternalMTreeNodeABCD (IMTreeNodeABCD <PointInMetricSpace, DataType> refOne,', ' IMTreeNodeABCD <PointInMetricSpace, DataType> refTwo) {', ' ', ' // create a necw list and add the two guys in', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> ();', ' myData.add (refOne.getBoundingSphere (), refOne);', ' myData.add (refTwo.getBoundingSphere (), refTwo);', ' }', ' ', ' // this constructs a new node that holds the list of data that we were passed in', ' public InternalMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> useMe) {', ' myData = useMe; ', ' }', ' ', ' // from the interface', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // find the best child; this is the one we are closest to', ' double bestDist = 9e99;', ' int bestIndex = 0;', ' for (int i = 0; i < myData.size (); i++) {', ' ', ' double newDist = myData.get (i).getKey ().getPointInInterior ().getDistance (keyToAdd);', ' if (newDist < bestDist) {', ' bestDist = newDist;', ' bestIndex = i;', ' }', ' }', ' ', ' // do the recursive insert', ' IMTreeNodeABCD <PointInMetricSpace, DataType> newRef = myData.get (bestIndex).getData ().insert (keyToAdd, dataToAdd);', ' ', ' // if we got something back, then there was a split, so add the new node into our list', ' if (newRef != null) {', ' myData.add (newRef.getBoundingSphere (), newRef);', ' }', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> newOne = myData.splitInTwo ();', ' InternalMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.intersects (myData.get (i).getKey ())) {', ' myData.get (i).getData ().findKClosest (query, myQ);', ' }', ' }', ' }', ' ', ' // from the interface', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.intersects (myData.get (i).getKey ())) {', ' returnVal.addAll (myData.get (i).getData ().find (query));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return myData.get (0).getData ().depth () + 1; ', ' }', ' ', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', 'abstract class AMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> implements IMetricDataListABCD <PointInMetricSpace,KeyType, DataType> {', '', ' // this is the data that is actually stored in the list', ' private ArrayList <DataWrapper <KeyType, DataType>> myData;', ' ', ' // this is the sphere that bounds everything in the list', ' private SphereABCD <PointInMetricSpace> myBoundingSphere;', ' ', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myBoundingSphere; ', ' }', ' ', ' public int size () {', ' if (myData != null)', ' return myData.size (); ', ' else', ' return 0;', ' }', ' ', ' public DataWrapper <KeyType, DataType> get (int pos) {', ' return myData.get (pos);', ' }', ' ', ' public void replaceKey (int pos, KeyType keyToAdd) {', ' DataWrapper <KeyType, DataType> temp = myData.remove (pos);', ' DataWrapper <KeyType, DataType> newOne = new DataWrapper <KeyType, DataType> (keyToAdd, temp.getData ());', ' myData.add (pos, newOne);', ' }', ' ', ' public void add (KeyType keyToAdd, DataType dataToAdd) {', ' ', ' // if this is the first add, then set everyone up', ' if (myData == null) {', ' PointInMetricSpace myCentroid = keyToAdd.getPointInInterior ();', ' myBoundingSphere = new SphereABCD <PointInMetricSpace> (myCentroid, keyToAdd.maxDistanceTo (myCentroid));', ' myData = new ArrayList <DataWrapper <KeyType, DataType>> ();', ' ', ' // otherwise, extend the sphere if needed', ' } else {', ' myBoundingSphere.swallow (keyToAdd);', ' }', ' ', ' // add the data', ' myData.add (new DataWrapper <KeyType, DataType> (keyToAdd, dataToAdd));', ' }', ' ', ' // we want to potentially allow many implementations of the splitting lalgorithm', ' abstract public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // this is here so the actual splitting algorithn can access the list and change the sphere', ' protected ArrayList <DataWrapper <KeyType, DataType>> getList () {', ' return myData;', ' }', ' ', ' // this is here so the splitting algorithm can modify the list and the sphere', ' protected void replaceGuts (AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> withMe) {', ' myData = withMe.myData;', ' myBoundingSphere = withMe.myBoundingSphere;', ' }', ' ', '}', '', '// this is a particular implementation of the metric data list that uses a simple quadratic clustering', '// algorithm to perform a list split. It picks two "seeds" (the most distant objects) and then repeatedly', '// adds to the two new lists by choosing the objects closest to the seeds', 'class ChrisMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> extends AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> {', '', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo () {', ' ', ' // first, we need to find the two most distant points in the list', ' ArrayList <DataWrapper <KeyType, DataType>> myData = getList ();', ' int bestI = 0, bestJ = 0;', ' double maxDist = -1.0;', ' for (int i = 0; i < myData.size (); i++) {', ' for (int j = i + 1; j < myData.size (); j++) {', ' ', ' // get the two keys', ' DataWrapper <KeyType, DataType> pointOne = myData.get (i);', ' DataWrapper <KeyType, DataType> pointTwo = myData.get (j);', ' ', ' // find the difference between them', ' double curDist = pointOne.getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', '', ' // see if it is the biggest', ' if (curDist > maxDist) {', ' maxDist = curDist;', ' bestI = i;', ' bestJ = j;', ' }', ' }', ' }', ' ', ' // now, we have the best two points; those are seeds for the clustering', ' DataWrapper <KeyType, DataType> pointOne = myData.remove (bestI);', ' DataWrapper <KeyType, DataType> pointTwo = myData.remove (bestJ - 1);', ' ', ' // these are the two new lists', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listOne = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listTwo = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' ', ' // put the two seeds in', ' listOne.add (pointOne.getKey (), pointOne.getData ());', ' listTwo.add (pointTwo.getKey (), pointTwo.getData ());', ' ', ' // and add everyone else in', ' while (myData.size () != 0) {', ' ', ' // find the one closest to the first seed', ' int bestIndex = 0;', ' double bestDist = 9e99;', ' ', ' // loop thru all of the candidate data objects', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listOne.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' ', ' // break if no more data', ' if (myData.size () == 0)', ' break;', ' ', ' // loop thru all of the candidate data objects', ' bestDist = 9e99;', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listTwo.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' }', ' ', ' // now we replace our own guts with the first list', ' replaceGuts (listOne);', ' ', ' // and return the other list', ' return listTwo;', ' }', '}', '', 'interface IMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> {', ' ', ' // add a new pair to the list', ' public void add (KeyType keyToAdd, DataType dataToAdd);', ' ', ' // replace a key at the indicated position', ' public void replaceKey (int pos, KeyType keyToAdd);', ' ', ' // get the key, data pair that resides at a particular position', ' public DataWrapper <KeyType, DataType> get (int pos);', ' ', ' // return the number of items in the list', ' public int size ();', ' ', ' // split the list in two, using some clutering algorithm', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // get a sphere that totally bounds all of the objects in the list', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class MTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public MTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class SCMTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public SCMTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', '', 'public class MTreeTester extends TestCase {', ' ', ' // compare two lists of strings to see if the contents are the same', ' private boolean compareStringSets (ArrayList <String> setOne, ArrayList <String> setTwo) {', ' ', ' // sort the sets and make sure they are the same', ' boolean returnVal = true;', ' if (setOne.size () == setTwo.size ()) {', ' Collections.sort (setOne);', ' Collections.sort (setTwo);', ' for (int i = 0; i < setOne.size (); i++) {', ' if (!setOne.get (i).equals (setTwo.get (i))) {', ' returnVal = false;', ' break; ', ' }', ' }', ' } else {', ' returnVal = false;', ' }', ' ', ' // print out the result', ' System.out.println ("**** Expected:");', ' for (int i = 0; i < setOne.size (); i++) {', ' System.out.format (setOne.get (i) + " ");', ' }', ' System.out.println ("\\n**** Got:");', ' for (int i = 0; i < setTwo.size (); i++) {', ' System.out.format (setTwo.get (i) + " ");', ' }', ' System.out.println ("");', ' ', ' return returnVal;', ' }', ' ', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST SIMPLE ONE DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testOneDimRangeQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.find (query, expectedQuerySize / 2);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.find (query, expectedQuerySize / 2);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (numPoints);', ' result1 = myTree.find (query, expectedQuerySize);', ' result2 = hisTree.find (query, expectedQuerySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // like the last one, but runs a top k', ' private void testOneDimTopKQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (167);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.findKClosest (query, querySize);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (0);', ' result1 = myTree.findKClosest (query, querySize);', ' result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST MULTI-DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimRangeQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' double dist1 = 0;', ' double dist2 = 0;', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' dist1 = Math.sqrt (numDims) * expectedQuerySize / 2.0;', ' dist2 = Math.sqrt (numDims) * expectedQuerySize;', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' // do a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, (int) expectedQuerySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = myTree.findKClosest (query2, (int) expectedQuerySize);', ' ', ' // find the distance to the furthest point in both cases', ' for (int i = 0; i < (int) expectedQuerySize; i++) {', ' double newDist = result1.get (i).getKey ().getDistance (query1);', ' if (newDist > dist1)', ' dist1 = newDist;', ' newDist = result2.get (i).getKey ().getDistance (query2);', ' if (newDist > dist2)', ' dist2 = newDist;', ' }', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.find (query1, dist1);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.find (query1, dist1);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.find (query2, dist2);', ' result2 = hisTree.find (query2, dist2);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimTopKQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, querySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.findKClosest (query1, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.findKClosest (query2, querySize);', ' result2 = hisTree.findKClosest (query2, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' ', ' /**', ' * "TIER 1" TESTS', ' * NONE OF THESE REQUIRE ANY SPLITS', ' */', ' public void testEasy1() {', ' testOneDimRangeQuery (true, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy2() {', ' testOneDimRangeQuery (false, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy3() {', ' testOneDimRangeQuery (true, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy4() {', ' testOneDimRangeQuery (false, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy5() {', ' testMultiDimRangeQuery (true, 1, 5, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy6() {', ' testMultiDimRangeQuery (false, 1, 10, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy7() {', ' testMultiDimRangeQuery (true, 1, 5, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy8() {', ' testMultiDimRangeQuery (false, 1, 15, 10000, 10000, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 2" TESTS', ' * NONE OF THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testMod1() {', ' testOneDimRangeQuery (true, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod2() {', ' testOneDimRangeQuery (false, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod3() {', ' testOneDimRangeQuery (true, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod4() {', ' testOneDimRangeQuery (false, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod5() {', ' testMultiDimRangeQuery (true, 2, 5, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod6() {', ' testMultiDimRangeQuery (false, 2, 10, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod7() {', ' testMultiDimRangeQuery (true, 2, 5, 10000, 100, 1000, 10);', ' }', ' ', ' public void testMod8() {', ' testMultiDimRangeQuery (false, 2, 15, 10000, 100, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 3" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testHard1() {', ' testOneDimRangeQuery (true, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard2() {', ' testOneDimRangeQuery (false, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard3() {', ' testOneDimRangeQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard4() {', ' testOneDimRangeQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard5() {', ' testMultiDimRangeQuery (true, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard6() {', ' testMultiDimRangeQuery (false, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard7() {', ' testMultiDimRangeQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard8() {', ' testMultiDimRangeQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', ' ', ' /**', ' * "TIER 4" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE AND THEY TEST THE TOPK FUNCTIONALITY', ' */', ' ', ' public void testTopK1() {', ' testOneDimTopKQuery (true, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK2() {', ' testOneDimTopKQuery (false, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK3() {', ' testOneDimTopKQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK4() {', ' testOneDimTopKQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK5() {', ' testMultiDimTopKQuery (true, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK6() {', ' testMultiDimTopKQuery (false, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK7() {', ' testMultiDimTopKQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK8() {', ' testMultiDimTopKQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', '}'] | [] | Variable 'centerIn' used at line 270 is defined at line 269 and has a Short-Range dependency.
Global_Variable 'center' used at line 270 is defined at line 265 and has a Short-Range dependency.
Variable 'radiusIn' used at line 271 is defined at line 269 and has a Short-Range dependency.
Global_Variable 'radius' used at line 271 is defined at line 266 and has a Short-Range dependency. | {} | {'Variable Short-Range': 2, 'Global_Variable Short-Range': 2} |
infilling_java | MTreeTester | 280 | 281 | ['import junit.framework.TestCase;', 'import java.util.ArrayList;', 'import java.util.Random;', 'import java.util.Collections;', '', '// this is a map from a set of keys of type PointInMetricSpace to a', '// set of data of type DataType', 'interface IMTree <Key extends IPointInMetricSpace <Key>, Data> {', ' ', ' // insert a new key/data pair into the map', ' void insert (Key keyToAdd, Data dataToAdd);', ' ', ' // find all of the key/data pairs in the map that fall within a', ' // particular distance of query point if no results are found, then', ' // an empty array is returned (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> find (Key query, double distance);', ' ', ' // find the k closest key/data pairs in the map to a particular', ' // query point ', ' //', ' // if the number of points in the map is less than k, then the', ' // returned list will have less than k pairs in it', ' //', ' // if the number of points is zero, then an empty array is returned', ' // (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> findKClosest (Key query, int k);', ' ', ' // returns the number of nodes that exist on a path from root to leaf in the tree...', ' // whtever the details of the implementation are, a tree with a single leaf node should return 1, and a tree', ' // with more than one lead node should return at least two (since it must have at least one internal node).', ' public int depth ();', ' ', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', '', 'interface IDoubleVector {', '', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '', '// this correponds to some geometric object in a metric space; the object is built out of', '// one or more points of type PointInMetricSpace', 'interface IObjectInMetricSpaceABCD <PointInMetricSpace extends IPointInMetricSpace<PointInMetricSpace>> {', ' ', ' // get the maximum distance from some point on the shape to a particular point in the metric space', ' double maxDistanceTo (PointInMetricSpace checkMe);', ' ', ' // return some arbitrary point on the interior of the geometric object', ' PointInMetricSpace getPointInInterior ();', '}', '', '', '// this interface corresponds to a point in some metric space', 'interface IPointInMetricSpace <PointInMetricSpace> {', ' ', ' // get the distance to another point', ' // ', ' // for this to work in an M-Tree, distances should be "metric" and', ' // obey the triangle inequality', ' double getDistance (PointInMetricSpace toMe);', '}', '', '// this is the basic node type in the structure', 'interface IMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> {', ' ', ' // insert a new key/data pair into the structure. The return value is a new MTreeNode if there was', ' // a split in response to the insertion, or a null if there was no split', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd);', ' ', ' // find all of the key/data pairs in the structure that fall within a particular query sphere', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query); ', ' ', ' // find the set of items closest to the given query point', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ);', ' ', ' // returns a sphere that totally encompasses everything in the node and its subtree', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', ' ', ' // returns the depth', ' public int depth ();', '}', '', '// this is a point in a particular metric space', 'class PointABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the point', ' private PointInMetricSpace me;', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return me; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return checkMe.getDistance (me); ', ' }', ' ', ' // contruct a point', ' public PointABCD (PointInMetricSpace useMe) {', ' me = useMe; ', ' }', '}', '', 'class PQueueABCD <PointInMetricSpace, DataType> {', ' ', ' // this is an object in the queue', ' private class Wrapper {', ' DataWrapper <PointInMetricSpace, DataType> myData;', ' double distance;', ' }', ' ', ' // this is the actual queue', ' ArrayList <Wrapper> myList;', ' ', ' // this is the largest distance value currently in the queue', ' double large;', ' ', ' // this is the max number of objects', ' int maxCount;', ' ', ' // create a priority queue with the speced number of slots', ' PQueueABCD (int maxCountIn) {', ' maxCount = maxCountIn;', ' myList = new ArrayList <Wrapper> ();', ' large = 9e99;', ' }', ' ', ' // get the largest distance in the queue', ' double getDist () {', ' return large;', ' }', ' ', ' // add a new object to the queue... the insertion is ignored if the distance value', ' // exceeds the largest that is in the queue and the queue is already full', ' void insert (PointInMetricSpace key, DataType data, double distance) {', ' ', ' // if we are full, remove the one with the largest distance', ' if (myList.size () == maxCount && distance < large) {', ' ', ' int badIndex = 0;', ' double maxDist = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > maxDist) {', ' maxDist = myList.get (i).distance;', ' badIndex = i;', ' }', ' }', ' ', ' myList.remove (badIndex);', ' }', ' ', ' // see if there is room', ' if (myList.size () < maxCount) {', ' ', ' // add it ', ' Wrapper newOne = new Wrapper ();', ' newOne.myData = new DataWrapper <PointInMetricSpace, DataType> (key, data);', ' newOne.distance = distance;', ' myList.add (newOne); ', ' }', ' ', ' // if we are full, reset the max distance', ' if (myList.size () == maxCount) {', ' large = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > large) {', ' large = myList.get (i).distance;', ' }', ' }', ' }', ' ', ' }', ' ', ' // extracts the contents of the queue', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> done () {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' for (int i = 0; i < myList.size (); i++) {', ' returnVal.add (myList.get (i).myData); ', ' }', ' ', ' return returnVal;', ' }', ' ', '}', '', '// this is a sphere in a particular metric space', 'class SphereABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the center of the sphere and its radius', ' private PointInMetricSpace center;', ' private double radius;', ' ', ' // build a sphere out of its center and its radius', ' public SphereABCD (PointInMetricSpace centerIn, double radiusIn) {', ' center = centerIn;', ' radius = radiusIn;', ' }', ' ', ' // increase the size of the sphere so it contains the object swallowMe', ' public void swallow (IObjectInMetricSpaceABCD <PointInMetricSpace> swallowMe) {', ' ', ' // see if we need to increase the radius to swallow this guy', ' double dist = swallowMe.maxDistanceTo (center);', ' if (dist > radius)'] | [' radius = dist;', ' }'] | [' ', ' // check to see if a sphere intersects another sphere', ' public boolean intersects (SphereABCD <PointInMetricSpace> me) {', ' return (me.center.getDistance (center) <= me.radius + radius);', ' }', ' ', ' // check to see if the sphere contains a point', ' public boolean contains (PointInMetricSpace checkMe) {', ' return (checkMe.getDistance (center) <= radius);', ' }', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return center; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return radius + checkMe.getDistance (center); ', ' }', '}', '', '', '', 'class OneDimPoint implements IPointInMetricSpace <OneDimPoint> {', ' ', ' // this is the actual double', ' Double value;', ' ', ' // construct this out of a double value', ' public OneDimPoint (double makeFromMe) {', ' value = new Double (makeFromMe);', ' }', ' ', ' // get the distance to another point', ' public double getDistance (OneDimPoint toMe) {', ' if (value > toMe.value)', ' return value - toMe.value;', ' else', ' return toMe.value - value;', ' }', ' ', '}', '', 'class MultiDimPoint implements IPointInMetricSpace <MultiDimPoint> {', ' ', ' // this is the point in a multidimensional space', ' IDoubleVector me;', ' ', ' // make this out of an IDoubleVector', ' public MultiDimPoint (IDoubleVector useMe) {', ' me = useMe;', ' }', ' ', ' // get the Euclidean distance to another point', ' public double getDistance (MultiDimPoint toMe) {', ' double distance = 0.0;', ' try {', ' for (int i = 0; i < me.getLength (); i++) {', ' double diff = me.getItem (i) - toMe.me.getItem (i);', ' diff *= diff;', ' distance += diff;', ' }', ' } catch (OutOfBoundsException e) {', ' throw new IndexOutOfBoundsException ("Can\'t compare two MultiDimPoint objects with different dimensionality!"); ', ' }', ' return Math.sqrt(distance);', ' }', ' ', '}', '// this is a leaf node', 'class LeafMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements ', ' IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myData;', ' ', ' // contructor that takes a data list and builds a node out of it', ' private LeafMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myDataIn) {', ' myData = myDataIn; ', ' }', ' ', ' // constructor that creates an empty node', ' public LeafMTreeNodeABCD () {', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> (); ', ' }', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // just add in the new data', ' myData.add (new PointABCD <PointInMetricSpace> (keyToAdd), dataToAdd);', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> newOne = myData.splitInTwo ();', ' LeafMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' myQ.insert (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData (), ', ' query.getDistance (myData.get (i).getKey ().getPointInInterior ()));', ' }', ' }', ' }', ' ', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' returnVal.add (new DataWrapper <PointInMetricSpace, DataType> (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData ()));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return 1; ', ' }', '', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', '// this silly little class is just a wrapper for a key, data pair', 'class DataWrapper <Key, Data> {', ' ', ' Key key;', ' Data data;', ' ', ' public DataWrapper (Key keyIn, Data dataIn) {', ' key = keyIn;', ' data = dataIn;', ' }', ' ', ' public Key getKey () {', ' return key;', ' }', ' ', ' public Data getData () {', ' return data;', ' }', '}', '', '', '// this is an internal node', 'class InternalMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType>', ' implements IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> myData;', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' // this constructs a new internal node that holds precisely the two nodes that are passed in', ' public InternalMTreeNodeABCD (IMTreeNodeABCD <PointInMetricSpace, DataType> refOne,', ' IMTreeNodeABCD <PointInMetricSpace, DataType> refTwo) {', ' ', ' // create a necw list and add the two guys in', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> ();', ' myData.add (refOne.getBoundingSphere (), refOne);', ' myData.add (refTwo.getBoundingSphere (), refTwo);', ' }', ' ', ' // this constructs a new node that holds the list of data that we were passed in', ' public InternalMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> useMe) {', ' myData = useMe; ', ' }', ' ', ' // from the interface', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // find the best child; this is the one we are closest to', ' double bestDist = 9e99;', ' int bestIndex = 0;', ' for (int i = 0; i < myData.size (); i++) {', ' ', ' double newDist = myData.get (i).getKey ().getPointInInterior ().getDistance (keyToAdd);', ' if (newDist < bestDist) {', ' bestDist = newDist;', ' bestIndex = i;', ' }', ' }', ' ', ' // do the recursive insert', ' IMTreeNodeABCD <PointInMetricSpace, DataType> newRef = myData.get (bestIndex).getData ().insert (keyToAdd, dataToAdd);', ' ', ' // if we got something back, then there was a split, so add the new node into our list', ' if (newRef != null) {', ' myData.add (newRef.getBoundingSphere (), newRef);', ' }', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> newOne = myData.splitInTwo ();', ' InternalMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.intersects (myData.get (i).getKey ())) {', ' myData.get (i).getData ().findKClosest (query, myQ);', ' }', ' }', ' }', ' ', ' // from the interface', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.intersects (myData.get (i).getKey ())) {', ' returnVal.addAll (myData.get (i).getData ().find (query));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return myData.get (0).getData ().depth () + 1; ', ' }', ' ', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', 'abstract class AMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> implements IMetricDataListABCD <PointInMetricSpace,KeyType, DataType> {', '', ' // this is the data that is actually stored in the list', ' private ArrayList <DataWrapper <KeyType, DataType>> myData;', ' ', ' // this is the sphere that bounds everything in the list', ' private SphereABCD <PointInMetricSpace> myBoundingSphere;', ' ', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myBoundingSphere; ', ' }', ' ', ' public int size () {', ' if (myData != null)', ' return myData.size (); ', ' else', ' return 0;', ' }', ' ', ' public DataWrapper <KeyType, DataType> get (int pos) {', ' return myData.get (pos);', ' }', ' ', ' public void replaceKey (int pos, KeyType keyToAdd) {', ' DataWrapper <KeyType, DataType> temp = myData.remove (pos);', ' DataWrapper <KeyType, DataType> newOne = new DataWrapper <KeyType, DataType> (keyToAdd, temp.getData ());', ' myData.add (pos, newOne);', ' }', ' ', ' public void add (KeyType keyToAdd, DataType dataToAdd) {', ' ', ' // if this is the first add, then set everyone up', ' if (myData == null) {', ' PointInMetricSpace myCentroid = keyToAdd.getPointInInterior ();', ' myBoundingSphere = new SphereABCD <PointInMetricSpace> (myCentroid, keyToAdd.maxDistanceTo (myCentroid));', ' myData = new ArrayList <DataWrapper <KeyType, DataType>> ();', ' ', ' // otherwise, extend the sphere if needed', ' } else {', ' myBoundingSphere.swallow (keyToAdd);', ' }', ' ', ' // add the data', ' myData.add (new DataWrapper <KeyType, DataType> (keyToAdd, dataToAdd));', ' }', ' ', ' // we want to potentially allow many implementations of the splitting lalgorithm', ' abstract public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // this is here so the actual splitting algorithn can access the list and change the sphere', ' protected ArrayList <DataWrapper <KeyType, DataType>> getList () {', ' return myData;', ' }', ' ', ' // this is here so the splitting algorithm can modify the list and the sphere', ' protected void replaceGuts (AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> withMe) {', ' myData = withMe.myData;', ' myBoundingSphere = withMe.myBoundingSphere;', ' }', ' ', '}', '', '// this is a particular implementation of the metric data list that uses a simple quadratic clustering', '// algorithm to perform a list split. It picks two "seeds" (the most distant objects) and then repeatedly', '// adds to the two new lists by choosing the objects closest to the seeds', 'class ChrisMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> extends AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> {', '', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo () {', ' ', ' // first, we need to find the two most distant points in the list', ' ArrayList <DataWrapper <KeyType, DataType>> myData = getList ();', ' int bestI = 0, bestJ = 0;', ' double maxDist = -1.0;', ' for (int i = 0; i < myData.size (); i++) {', ' for (int j = i + 1; j < myData.size (); j++) {', ' ', ' // get the two keys', ' DataWrapper <KeyType, DataType> pointOne = myData.get (i);', ' DataWrapper <KeyType, DataType> pointTwo = myData.get (j);', ' ', ' // find the difference between them', ' double curDist = pointOne.getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', '', ' // see if it is the biggest', ' if (curDist > maxDist) {', ' maxDist = curDist;', ' bestI = i;', ' bestJ = j;', ' }', ' }', ' }', ' ', ' // now, we have the best two points; those are seeds for the clustering', ' DataWrapper <KeyType, DataType> pointOne = myData.remove (bestI);', ' DataWrapper <KeyType, DataType> pointTwo = myData.remove (bestJ - 1);', ' ', ' // these are the two new lists', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listOne = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listTwo = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' ', ' // put the two seeds in', ' listOne.add (pointOne.getKey (), pointOne.getData ());', ' listTwo.add (pointTwo.getKey (), pointTwo.getData ());', ' ', ' // and add everyone else in', ' while (myData.size () != 0) {', ' ', ' // find the one closest to the first seed', ' int bestIndex = 0;', ' double bestDist = 9e99;', ' ', ' // loop thru all of the candidate data objects', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listOne.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' ', ' // break if no more data', ' if (myData.size () == 0)', ' break;', ' ', ' // loop thru all of the candidate data objects', ' bestDist = 9e99;', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listTwo.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' }', ' ', ' // now we replace our own guts with the first list', ' replaceGuts (listOne);', ' ', ' // and return the other list', ' return listTwo;', ' }', '}', '', 'interface IMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> {', ' ', ' // add a new pair to the list', ' public void add (KeyType keyToAdd, DataType dataToAdd);', ' ', ' // replace a key at the indicated position', ' public void replaceKey (int pos, KeyType keyToAdd);', ' ', ' // get the key, data pair that resides at a particular position', ' public DataWrapper <KeyType, DataType> get (int pos);', ' ', ' // return the number of items in the list', ' public int size ();', ' ', ' // split the list in two, using some clutering algorithm', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // get a sphere that totally bounds all of the objects in the list', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class MTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public MTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class SCMTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public SCMTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', '', 'public class MTreeTester extends TestCase {', ' ', ' // compare two lists of strings to see if the contents are the same', ' private boolean compareStringSets (ArrayList <String> setOne, ArrayList <String> setTwo) {', ' ', ' // sort the sets and make sure they are the same', ' boolean returnVal = true;', ' if (setOne.size () == setTwo.size ()) {', ' Collections.sort (setOne);', ' Collections.sort (setTwo);', ' for (int i = 0; i < setOne.size (); i++) {', ' if (!setOne.get (i).equals (setTwo.get (i))) {', ' returnVal = false;', ' break; ', ' }', ' }', ' } else {', ' returnVal = false;', ' }', ' ', ' // print out the result', ' System.out.println ("**** Expected:");', ' for (int i = 0; i < setOne.size (); i++) {', ' System.out.format (setOne.get (i) + " ");', ' }', ' System.out.println ("\\n**** Got:");', ' for (int i = 0; i < setTwo.size (); i++) {', ' System.out.format (setTwo.get (i) + " ");', ' }', ' System.out.println ("");', ' ', ' return returnVal;', ' }', ' ', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST SIMPLE ONE DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testOneDimRangeQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.find (query, expectedQuerySize / 2);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.find (query, expectedQuerySize / 2);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (numPoints);', ' result1 = myTree.find (query, expectedQuerySize);', ' result2 = hisTree.find (query, expectedQuerySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // like the last one, but runs a top k', ' private void testOneDimTopKQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (167);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.findKClosest (query, querySize);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (0);', ' result1 = myTree.findKClosest (query, querySize);', ' result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST MULTI-DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimRangeQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' double dist1 = 0;', ' double dist2 = 0;', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' dist1 = Math.sqrt (numDims) * expectedQuerySize / 2.0;', ' dist2 = Math.sqrt (numDims) * expectedQuerySize;', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' // do a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, (int) expectedQuerySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = myTree.findKClosest (query2, (int) expectedQuerySize);', ' ', ' // find the distance to the furthest point in both cases', ' for (int i = 0; i < (int) expectedQuerySize; i++) {', ' double newDist = result1.get (i).getKey ().getDistance (query1);', ' if (newDist > dist1)', ' dist1 = newDist;', ' newDist = result2.get (i).getKey ().getDistance (query2);', ' if (newDist > dist2)', ' dist2 = newDist;', ' }', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.find (query1, dist1);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.find (query1, dist1);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.find (query2, dist2);', ' result2 = hisTree.find (query2, dist2);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimTopKQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, querySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.findKClosest (query1, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.findKClosest (query2, querySize);', ' result2 = hisTree.findKClosest (query2, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' ', ' /**', ' * "TIER 1" TESTS', ' * NONE OF THESE REQUIRE ANY SPLITS', ' */', ' public void testEasy1() {', ' testOneDimRangeQuery (true, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy2() {', ' testOneDimRangeQuery (false, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy3() {', ' testOneDimRangeQuery (true, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy4() {', ' testOneDimRangeQuery (false, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy5() {', ' testMultiDimRangeQuery (true, 1, 5, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy6() {', ' testMultiDimRangeQuery (false, 1, 10, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy7() {', ' testMultiDimRangeQuery (true, 1, 5, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy8() {', ' testMultiDimRangeQuery (false, 1, 15, 10000, 10000, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 2" TESTS', ' * NONE OF THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testMod1() {', ' testOneDimRangeQuery (true, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod2() {', ' testOneDimRangeQuery (false, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod3() {', ' testOneDimRangeQuery (true, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod4() {', ' testOneDimRangeQuery (false, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod5() {', ' testMultiDimRangeQuery (true, 2, 5, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod6() {', ' testMultiDimRangeQuery (false, 2, 10, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod7() {', ' testMultiDimRangeQuery (true, 2, 5, 10000, 100, 1000, 10);', ' }', ' ', ' public void testMod8() {', ' testMultiDimRangeQuery (false, 2, 15, 10000, 100, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 3" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testHard1() {', ' testOneDimRangeQuery (true, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard2() {', ' testOneDimRangeQuery (false, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard3() {', ' testOneDimRangeQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard4() {', ' testOneDimRangeQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard5() {', ' testMultiDimRangeQuery (true, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard6() {', ' testMultiDimRangeQuery (false, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard7() {', ' testMultiDimRangeQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard8() {', ' testMultiDimRangeQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', ' ', ' /**', ' * "TIER 4" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE AND THEY TEST THE TOPK FUNCTIONALITY', ' */', ' ', ' public void testTopK1() {', ' testOneDimTopKQuery (true, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK2() {', ' testOneDimTopKQuery (false, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK3() {', ' testOneDimTopKQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK4() {', ' testOneDimTopKQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK5() {', ' testMultiDimTopKQuery (true, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK6() {', ' testMultiDimTopKQuery (false, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK7() {', ' testMultiDimTopKQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK8() {', ' testMultiDimTopKQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', '}'] | [{'reason_category': 'If Body', 'usage_line': 280}, {'reason_category': 'If Body', 'usage_line': 281}] | Variable 'dist' used at line 280 is defined at line 278 and has a Short-Range dependency.
Global_Variable 'radius' used at line 280 is defined at line 266 and has a Medium-Range dependency. | {'If Body': 2} | {'Variable Short-Range': 1, 'Global_Variable Medium-Range': 1} |
infilling_java | MTreeTester | 285 | 286 | ['import junit.framework.TestCase;', 'import java.util.ArrayList;', 'import java.util.Random;', 'import java.util.Collections;', '', '// this is a map from a set of keys of type PointInMetricSpace to a', '// set of data of type DataType', 'interface IMTree <Key extends IPointInMetricSpace <Key>, Data> {', ' ', ' // insert a new key/data pair into the map', ' void insert (Key keyToAdd, Data dataToAdd);', ' ', ' // find all of the key/data pairs in the map that fall within a', ' // particular distance of query point if no results are found, then', ' // an empty array is returned (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> find (Key query, double distance);', ' ', ' // find the k closest key/data pairs in the map to a particular', ' // query point ', ' //', ' // if the number of points in the map is less than k, then the', ' // returned list will have less than k pairs in it', ' //', ' // if the number of points is zero, then an empty array is returned', ' // (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> findKClosest (Key query, int k);', ' ', ' // returns the number of nodes that exist on a path from root to leaf in the tree...', ' // whtever the details of the implementation are, a tree with a single leaf node should return 1, and a tree', ' // with more than one lead node should return at least two (since it must have at least one internal node).', ' public int depth ();', ' ', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', '', 'interface IDoubleVector {', '', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '', '// this correponds to some geometric object in a metric space; the object is built out of', '// one or more points of type PointInMetricSpace', 'interface IObjectInMetricSpaceABCD <PointInMetricSpace extends IPointInMetricSpace<PointInMetricSpace>> {', ' ', ' // get the maximum distance from some point on the shape to a particular point in the metric space', ' double maxDistanceTo (PointInMetricSpace checkMe);', ' ', ' // return some arbitrary point on the interior of the geometric object', ' PointInMetricSpace getPointInInterior ();', '}', '', '', '// this interface corresponds to a point in some metric space', 'interface IPointInMetricSpace <PointInMetricSpace> {', ' ', ' // get the distance to another point', ' // ', ' // for this to work in an M-Tree, distances should be "metric" and', ' // obey the triangle inequality', ' double getDistance (PointInMetricSpace toMe);', '}', '', '// this is the basic node type in the structure', 'interface IMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> {', ' ', ' // insert a new key/data pair into the structure. The return value is a new MTreeNode if there was', ' // a split in response to the insertion, or a null if there was no split', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd);', ' ', ' // find all of the key/data pairs in the structure that fall within a particular query sphere', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query); ', ' ', ' // find the set of items closest to the given query point', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ);', ' ', ' // returns a sphere that totally encompasses everything in the node and its subtree', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', ' ', ' // returns the depth', ' public int depth ();', '}', '', '// this is a point in a particular metric space', 'class PointABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the point', ' private PointInMetricSpace me;', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return me; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return checkMe.getDistance (me); ', ' }', ' ', ' // contruct a point', ' public PointABCD (PointInMetricSpace useMe) {', ' me = useMe; ', ' }', '}', '', 'class PQueueABCD <PointInMetricSpace, DataType> {', ' ', ' // this is an object in the queue', ' private class Wrapper {', ' DataWrapper <PointInMetricSpace, DataType> myData;', ' double distance;', ' }', ' ', ' // this is the actual queue', ' ArrayList <Wrapper> myList;', ' ', ' // this is the largest distance value currently in the queue', ' double large;', ' ', ' // this is the max number of objects', ' int maxCount;', ' ', ' // create a priority queue with the speced number of slots', ' PQueueABCD (int maxCountIn) {', ' maxCount = maxCountIn;', ' myList = new ArrayList <Wrapper> ();', ' large = 9e99;', ' }', ' ', ' // get the largest distance in the queue', ' double getDist () {', ' return large;', ' }', ' ', ' // add a new object to the queue... the insertion is ignored if the distance value', ' // exceeds the largest that is in the queue and the queue is already full', ' void insert (PointInMetricSpace key, DataType data, double distance) {', ' ', ' // if we are full, remove the one with the largest distance', ' if (myList.size () == maxCount && distance < large) {', ' ', ' int badIndex = 0;', ' double maxDist = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > maxDist) {', ' maxDist = myList.get (i).distance;', ' badIndex = i;', ' }', ' }', ' ', ' myList.remove (badIndex);', ' }', ' ', ' // see if there is room', ' if (myList.size () < maxCount) {', ' ', ' // add it ', ' Wrapper newOne = new Wrapper ();', ' newOne.myData = new DataWrapper <PointInMetricSpace, DataType> (key, data);', ' newOne.distance = distance;', ' myList.add (newOne); ', ' }', ' ', ' // if we are full, reset the max distance', ' if (myList.size () == maxCount) {', ' large = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > large) {', ' large = myList.get (i).distance;', ' }', ' }', ' }', ' ', ' }', ' ', ' // extracts the contents of the queue', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> done () {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' for (int i = 0; i < myList.size (); i++) {', ' returnVal.add (myList.get (i).myData); ', ' }', ' ', ' return returnVal;', ' }', ' ', '}', '', '// this is a sphere in a particular metric space', 'class SphereABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the center of the sphere and its radius', ' private PointInMetricSpace center;', ' private double radius;', ' ', ' // build a sphere out of its center and its radius', ' public SphereABCD (PointInMetricSpace centerIn, double radiusIn) {', ' center = centerIn;', ' radius = radiusIn;', ' }', ' ', ' // increase the size of the sphere so it contains the object swallowMe', ' public void swallow (IObjectInMetricSpaceABCD <PointInMetricSpace> swallowMe) {', ' ', ' // see if we need to increase the radius to swallow this guy', ' double dist = swallowMe.maxDistanceTo (center);', ' if (dist > radius)', ' radius = dist;', ' }', ' ', ' // check to see if a sphere intersects another sphere', ' public boolean intersects (SphereABCD <PointInMetricSpace> me) {'] | [' return (me.center.getDistance (center) <= me.radius + radius);', ' }'] | [' ', ' // check to see if the sphere contains a point', ' public boolean contains (PointInMetricSpace checkMe) {', ' return (checkMe.getDistance (center) <= radius);', ' }', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return center; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return radius + checkMe.getDistance (center); ', ' }', '}', '', '', '', 'class OneDimPoint implements IPointInMetricSpace <OneDimPoint> {', ' ', ' // this is the actual double', ' Double value;', ' ', ' // construct this out of a double value', ' public OneDimPoint (double makeFromMe) {', ' value = new Double (makeFromMe);', ' }', ' ', ' // get the distance to another point', ' public double getDistance (OneDimPoint toMe) {', ' if (value > toMe.value)', ' return value - toMe.value;', ' else', ' return toMe.value - value;', ' }', ' ', '}', '', 'class MultiDimPoint implements IPointInMetricSpace <MultiDimPoint> {', ' ', ' // this is the point in a multidimensional space', ' IDoubleVector me;', ' ', ' // make this out of an IDoubleVector', ' public MultiDimPoint (IDoubleVector useMe) {', ' me = useMe;', ' }', ' ', ' // get the Euclidean distance to another point', ' public double getDistance (MultiDimPoint toMe) {', ' double distance = 0.0;', ' try {', ' for (int i = 0; i < me.getLength (); i++) {', ' double diff = me.getItem (i) - toMe.me.getItem (i);', ' diff *= diff;', ' distance += diff;', ' }', ' } catch (OutOfBoundsException e) {', ' throw new IndexOutOfBoundsException ("Can\'t compare two MultiDimPoint objects with different dimensionality!"); ', ' }', ' return Math.sqrt(distance);', ' }', ' ', '}', '// this is a leaf node', 'class LeafMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements ', ' IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myData;', ' ', ' // contructor that takes a data list and builds a node out of it', ' private LeafMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myDataIn) {', ' myData = myDataIn; ', ' }', ' ', ' // constructor that creates an empty node', ' public LeafMTreeNodeABCD () {', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> (); ', ' }', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // just add in the new data', ' myData.add (new PointABCD <PointInMetricSpace> (keyToAdd), dataToAdd);', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> newOne = myData.splitInTwo ();', ' LeafMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' myQ.insert (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData (), ', ' query.getDistance (myData.get (i).getKey ().getPointInInterior ()));', ' }', ' }', ' }', ' ', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' returnVal.add (new DataWrapper <PointInMetricSpace, DataType> (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData ()));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return 1; ', ' }', '', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', '// this silly little class is just a wrapper for a key, data pair', 'class DataWrapper <Key, Data> {', ' ', ' Key key;', ' Data data;', ' ', ' public DataWrapper (Key keyIn, Data dataIn) {', ' key = keyIn;', ' data = dataIn;', ' }', ' ', ' public Key getKey () {', ' return key;', ' }', ' ', ' public Data getData () {', ' return data;', ' }', '}', '', '', '// this is an internal node', 'class InternalMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType>', ' implements IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> myData;', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' // this constructs a new internal node that holds precisely the two nodes that are passed in', ' public InternalMTreeNodeABCD (IMTreeNodeABCD <PointInMetricSpace, DataType> refOne,', ' IMTreeNodeABCD <PointInMetricSpace, DataType> refTwo) {', ' ', ' // create a necw list and add the two guys in', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> ();', ' myData.add (refOne.getBoundingSphere (), refOne);', ' myData.add (refTwo.getBoundingSphere (), refTwo);', ' }', ' ', ' // this constructs a new node that holds the list of data that we were passed in', ' public InternalMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> useMe) {', ' myData = useMe; ', ' }', ' ', ' // from the interface', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // find the best child; this is the one we are closest to', ' double bestDist = 9e99;', ' int bestIndex = 0;', ' for (int i = 0; i < myData.size (); i++) {', ' ', ' double newDist = myData.get (i).getKey ().getPointInInterior ().getDistance (keyToAdd);', ' if (newDist < bestDist) {', ' bestDist = newDist;', ' bestIndex = i;', ' }', ' }', ' ', ' // do the recursive insert', ' IMTreeNodeABCD <PointInMetricSpace, DataType> newRef = myData.get (bestIndex).getData ().insert (keyToAdd, dataToAdd);', ' ', ' // if we got something back, then there was a split, so add the new node into our list', ' if (newRef != null) {', ' myData.add (newRef.getBoundingSphere (), newRef);', ' }', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> newOne = myData.splitInTwo ();', ' InternalMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.intersects (myData.get (i).getKey ())) {', ' myData.get (i).getData ().findKClosest (query, myQ);', ' }', ' }', ' }', ' ', ' // from the interface', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.intersects (myData.get (i).getKey ())) {', ' returnVal.addAll (myData.get (i).getData ().find (query));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return myData.get (0).getData ().depth () + 1; ', ' }', ' ', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', 'abstract class AMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> implements IMetricDataListABCD <PointInMetricSpace,KeyType, DataType> {', '', ' // this is the data that is actually stored in the list', ' private ArrayList <DataWrapper <KeyType, DataType>> myData;', ' ', ' // this is the sphere that bounds everything in the list', ' private SphereABCD <PointInMetricSpace> myBoundingSphere;', ' ', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myBoundingSphere; ', ' }', ' ', ' public int size () {', ' if (myData != null)', ' return myData.size (); ', ' else', ' return 0;', ' }', ' ', ' public DataWrapper <KeyType, DataType> get (int pos) {', ' return myData.get (pos);', ' }', ' ', ' public void replaceKey (int pos, KeyType keyToAdd) {', ' DataWrapper <KeyType, DataType> temp = myData.remove (pos);', ' DataWrapper <KeyType, DataType> newOne = new DataWrapper <KeyType, DataType> (keyToAdd, temp.getData ());', ' myData.add (pos, newOne);', ' }', ' ', ' public void add (KeyType keyToAdd, DataType dataToAdd) {', ' ', ' // if this is the first add, then set everyone up', ' if (myData == null) {', ' PointInMetricSpace myCentroid = keyToAdd.getPointInInterior ();', ' myBoundingSphere = new SphereABCD <PointInMetricSpace> (myCentroid, keyToAdd.maxDistanceTo (myCentroid));', ' myData = new ArrayList <DataWrapper <KeyType, DataType>> ();', ' ', ' // otherwise, extend the sphere if needed', ' } else {', ' myBoundingSphere.swallow (keyToAdd);', ' }', ' ', ' // add the data', ' myData.add (new DataWrapper <KeyType, DataType> (keyToAdd, dataToAdd));', ' }', ' ', ' // we want to potentially allow many implementations of the splitting lalgorithm', ' abstract public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // this is here so the actual splitting algorithn can access the list and change the sphere', ' protected ArrayList <DataWrapper <KeyType, DataType>> getList () {', ' return myData;', ' }', ' ', ' // this is here so the splitting algorithm can modify the list and the sphere', ' protected void replaceGuts (AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> withMe) {', ' myData = withMe.myData;', ' myBoundingSphere = withMe.myBoundingSphere;', ' }', ' ', '}', '', '// this is a particular implementation of the metric data list that uses a simple quadratic clustering', '// algorithm to perform a list split. It picks two "seeds" (the most distant objects) and then repeatedly', '// adds to the two new lists by choosing the objects closest to the seeds', 'class ChrisMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> extends AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> {', '', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo () {', ' ', ' // first, we need to find the two most distant points in the list', ' ArrayList <DataWrapper <KeyType, DataType>> myData = getList ();', ' int bestI = 0, bestJ = 0;', ' double maxDist = -1.0;', ' for (int i = 0; i < myData.size (); i++) {', ' for (int j = i + 1; j < myData.size (); j++) {', ' ', ' // get the two keys', ' DataWrapper <KeyType, DataType> pointOne = myData.get (i);', ' DataWrapper <KeyType, DataType> pointTwo = myData.get (j);', ' ', ' // find the difference between them', ' double curDist = pointOne.getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', '', ' // see if it is the biggest', ' if (curDist > maxDist) {', ' maxDist = curDist;', ' bestI = i;', ' bestJ = j;', ' }', ' }', ' }', ' ', ' // now, we have the best two points; those are seeds for the clustering', ' DataWrapper <KeyType, DataType> pointOne = myData.remove (bestI);', ' DataWrapper <KeyType, DataType> pointTwo = myData.remove (bestJ - 1);', ' ', ' // these are the two new lists', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listOne = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listTwo = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' ', ' // put the two seeds in', ' listOne.add (pointOne.getKey (), pointOne.getData ());', ' listTwo.add (pointTwo.getKey (), pointTwo.getData ());', ' ', ' // and add everyone else in', ' while (myData.size () != 0) {', ' ', ' // find the one closest to the first seed', ' int bestIndex = 0;', ' double bestDist = 9e99;', ' ', ' // loop thru all of the candidate data objects', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listOne.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' ', ' // break if no more data', ' if (myData.size () == 0)', ' break;', ' ', ' // loop thru all of the candidate data objects', ' bestDist = 9e99;', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listTwo.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' }', ' ', ' // now we replace our own guts with the first list', ' replaceGuts (listOne);', ' ', ' // and return the other list', ' return listTwo;', ' }', '}', '', 'interface IMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> {', ' ', ' // add a new pair to the list', ' public void add (KeyType keyToAdd, DataType dataToAdd);', ' ', ' // replace a key at the indicated position', ' public void replaceKey (int pos, KeyType keyToAdd);', ' ', ' // get the key, data pair that resides at a particular position', ' public DataWrapper <KeyType, DataType> get (int pos);', ' ', ' // return the number of items in the list', ' public int size ();', ' ', ' // split the list in two, using some clutering algorithm', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // get a sphere that totally bounds all of the objects in the list', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class MTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public MTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class SCMTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public SCMTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', '', 'public class MTreeTester extends TestCase {', ' ', ' // compare two lists of strings to see if the contents are the same', ' private boolean compareStringSets (ArrayList <String> setOne, ArrayList <String> setTwo) {', ' ', ' // sort the sets and make sure they are the same', ' boolean returnVal = true;', ' if (setOne.size () == setTwo.size ()) {', ' Collections.sort (setOne);', ' Collections.sort (setTwo);', ' for (int i = 0; i < setOne.size (); i++) {', ' if (!setOne.get (i).equals (setTwo.get (i))) {', ' returnVal = false;', ' break; ', ' }', ' }', ' } else {', ' returnVal = false;', ' }', ' ', ' // print out the result', ' System.out.println ("**** Expected:");', ' for (int i = 0; i < setOne.size (); i++) {', ' System.out.format (setOne.get (i) + " ");', ' }', ' System.out.println ("\\n**** Got:");', ' for (int i = 0; i < setTwo.size (); i++) {', ' System.out.format (setTwo.get (i) + " ");', ' }', ' System.out.println ("");', ' ', ' return returnVal;', ' }', ' ', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST SIMPLE ONE DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testOneDimRangeQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.find (query, expectedQuerySize / 2);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.find (query, expectedQuerySize / 2);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (numPoints);', ' result1 = myTree.find (query, expectedQuerySize);', ' result2 = hisTree.find (query, expectedQuerySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // like the last one, but runs a top k', ' private void testOneDimTopKQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (167);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.findKClosest (query, querySize);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (0);', ' result1 = myTree.findKClosest (query, querySize);', ' result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST MULTI-DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimRangeQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' double dist1 = 0;', ' double dist2 = 0;', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' dist1 = Math.sqrt (numDims) * expectedQuerySize / 2.0;', ' dist2 = Math.sqrt (numDims) * expectedQuerySize;', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' // do a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, (int) expectedQuerySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = myTree.findKClosest (query2, (int) expectedQuerySize);', ' ', ' // find the distance to the furthest point in both cases', ' for (int i = 0; i < (int) expectedQuerySize; i++) {', ' double newDist = result1.get (i).getKey ().getDistance (query1);', ' if (newDist > dist1)', ' dist1 = newDist;', ' newDist = result2.get (i).getKey ().getDistance (query2);', ' if (newDist > dist2)', ' dist2 = newDist;', ' }', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.find (query1, dist1);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.find (query1, dist1);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.find (query2, dist2);', ' result2 = hisTree.find (query2, dist2);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimTopKQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, querySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.findKClosest (query1, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.findKClosest (query2, querySize);', ' result2 = hisTree.findKClosest (query2, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' ', ' /**', ' * "TIER 1" TESTS', ' * NONE OF THESE REQUIRE ANY SPLITS', ' */', ' public void testEasy1() {', ' testOneDimRangeQuery (true, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy2() {', ' testOneDimRangeQuery (false, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy3() {', ' testOneDimRangeQuery (true, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy4() {', ' testOneDimRangeQuery (false, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy5() {', ' testMultiDimRangeQuery (true, 1, 5, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy6() {', ' testMultiDimRangeQuery (false, 1, 10, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy7() {', ' testMultiDimRangeQuery (true, 1, 5, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy8() {', ' testMultiDimRangeQuery (false, 1, 15, 10000, 10000, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 2" TESTS', ' * NONE OF THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testMod1() {', ' testOneDimRangeQuery (true, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod2() {', ' testOneDimRangeQuery (false, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod3() {', ' testOneDimRangeQuery (true, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod4() {', ' testOneDimRangeQuery (false, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod5() {', ' testMultiDimRangeQuery (true, 2, 5, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod6() {', ' testMultiDimRangeQuery (false, 2, 10, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod7() {', ' testMultiDimRangeQuery (true, 2, 5, 10000, 100, 1000, 10);', ' }', ' ', ' public void testMod8() {', ' testMultiDimRangeQuery (false, 2, 15, 10000, 100, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 3" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testHard1() {', ' testOneDimRangeQuery (true, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard2() {', ' testOneDimRangeQuery (false, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard3() {', ' testOneDimRangeQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard4() {', ' testOneDimRangeQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard5() {', ' testMultiDimRangeQuery (true, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard6() {', ' testMultiDimRangeQuery (false, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard7() {', ' testMultiDimRangeQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard8() {', ' testMultiDimRangeQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', ' ', ' /**', ' * "TIER 4" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE AND THEY TEST THE TOPK FUNCTIONALITY', ' */', ' ', ' public void testTopK1() {', ' testOneDimTopKQuery (true, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK2() {', ' testOneDimTopKQuery (false, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK3() {', ' testOneDimTopKQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK4() {', ' testOneDimTopKQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK5() {', ' testMultiDimTopKQuery (true, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK6() {', ' testMultiDimTopKQuery (false, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK7() {', ' testMultiDimTopKQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK8() {', ' testMultiDimTopKQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', '}'] | [] | Global_Variable 'center' used at line 285 is defined at line 265 and has a Medium-Range dependency.
Variable 'me' used at line 285 is defined at line 284 and has a Short-Range dependency.
Global_Variable 'radius' used at line 285 is defined at line 266 and has a Medium-Range dependency. | {} | {'Global_Variable Medium-Range': 2, 'Variable Short-Range': 1} |
infilling_java | MTreeTester | 290 | 291 | ['import junit.framework.TestCase;', 'import java.util.ArrayList;', 'import java.util.Random;', 'import java.util.Collections;', '', '// this is a map from a set of keys of type PointInMetricSpace to a', '// set of data of type DataType', 'interface IMTree <Key extends IPointInMetricSpace <Key>, Data> {', ' ', ' // insert a new key/data pair into the map', ' void insert (Key keyToAdd, Data dataToAdd);', ' ', ' // find all of the key/data pairs in the map that fall within a', ' // particular distance of query point if no results are found, then', ' // an empty array is returned (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> find (Key query, double distance);', ' ', ' // find the k closest key/data pairs in the map to a particular', ' // query point ', ' //', ' // if the number of points in the map is less than k, then the', ' // returned list will have less than k pairs in it', ' //', ' // if the number of points is zero, then an empty array is returned', ' // (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> findKClosest (Key query, int k);', ' ', ' // returns the number of nodes that exist on a path from root to leaf in the tree...', ' // whtever the details of the implementation are, a tree with a single leaf node should return 1, and a tree', ' // with more than one lead node should return at least two (since it must have at least one internal node).', ' public int depth ();', ' ', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', '', 'interface IDoubleVector {', '', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '', '// this correponds to some geometric object in a metric space; the object is built out of', '// one or more points of type PointInMetricSpace', 'interface IObjectInMetricSpaceABCD <PointInMetricSpace extends IPointInMetricSpace<PointInMetricSpace>> {', ' ', ' // get the maximum distance from some point on the shape to a particular point in the metric space', ' double maxDistanceTo (PointInMetricSpace checkMe);', ' ', ' // return some arbitrary point on the interior of the geometric object', ' PointInMetricSpace getPointInInterior ();', '}', '', '', '// this interface corresponds to a point in some metric space', 'interface IPointInMetricSpace <PointInMetricSpace> {', ' ', ' // get the distance to another point', ' // ', ' // for this to work in an M-Tree, distances should be "metric" and', ' // obey the triangle inequality', ' double getDistance (PointInMetricSpace toMe);', '}', '', '// this is the basic node type in the structure', 'interface IMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> {', ' ', ' // insert a new key/data pair into the structure. The return value is a new MTreeNode if there was', ' // a split in response to the insertion, or a null if there was no split', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd);', ' ', ' // find all of the key/data pairs in the structure that fall within a particular query sphere', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query); ', ' ', ' // find the set of items closest to the given query point', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ);', ' ', ' // returns a sphere that totally encompasses everything in the node and its subtree', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', ' ', ' // returns the depth', ' public int depth ();', '}', '', '// this is a point in a particular metric space', 'class PointABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the point', ' private PointInMetricSpace me;', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return me; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return checkMe.getDistance (me); ', ' }', ' ', ' // contruct a point', ' public PointABCD (PointInMetricSpace useMe) {', ' me = useMe; ', ' }', '}', '', 'class PQueueABCD <PointInMetricSpace, DataType> {', ' ', ' // this is an object in the queue', ' private class Wrapper {', ' DataWrapper <PointInMetricSpace, DataType> myData;', ' double distance;', ' }', ' ', ' // this is the actual queue', ' ArrayList <Wrapper> myList;', ' ', ' // this is the largest distance value currently in the queue', ' double large;', ' ', ' // this is the max number of objects', ' int maxCount;', ' ', ' // create a priority queue with the speced number of slots', ' PQueueABCD (int maxCountIn) {', ' maxCount = maxCountIn;', ' myList = new ArrayList <Wrapper> ();', ' large = 9e99;', ' }', ' ', ' // get the largest distance in the queue', ' double getDist () {', ' return large;', ' }', ' ', ' // add a new object to the queue... the insertion is ignored if the distance value', ' // exceeds the largest that is in the queue and the queue is already full', ' void insert (PointInMetricSpace key, DataType data, double distance) {', ' ', ' // if we are full, remove the one with the largest distance', ' if (myList.size () == maxCount && distance < large) {', ' ', ' int badIndex = 0;', ' double maxDist = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > maxDist) {', ' maxDist = myList.get (i).distance;', ' badIndex = i;', ' }', ' }', ' ', ' myList.remove (badIndex);', ' }', ' ', ' // see if there is room', ' if (myList.size () < maxCount) {', ' ', ' // add it ', ' Wrapper newOne = new Wrapper ();', ' newOne.myData = new DataWrapper <PointInMetricSpace, DataType> (key, data);', ' newOne.distance = distance;', ' myList.add (newOne); ', ' }', ' ', ' // if we are full, reset the max distance', ' if (myList.size () == maxCount) {', ' large = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > large) {', ' large = myList.get (i).distance;', ' }', ' }', ' }', ' ', ' }', ' ', ' // extracts the contents of the queue', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> done () {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' for (int i = 0; i < myList.size (); i++) {', ' returnVal.add (myList.get (i).myData); ', ' }', ' ', ' return returnVal;', ' }', ' ', '}', '', '// this is a sphere in a particular metric space', 'class SphereABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the center of the sphere and its radius', ' private PointInMetricSpace center;', ' private double radius;', ' ', ' // build a sphere out of its center and its radius', ' public SphereABCD (PointInMetricSpace centerIn, double radiusIn) {', ' center = centerIn;', ' radius = radiusIn;', ' }', ' ', ' // increase the size of the sphere so it contains the object swallowMe', ' public void swallow (IObjectInMetricSpaceABCD <PointInMetricSpace> swallowMe) {', ' ', ' // see if we need to increase the radius to swallow this guy', ' double dist = swallowMe.maxDistanceTo (center);', ' if (dist > radius)', ' radius = dist;', ' }', ' ', ' // check to see if a sphere intersects another sphere', ' public boolean intersects (SphereABCD <PointInMetricSpace> me) {', ' return (me.center.getDistance (center) <= me.radius + radius);', ' }', ' ', ' // check to see if the sphere contains a point', ' public boolean contains (PointInMetricSpace checkMe) {'] | [' return (checkMe.getDistance (center) <= radius);', ' }'] | [' ', ' public PointInMetricSpace getPointInInterior () {', ' return center; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return radius + checkMe.getDistance (center); ', ' }', '}', '', '', '', 'class OneDimPoint implements IPointInMetricSpace <OneDimPoint> {', ' ', ' // this is the actual double', ' Double value;', ' ', ' // construct this out of a double value', ' public OneDimPoint (double makeFromMe) {', ' value = new Double (makeFromMe);', ' }', ' ', ' // get the distance to another point', ' public double getDistance (OneDimPoint toMe) {', ' if (value > toMe.value)', ' return value - toMe.value;', ' else', ' return toMe.value - value;', ' }', ' ', '}', '', 'class MultiDimPoint implements IPointInMetricSpace <MultiDimPoint> {', ' ', ' // this is the point in a multidimensional space', ' IDoubleVector me;', ' ', ' // make this out of an IDoubleVector', ' public MultiDimPoint (IDoubleVector useMe) {', ' me = useMe;', ' }', ' ', ' // get the Euclidean distance to another point', ' public double getDistance (MultiDimPoint toMe) {', ' double distance = 0.0;', ' try {', ' for (int i = 0; i < me.getLength (); i++) {', ' double diff = me.getItem (i) - toMe.me.getItem (i);', ' diff *= diff;', ' distance += diff;', ' }', ' } catch (OutOfBoundsException e) {', ' throw new IndexOutOfBoundsException ("Can\'t compare two MultiDimPoint objects with different dimensionality!"); ', ' }', ' return Math.sqrt(distance);', ' }', ' ', '}', '// this is a leaf node', 'class LeafMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements ', ' IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myData;', ' ', ' // contructor that takes a data list and builds a node out of it', ' private LeafMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myDataIn) {', ' myData = myDataIn; ', ' }', ' ', ' // constructor that creates an empty node', ' public LeafMTreeNodeABCD () {', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> (); ', ' }', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // just add in the new data', ' myData.add (new PointABCD <PointInMetricSpace> (keyToAdd), dataToAdd);', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> newOne = myData.splitInTwo ();', ' LeafMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' myQ.insert (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData (), ', ' query.getDistance (myData.get (i).getKey ().getPointInInterior ()));', ' }', ' }', ' }', ' ', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' returnVal.add (new DataWrapper <PointInMetricSpace, DataType> (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData ()));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return 1; ', ' }', '', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', '// this silly little class is just a wrapper for a key, data pair', 'class DataWrapper <Key, Data> {', ' ', ' Key key;', ' Data data;', ' ', ' public DataWrapper (Key keyIn, Data dataIn) {', ' key = keyIn;', ' data = dataIn;', ' }', ' ', ' public Key getKey () {', ' return key;', ' }', ' ', ' public Data getData () {', ' return data;', ' }', '}', '', '', '// this is an internal node', 'class InternalMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType>', ' implements IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> myData;', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' // this constructs a new internal node that holds precisely the two nodes that are passed in', ' public InternalMTreeNodeABCD (IMTreeNodeABCD <PointInMetricSpace, DataType> refOne,', ' IMTreeNodeABCD <PointInMetricSpace, DataType> refTwo) {', ' ', ' // create a necw list and add the two guys in', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> ();', ' myData.add (refOne.getBoundingSphere (), refOne);', ' myData.add (refTwo.getBoundingSphere (), refTwo);', ' }', ' ', ' // this constructs a new node that holds the list of data that we were passed in', ' public InternalMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> useMe) {', ' myData = useMe; ', ' }', ' ', ' // from the interface', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // find the best child; this is the one we are closest to', ' double bestDist = 9e99;', ' int bestIndex = 0;', ' for (int i = 0; i < myData.size (); i++) {', ' ', ' double newDist = myData.get (i).getKey ().getPointInInterior ().getDistance (keyToAdd);', ' if (newDist < bestDist) {', ' bestDist = newDist;', ' bestIndex = i;', ' }', ' }', ' ', ' // do the recursive insert', ' IMTreeNodeABCD <PointInMetricSpace, DataType> newRef = myData.get (bestIndex).getData ().insert (keyToAdd, dataToAdd);', ' ', ' // if we got something back, then there was a split, so add the new node into our list', ' if (newRef != null) {', ' myData.add (newRef.getBoundingSphere (), newRef);', ' }', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> newOne = myData.splitInTwo ();', ' InternalMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.intersects (myData.get (i).getKey ())) {', ' myData.get (i).getData ().findKClosest (query, myQ);', ' }', ' }', ' }', ' ', ' // from the interface', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.intersects (myData.get (i).getKey ())) {', ' returnVal.addAll (myData.get (i).getData ().find (query));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return myData.get (0).getData ().depth () + 1; ', ' }', ' ', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', 'abstract class AMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> implements IMetricDataListABCD <PointInMetricSpace,KeyType, DataType> {', '', ' // this is the data that is actually stored in the list', ' private ArrayList <DataWrapper <KeyType, DataType>> myData;', ' ', ' // this is the sphere that bounds everything in the list', ' private SphereABCD <PointInMetricSpace> myBoundingSphere;', ' ', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myBoundingSphere; ', ' }', ' ', ' public int size () {', ' if (myData != null)', ' return myData.size (); ', ' else', ' return 0;', ' }', ' ', ' public DataWrapper <KeyType, DataType> get (int pos) {', ' return myData.get (pos);', ' }', ' ', ' public void replaceKey (int pos, KeyType keyToAdd) {', ' DataWrapper <KeyType, DataType> temp = myData.remove (pos);', ' DataWrapper <KeyType, DataType> newOne = new DataWrapper <KeyType, DataType> (keyToAdd, temp.getData ());', ' myData.add (pos, newOne);', ' }', ' ', ' public void add (KeyType keyToAdd, DataType dataToAdd) {', ' ', ' // if this is the first add, then set everyone up', ' if (myData == null) {', ' PointInMetricSpace myCentroid = keyToAdd.getPointInInterior ();', ' myBoundingSphere = new SphereABCD <PointInMetricSpace> (myCentroid, keyToAdd.maxDistanceTo (myCentroid));', ' myData = new ArrayList <DataWrapper <KeyType, DataType>> ();', ' ', ' // otherwise, extend the sphere if needed', ' } else {', ' myBoundingSphere.swallow (keyToAdd);', ' }', ' ', ' // add the data', ' myData.add (new DataWrapper <KeyType, DataType> (keyToAdd, dataToAdd));', ' }', ' ', ' // we want to potentially allow many implementations of the splitting lalgorithm', ' abstract public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // this is here so the actual splitting algorithn can access the list and change the sphere', ' protected ArrayList <DataWrapper <KeyType, DataType>> getList () {', ' return myData;', ' }', ' ', ' // this is here so the splitting algorithm can modify the list and the sphere', ' protected void replaceGuts (AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> withMe) {', ' myData = withMe.myData;', ' myBoundingSphere = withMe.myBoundingSphere;', ' }', ' ', '}', '', '// this is a particular implementation of the metric data list that uses a simple quadratic clustering', '// algorithm to perform a list split. It picks two "seeds" (the most distant objects) and then repeatedly', '// adds to the two new lists by choosing the objects closest to the seeds', 'class ChrisMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> extends AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> {', '', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo () {', ' ', ' // first, we need to find the two most distant points in the list', ' ArrayList <DataWrapper <KeyType, DataType>> myData = getList ();', ' int bestI = 0, bestJ = 0;', ' double maxDist = -1.0;', ' for (int i = 0; i < myData.size (); i++) {', ' for (int j = i + 1; j < myData.size (); j++) {', ' ', ' // get the two keys', ' DataWrapper <KeyType, DataType> pointOne = myData.get (i);', ' DataWrapper <KeyType, DataType> pointTwo = myData.get (j);', ' ', ' // find the difference between them', ' double curDist = pointOne.getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', '', ' // see if it is the biggest', ' if (curDist > maxDist) {', ' maxDist = curDist;', ' bestI = i;', ' bestJ = j;', ' }', ' }', ' }', ' ', ' // now, we have the best two points; those are seeds for the clustering', ' DataWrapper <KeyType, DataType> pointOne = myData.remove (bestI);', ' DataWrapper <KeyType, DataType> pointTwo = myData.remove (bestJ - 1);', ' ', ' // these are the two new lists', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listOne = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listTwo = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' ', ' // put the two seeds in', ' listOne.add (pointOne.getKey (), pointOne.getData ());', ' listTwo.add (pointTwo.getKey (), pointTwo.getData ());', ' ', ' // and add everyone else in', ' while (myData.size () != 0) {', ' ', ' // find the one closest to the first seed', ' int bestIndex = 0;', ' double bestDist = 9e99;', ' ', ' // loop thru all of the candidate data objects', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listOne.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' ', ' // break if no more data', ' if (myData.size () == 0)', ' break;', ' ', ' // loop thru all of the candidate data objects', ' bestDist = 9e99;', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listTwo.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' }', ' ', ' // now we replace our own guts with the first list', ' replaceGuts (listOne);', ' ', ' // and return the other list', ' return listTwo;', ' }', '}', '', 'interface IMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> {', ' ', ' // add a new pair to the list', ' public void add (KeyType keyToAdd, DataType dataToAdd);', ' ', ' // replace a key at the indicated position', ' public void replaceKey (int pos, KeyType keyToAdd);', ' ', ' // get the key, data pair that resides at a particular position', ' public DataWrapper <KeyType, DataType> get (int pos);', ' ', ' // return the number of items in the list', ' public int size ();', ' ', ' // split the list in two, using some clutering algorithm', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // get a sphere that totally bounds all of the objects in the list', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class MTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public MTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class SCMTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public SCMTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', '', 'public class MTreeTester extends TestCase {', ' ', ' // compare two lists of strings to see if the contents are the same', ' private boolean compareStringSets (ArrayList <String> setOne, ArrayList <String> setTwo) {', ' ', ' // sort the sets and make sure they are the same', ' boolean returnVal = true;', ' if (setOne.size () == setTwo.size ()) {', ' Collections.sort (setOne);', ' Collections.sort (setTwo);', ' for (int i = 0; i < setOne.size (); i++) {', ' if (!setOne.get (i).equals (setTwo.get (i))) {', ' returnVal = false;', ' break; ', ' }', ' }', ' } else {', ' returnVal = false;', ' }', ' ', ' // print out the result', ' System.out.println ("**** Expected:");', ' for (int i = 0; i < setOne.size (); i++) {', ' System.out.format (setOne.get (i) + " ");', ' }', ' System.out.println ("\\n**** Got:");', ' for (int i = 0; i < setTwo.size (); i++) {', ' System.out.format (setTwo.get (i) + " ");', ' }', ' System.out.println ("");', ' ', ' return returnVal;', ' }', ' ', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST SIMPLE ONE DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testOneDimRangeQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.find (query, expectedQuerySize / 2);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.find (query, expectedQuerySize / 2);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (numPoints);', ' result1 = myTree.find (query, expectedQuerySize);', ' result2 = hisTree.find (query, expectedQuerySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // like the last one, but runs a top k', ' private void testOneDimTopKQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (167);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.findKClosest (query, querySize);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (0);', ' result1 = myTree.findKClosest (query, querySize);', ' result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST MULTI-DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimRangeQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' double dist1 = 0;', ' double dist2 = 0;', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' dist1 = Math.sqrt (numDims) * expectedQuerySize / 2.0;', ' dist2 = Math.sqrt (numDims) * expectedQuerySize;', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' // do a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, (int) expectedQuerySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = myTree.findKClosest (query2, (int) expectedQuerySize);', ' ', ' // find the distance to the furthest point in both cases', ' for (int i = 0; i < (int) expectedQuerySize; i++) {', ' double newDist = result1.get (i).getKey ().getDistance (query1);', ' if (newDist > dist1)', ' dist1 = newDist;', ' newDist = result2.get (i).getKey ().getDistance (query2);', ' if (newDist > dist2)', ' dist2 = newDist;', ' }', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.find (query1, dist1);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.find (query1, dist1);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.find (query2, dist2);', ' result2 = hisTree.find (query2, dist2);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimTopKQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, querySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.findKClosest (query1, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.findKClosest (query2, querySize);', ' result2 = hisTree.findKClosest (query2, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' ', ' /**', ' * "TIER 1" TESTS', ' * NONE OF THESE REQUIRE ANY SPLITS', ' */', ' public void testEasy1() {', ' testOneDimRangeQuery (true, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy2() {', ' testOneDimRangeQuery (false, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy3() {', ' testOneDimRangeQuery (true, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy4() {', ' testOneDimRangeQuery (false, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy5() {', ' testMultiDimRangeQuery (true, 1, 5, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy6() {', ' testMultiDimRangeQuery (false, 1, 10, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy7() {', ' testMultiDimRangeQuery (true, 1, 5, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy8() {', ' testMultiDimRangeQuery (false, 1, 15, 10000, 10000, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 2" TESTS', ' * NONE OF THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testMod1() {', ' testOneDimRangeQuery (true, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod2() {', ' testOneDimRangeQuery (false, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod3() {', ' testOneDimRangeQuery (true, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod4() {', ' testOneDimRangeQuery (false, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod5() {', ' testMultiDimRangeQuery (true, 2, 5, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod6() {', ' testMultiDimRangeQuery (false, 2, 10, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod7() {', ' testMultiDimRangeQuery (true, 2, 5, 10000, 100, 1000, 10);', ' }', ' ', ' public void testMod8() {', ' testMultiDimRangeQuery (false, 2, 15, 10000, 100, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 3" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testHard1() {', ' testOneDimRangeQuery (true, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard2() {', ' testOneDimRangeQuery (false, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard3() {', ' testOneDimRangeQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard4() {', ' testOneDimRangeQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard5() {', ' testMultiDimRangeQuery (true, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard6() {', ' testMultiDimRangeQuery (false, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard7() {', ' testMultiDimRangeQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard8() {', ' testMultiDimRangeQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', ' ', ' /**', ' * "TIER 4" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE AND THEY TEST THE TOPK FUNCTIONALITY', ' */', ' ', ' public void testTopK1() {', ' testOneDimTopKQuery (true, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK2() {', ' testOneDimTopKQuery (false, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK3() {', ' testOneDimTopKQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK4() {', ' testOneDimTopKQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK5() {', ' testMultiDimTopKQuery (true, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK6() {', ' testMultiDimTopKQuery (false, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK7() {', ' testMultiDimTopKQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK8() {', ' testMultiDimTopKQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', '}'] | [] | Variable 'checkMe' used at line 290 is defined at line 289 and has a Short-Range dependency.
Global_Variable 'center' used at line 290 is defined at line 265 and has a Medium-Range dependency.
Global_Variable 'radius' used at line 290 is defined at line 266 and has a Medium-Range dependency. | {} | {'Variable Short-Range': 1, 'Global_Variable Medium-Range': 2} |
infilling_java | MTreeTester | 311 | 312 | ['import junit.framework.TestCase;', 'import java.util.ArrayList;', 'import java.util.Random;', 'import java.util.Collections;', '', '// this is a map from a set of keys of type PointInMetricSpace to a', '// set of data of type DataType', 'interface IMTree <Key extends IPointInMetricSpace <Key>, Data> {', ' ', ' // insert a new key/data pair into the map', ' void insert (Key keyToAdd, Data dataToAdd);', ' ', ' // find all of the key/data pairs in the map that fall within a', ' // particular distance of query point if no results are found, then', ' // an empty array is returned (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> find (Key query, double distance);', ' ', ' // find the k closest key/data pairs in the map to a particular', ' // query point ', ' //', ' // if the number of points in the map is less than k, then the', ' // returned list will have less than k pairs in it', ' //', ' // if the number of points is zero, then an empty array is returned', ' // (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> findKClosest (Key query, int k);', ' ', ' // returns the number of nodes that exist on a path from root to leaf in the tree...', ' // whtever the details of the implementation are, a tree with a single leaf node should return 1, and a tree', ' // with more than one lead node should return at least two (since it must have at least one internal node).', ' public int depth ();', ' ', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', '', 'interface IDoubleVector {', '', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '', '// this correponds to some geometric object in a metric space; the object is built out of', '// one or more points of type PointInMetricSpace', 'interface IObjectInMetricSpaceABCD <PointInMetricSpace extends IPointInMetricSpace<PointInMetricSpace>> {', ' ', ' // get the maximum distance from some point on the shape to a particular point in the metric space', ' double maxDistanceTo (PointInMetricSpace checkMe);', ' ', ' // return some arbitrary point on the interior of the geometric object', ' PointInMetricSpace getPointInInterior ();', '}', '', '', '// this interface corresponds to a point in some metric space', 'interface IPointInMetricSpace <PointInMetricSpace> {', ' ', ' // get the distance to another point', ' // ', ' // for this to work in an M-Tree, distances should be "metric" and', ' // obey the triangle inequality', ' double getDistance (PointInMetricSpace toMe);', '}', '', '// this is the basic node type in the structure', 'interface IMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> {', ' ', ' // insert a new key/data pair into the structure. The return value is a new MTreeNode if there was', ' // a split in response to the insertion, or a null if there was no split', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd);', ' ', ' // find all of the key/data pairs in the structure that fall within a particular query sphere', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query); ', ' ', ' // find the set of items closest to the given query point', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ);', ' ', ' // returns a sphere that totally encompasses everything in the node and its subtree', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', ' ', ' // returns the depth', ' public int depth ();', '}', '', '// this is a point in a particular metric space', 'class PointABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the point', ' private PointInMetricSpace me;', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return me; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return checkMe.getDistance (me); ', ' }', ' ', ' // contruct a point', ' public PointABCD (PointInMetricSpace useMe) {', ' me = useMe; ', ' }', '}', '', 'class PQueueABCD <PointInMetricSpace, DataType> {', ' ', ' // this is an object in the queue', ' private class Wrapper {', ' DataWrapper <PointInMetricSpace, DataType> myData;', ' double distance;', ' }', ' ', ' // this is the actual queue', ' ArrayList <Wrapper> myList;', ' ', ' // this is the largest distance value currently in the queue', ' double large;', ' ', ' // this is the max number of objects', ' int maxCount;', ' ', ' // create a priority queue with the speced number of slots', ' PQueueABCD (int maxCountIn) {', ' maxCount = maxCountIn;', ' myList = new ArrayList <Wrapper> ();', ' large = 9e99;', ' }', ' ', ' // get the largest distance in the queue', ' double getDist () {', ' return large;', ' }', ' ', ' // add a new object to the queue... the insertion is ignored if the distance value', ' // exceeds the largest that is in the queue and the queue is already full', ' void insert (PointInMetricSpace key, DataType data, double distance) {', ' ', ' // if we are full, remove the one with the largest distance', ' if (myList.size () == maxCount && distance < large) {', ' ', ' int badIndex = 0;', ' double maxDist = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > maxDist) {', ' maxDist = myList.get (i).distance;', ' badIndex = i;', ' }', ' }', ' ', ' myList.remove (badIndex);', ' }', ' ', ' // see if there is room', ' if (myList.size () < maxCount) {', ' ', ' // add it ', ' Wrapper newOne = new Wrapper ();', ' newOne.myData = new DataWrapper <PointInMetricSpace, DataType> (key, data);', ' newOne.distance = distance;', ' myList.add (newOne); ', ' }', ' ', ' // if we are full, reset the max distance', ' if (myList.size () == maxCount) {', ' large = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > large) {', ' large = myList.get (i).distance;', ' }', ' }', ' }', ' ', ' }', ' ', ' // extracts the contents of the queue', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> done () {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' for (int i = 0; i < myList.size (); i++) {', ' returnVal.add (myList.get (i).myData); ', ' }', ' ', ' return returnVal;', ' }', ' ', '}', '', '// this is a sphere in a particular metric space', 'class SphereABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the center of the sphere and its radius', ' private PointInMetricSpace center;', ' private double radius;', ' ', ' // build a sphere out of its center and its radius', ' public SphereABCD (PointInMetricSpace centerIn, double radiusIn) {', ' center = centerIn;', ' radius = radiusIn;', ' }', ' ', ' // increase the size of the sphere so it contains the object swallowMe', ' public void swallow (IObjectInMetricSpaceABCD <PointInMetricSpace> swallowMe) {', ' ', ' // see if we need to increase the radius to swallow this guy', ' double dist = swallowMe.maxDistanceTo (center);', ' if (dist > radius)', ' radius = dist;', ' }', ' ', ' // check to see if a sphere intersects another sphere', ' public boolean intersects (SphereABCD <PointInMetricSpace> me) {', ' return (me.center.getDistance (center) <= me.radius + radius);', ' }', ' ', ' // check to see if the sphere contains a point', ' public boolean contains (PointInMetricSpace checkMe) {', ' return (checkMe.getDistance (center) <= radius);', ' }', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return center; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return radius + checkMe.getDistance (center); ', ' }', '}', '', '', '', 'class OneDimPoint implements IPointInMetricSpace <OneDimPoint> {', ' ', ' // this is the actual double', ' Double value;', ' ', ' // construct this out of a double value', ' public OneDimPoint (double makeFromMe) {'] | [' value = new Double (makeFromMe);', ' }'] | [' ', ' // get the distance to another point', ' public double getDistance (OneDimPoint toMe) {', ' if (value > toMe.value)', ' return value - toMe.value;', ' else', ' return toMe.value - value;', ' }', ' ', '}', '', 'class MultiDimPoint implements IPointInMetricSpace <MultiDimPoint> {', ' ', ' // this is the point in a multidimensional space', ' IDoubleVector me;', ' ', ' // make this out of an IDoubleVector', ' public MultiDimPoint (IDoubleVector useMe) {', ' me = useMe;', ' }', ' ', ' // get the Euclidean distance to another point', ' public double getDistance (MultiDimPoint toMe) {', ' double distance = 0.0;', ' try {', ' for (int i = 0; i < me.getLength (); i++) {', ' double diff = me.getItem (i) - toMe.me.getItem (i);', ' diff *= diff;', ' distance += diff;', ' }', ' } catch (OutOfBoundsException e) {', ' throw new IndexOutOfBoundsException ("Can\'t compare two MultiDimPoint objects with different dimensionality!"); ', ' }', ' return Math.sqrt(distance);', ' }', ' ', '}', '// this is a leaf node', 'class LeafMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements ', ' IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myData;', ' ', ' // contructor that takes a data list and builds a node out of it', ' private LeafMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myDataIn) {', ' myData = myDataIn; ', ' }', ' ', ' // constructor that creates an empty node', ' public LeafMTreeNodeABCD () {', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> (); ', ' }', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // just add in the new data', ' myData.add (new PointABCD <PointInMetricSpace> (keyToAdd), dataToAdd);', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> newOne = myData.splitInTwo ();', ' LeafMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' myQ.insert (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData (), ', ' query.getDistance (myData.get (i).getKey ().getPointInInterior ()));', ' }', ' }', ' }', ' ', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' returnVal.add (new DataWrapper <PointInMetricSpace, DataType> (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData ()));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return 1; ', ' }', '', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', '// this silly little class is just a wrapper for a key, data pair', 'class DataWrapper <Key, Data> {', ' ', ' Key key;', ' Data data;', ' ', ' public DataWrapper (Key keyIn, Data dataIn) {', ' key = keyIn;', ' data = dataIn;', ' }', ' ', ' public Key getKey () {', ' return key;', ' }', ' ', ' public Data getData () {', ' return data;', ' }', '}', '', '', '// this is an internal node', 'class InternalMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType>', ' implements IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> myData;', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' // this constructs a new internal node that holds precisely the two nodes that are passed in', ' public InternalMTreeNodeABCD (IMTreeNodeABCD <PointInMetricSpace, DataType> refOne,', ' IMTreeNodeABCD <PointInMetricSpace, DataType> refTwo) {', ' ', ' // create a necw list and add the two guys in', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> ();', ' myData.add (refOne.getBoundingSphere (), refOne);', ' myData.add (refTwo.getBoundingSphere (), refTwo);', ' }', ' ', ' // this constructs a new node that holds the list of data that we were passed in', ' public InternalMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> useMe) {', ' myData = useMe; ', ' }', ' ', ' // from the interface', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // find the best child; this is the one we are closest to', ' double bestDist = 9e99;', ' int bestIndex = 0;', ' for (int i = 0; i < myData.size (); i++) {', ' ', ' double newDist = myData.get (i).getKey ().getPointInInterior ().getDistance (keyToAdd);', ' if (newDist < bestDist) {', ' bestDist = newDist;', ' bestIndex = i;', ' }', ' }', ' ', ' // do the recursive insert', ' IMTreeNodeABCD <PointInMetricSpace, DataType> newRef = myData.get (bestIndex).getData ().insert (keyToAdd, dataToAdd);', ' ', ' // if we got something back, then there was a split, so add the new node into our list', ' if (newRef != null) {', ' myData.add (newRef.getBoundingSphere (), newRef);', ' }', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> newOne = myData.splitInTwo ();', ' InternalMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.intersects (myData.get (i).getKey ())) {', ' myData.get (i).getData ().findKClosest (query, myQ);', ' }', ' }', ' }', ' ', ' // from the interface', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.intersects (myData.get (i).getKey ())) {', ' returnVal.addAll (myData.get (i).getData ().find (query));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return myData.get (0).getData ().depth () + 1; ', ' }', ' ', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', 'abstract class AMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> implements IMetricDataListABCD <PointInMetricSpace,KeyType, DataType> {', '', ' // this is the data that is actually stored in the list', ' private ArrayList <DataWrapper <KeyType, DataType>> myData;', ' ', ' // this is the sphere that bounds everything in the list', ' private SphereABCD <PointInMetricSpace> myBoundingSphere;', ' ', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myBoundingSphere; ', ' }', ' ', ' public int size () {', ' if (myData != null)', ' return myData.size (); ', ' else', ' return 0;', ' }', ' ', ' public DataWrapper <KeyType, DataType> get (int pos) {', ' return myData.get (pos);', ' }', ' ', ' public void replaceKey (int pos, KeyType keyToAdd) {', ' DataWrapper <KeyType, DataType> temp = myData.remove (pos);', ' DataWrapper <KeyType, DataType> newOne = new DataWrapper <KeyType, DataType> (keyToAdd, temp.getData ());', ' myData.add (pos, newOne);', ' }', ' ', ' public void add (KeyType keyToAdd, DataType dataToAdd) {', ' ', ' // if this is the first add, then set everyone up', ' if (myData == null) {', ' PointInMetricSpace myCentroid = keyToAdd.getPointInInterior ();', ' myBoundingSphere = new SphereABCD <PointInMetricSpace> (myCentroid, keyToAdd.maxDistanceTo (myCentroid));', ' myData = new ArrayList <DataWrapper <KeyType, DataType>> ();', ' ', ' // otherwise, extend the sphere if needed', ' } else {', ' myBoundingSphere.swallow (keyToAdd);', ' }', ' ', ' // add the data', ' myData.add (new DataWrapper <KeyType, DataType> (keyToAdd, dataToAdd));', ' }', ' ', ' // we want to potentially allow many implementations of the splitting lalgorithm', ' abstract public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // this is here so the actual splitting algorithn can access the list and change the sphere', ' protected ArrayList <DataWrapper <KeyType, DataType>> getList () {', ' return myData;', ' }', ' ', ' // this is here so the splitting algorithm can modify the list and the sphere', ' protected void replaceGuts (AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> withMe) {', ' myData = withMe.myData;', ' myBoundingSphere = withMe.myBoundingSphere;', ' }', ' ', '}', '', '// this is a particular implementation of the metric data list that uses a simple quadratic clustering', '// algorithm to perform a list split. It picks two "seeds" (the most distant objects) and then repeatedly', '// adds to the two new lists by choosing the objects closest to the seeds', 'class ChrisMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> extends AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> {', '', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo () {', ' ', ' // first, we need to find the two most distant points in the list', ' ArrayList <DataWrapper <KeyType, DataType>> myData = getList ();', ' int bestI = 0, bestJ = 0;', ' double maxDist = -1.0;', ' for (int i = 0; i < myData.size (); i++) {', ' for (int j = i + 1; j < myData.size (); j++) {', ' ', ' // get the two keys', ' DataWrapper <KeyType, DataType> pointOne = myData.get (i);', ' DataWrapper <KeyType, DataType> pointTwo = myData.get (j);', ' ', ' // find the difference between them', ' double curDist = pointOne.getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', '', ' // see if it is the biggest', ' if (curDist > maxDist) {', ' maxDist = curDist;', ' bestI = i;', ' bestJ = j;', ' }', ' }', ' }', ' ', ' // now, we have the best two points; those are seeds for the clustering', ' DataWrapper <KeyType, DataType> pointOne = myData.remove (bestI);', ' DataWrapper <KeyType, DataType> pointTwo = myData.remove (bestJ - 1);', ' ', ' // these are the two new lists', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listOne = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listTwo = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' ', ' // put the two seeds in', ' listOne.add (pointOne.getKey (), pointOne.getData ());', ' listTwo.add (pointTwo.getKey (), pointTwo.getData ());', ' ', ' // and add everyone else in', ' while (myData.size () != 0) {', ' ', ' // find the one closest to the first seed', ' int bestIndex = 0;', ' double bestDist = 9e99;', ' ', ' // loop thru all of the candidate data objects', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listOne.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' ', ' // break if no more data', ' if (myData.size () == 0)', ' break;', ' ', ' // loop thru all of the candidate data objects', ' bestDist = 9e99;', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listTwo.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' }', ' ', ' // now we replace our own guts with the first list', ' replaceGuts (listOne);', ' ', ' // and return the other list', ' return listTwo;', ' }', '}', '', 'interface IMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> {', ' ', ' // add a new pair to the list', ' public void add (KeyType keyToAdd, DataType dataToAdd);', ' ', ' // replace a key at the indicated position', ' public void replaceKey (int pos, KeyType keyToAdd);', ' ', ' // get the key, data pair that resides at a particular position', ' public DataWrapper <KeyType, DataType> get (int pos);', ' ', ' // return the number of items in the list', ' public int size ();', ' ', ' // split the list in two, using some clutering algorithm', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // get a sphere that totally bounds all of the objects in the list', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class MTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public MTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class SCMTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public SCMTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', '', 'public class MTreeTester extends TestCase {', ' ', ' // compare two lists of strings to see if the contents are the same', ' private boolean compareStringSets (ArrayList <String> setOne, ArrayList <String> setTwo) {', ' ', ' // sort the sets and make sure they are the same', ' boolean returnVal = true;', ' if (setOne.size () == setTwo.size ()) {', ' Collections.sort (setOne);', ' Collections.sort (setTwo);', ' for (int i = 0; i < setOne.size (); i++) {', ' if (!setOne.get (i).equals (setTwo.get (i))) {', ' returnVal = false;', ' break; ', ' }', ' }', ' } else {', ' returnVal = false;', ' }', ' ', ' // print out the result', ' System.out.println ("**** Expected:");', ' for (int i = 0; i < setOne.size (); i++) {', ' System.out.format (setOne.get (i) + " ");', ' }', ' System.out.println ("\\n**** Got:");', ' for (int i = 0; i < setTwo.size (); i++) {', ' System.out.format (setTwo.get (i) + " ");', ' }', ' System.out.println ("");', ' ', ' return returnVal;', ' }', ' ', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST SIMPLE ONE DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testOneDimRangeQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.find (query, expectedQuerySize / 2);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.find (query, expectedQuerySize / 2);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (numPoints);', ' result1 = myTree.find (query, expectedQuerySize);', ' result2 = hisTree.find (query, expectedQuerySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // like the last one, but runs a top k', ' private void testOneDimTopKQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (167);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.findKClosest (query, querySize);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (0);', ' result1 = myTree.findKClosest (query, querySize);', ' result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST MULTI-DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimRangeQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' double dist1 = 0;', ' double dist2 = 0;', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' dist1 = Math.sqrt (numDims) * expectedQuerySize / 2.0;', ' dist2 = Math.sqrt (numDims) * expectedQuerySize;', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' // do a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, (int) expectedQuerySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = myTree.findKClosest (query2, (int) expectedQuerySize);', ' ', ' // find the distance to the furthest point in both cases', ' for (int i = 0; i < (int) expectedQuerySize; i++) {', ' double newDist = result1.get (i).getKey ().getDistance (query1);', ' if (newDist > dist1)', ' dist1 = newDist;', ' newDist = result2.get (i).getKey ().getDistance (query2);', ' if (newDist > dist2)', ' dist2 = newDist;', ' }', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.find (query1, dist1);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.find (query1, dist1);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.find (query2, dist2);', ' result2 = hisTree.find (query2, dist2);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimTopKQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, querySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.findKClosest (query1, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.findKClosest (query2, querySize);', ' result2 = hisTree.findKClosest (query2, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' ', ' /**', ' * "TIER 1" TESTS', ' * NONE OF THESE REQUIRE ANY SPLITS', ' */', ' public void testEasy1() {', ' testOneDimRangeQuery (true, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy2() {', ' testOneDimRangeQuery (false, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy3() {', ' testOneDimRangeQuery (true, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy4() {', ' testOneDimRangeQuery (false, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy5() {', ' testMultiDimRangeQuery (true, 1, 5, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy6() {', ' testMultiDimRangeQuery (false, 1, 10, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy7() {', ' testMultiDimRangeQuery (true, 1, 5, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy8() {', ' testMultiDimRangeQuery (false, 1, 15, 10000, 10000, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 2" TESTS', ' * NONE OF THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testMod1() {', ' testOneDimRangeQuery (true, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod2() {', ' testOneDimRangeQuery (false, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod3() {', ' testOneDimRangeQuery (true, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod4() {', ' testOneDimRangeQuery (false, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod5() {', ' testMultiDimRangeQuery (true, 2, 5, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod6() {', ' testMultiDimRangeQuery (false, 2, 10, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod7() {', ' testMultiDimRangeQuery (true, 2, 5, 10000, 100, 1000, 10);', ' }', ' ', ' public void testMod8() {', ' testMultiDimRangeQuery (false, 2, 15, 10000, 100, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 3" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testHard1() {', ' testOneDimRangeQuery (true, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard2() {', ' testOneDimRangeQuery (false, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard3() {', ' testOneDimRangeQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard4() {', ' testOneDimRangeQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard5() {', ' testMultiDimRangeQuery (true, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard6() {', ' testMultiDimRangeQuery (false, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard7() {', ' testMultiDimRangeQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard8() {', ' testMultiDimRangeQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', ' ', ' /**', ' * "TIER 4" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE AND THEY TEST THE TOPK FUNCTIONALITY', ' */', ' ', ' public void testTopK1() {', ' testOneDimTopKQuery (true, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK2() {', ' testOneDimTopKQuery (false, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK3() {', ' testOneDimTopKQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK4() {', ' testOneDimTopKQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK5() {', ' testMultiDimTopKQuery (true, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK6() {', ' testMultiDimTopKQuery (false, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK7() {', ' testMultiDimTopKQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK8() {', ' testMultiDimTopKQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', '}'] | [] | Variable 'makeFromMe' used at line 311 is defined at line 310 and has a Short-Range dependency.
Global_Variable 'value' used at line 311 is defined at line 307 and has a Short-Range dependency. | {} | {'Variable Short-Range': 1, 'Global_Variable Short-Range': 1} |
infilling_java | MTreeTester | 317 | 317 | ['import junit.framework.TestCase;', 'import java.util.ArrayList;', 'import java.util.Random;', 'import java.util.Collections;', '', '// this is a map from a set of keys of type PointInMetricSpace to a', '// set of data of type DataType', 'interface IMTree <Key extends IPointInMetricSpace <Key>, Data> {', ' ', ' // insert a new key/data pair into the map', ' void insert (Key keyToAdd, Data dataToAdd);', ' ', ' // find all of the key/data pairs in the map that fall within a', ' // particular distance of query point if no results are found, then', ' // an empty array is returned (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> find (Key query, double distance);', ' ', ' // find the k closest key/data pairs in the map to a particular', ' // query point ', ' //', ' // if the number of points in the map is less than k, then the', ' // returned list will have less than k pairs in it', ' //', ' // if the number of points is zero, then an empty array is returned', ' // (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> findKClosest (Key query, int k);', ' ', ' // returns the number of nodes that exist on a path from root to leaf in the tree...', ' // whtever the details of the implementation are, a tree with a single leaf node should return 1, and a tree', ' // with more than one lead node should return at least two (since it must have at least one internal node).', ' public int depth ();', ' ', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', '', 'interface IDoubleVector {', '', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '', '// this correponds to some geometric object in a metric space; the object is built out of', '// one or more points of type PointInMetricSpace', 'interface IObjectInMetricSpaceABCD <PointInMetricSpace extends IPointInMetricSpace<PointInMetricSpace>> {', ' ', ' // get the maximum distance from some point on the shape to a particular point in the metric space', ' double maxDistanceTo (PointInMetricSpace checkMe);', ' ', ' // return some arbitrary point on the interior of the geometric object', ' PointInMetricSpace getPointInInterior ();', '}', '', '', '// this interface corresponds to a point in some metric space', 'interface IPointInMetricSpace <PointInMetricSpace> {', ' ', ' // get the distance to another point', ' // ', ' // for this to work in an M-Tree, distances should be "metric" and', ' // obey the triangle inequality', ' double getDistance (PointInMetricSpace toMe);', '}', '', '// this is the basic node type in the structure', 'interface IMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> {', ' ', ' // insert a new key/data pair into the structure. The return value is a new MTreeNode if there was', ' // a split in response to the insertion, or a null if there was no split', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd);', ' ', ' // find all of the key/data pairs in the structure that fall within a particular query sphere', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query); ', ' ', ' // find the set of items closest to the given query point', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ);', ' ', ' // returns a sphere that totally encompasses everything in the node and its subtree', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', ' ', ' // returns the depth', ' public int depth ();', '}', '', '// this is a point in a particular metric space', 'class PointABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the point', ' private PointInMetricSpace me;', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return me; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return checkMe.getDistance (me); ', ' }', ' ', ' // contruct a point', ' public PointABCD (PointInMetricSpace useMe) {', ' me = useMe; ', ' }', '}', '', 'class PQueueABCD <PointInMetricSpace, DataType> {', ' ', ' // this is an object in the queue', ' private class Wrapper {', ' DataWrapper <PointInMetricSpace, DataType> myData;', ' double distance;', ' }', ' ', ' // this is the actual queue', ' ArrayList <Wrapper> myList;', ' ', ' // this is the largest distance value currently in the queue', ' double large;', ' ', ' // this is the max number of objects', ' int maxCount;', ' ', ' // create a priority queue with the speced number of slots', ' PQueueABCD (int maxCountIn) {', ' maxCount = maxCountIn;', ' myList = new ArrayList <Wrapper> ();', ' large = 9e99;', ' }', ' ', ' // get the largest distance in the queue', ' double getDist () {', ' return large;', ' }', ' ', ' // add a new object to the queue... the insertion is ignored if the distance value', ' // exceeds the largest that is in the queue and the queue is already full', ' void insert (PointInMetricSpace key, DataType data, double distance) {', ' ', ' // if we are full, remove the one with the largest distance', ' if (myList.size () == maxCount && distance < large) {', ' ', ' int badIndex = 0;', ' double maxDist = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > maxDist) {', ' maxDist = myList.get (i).distance;', ' badIndex = i;', ' }', ' }', ' ', ' myList.remove (badIndex);', ' }', ' ', ' // see if there is room', ' if (myList.size () < maxCount) {', ' ', ' // add it ', ' Wrapper newOne = new Wrapper ();', ' newOne.myData = new DataWrapper <PointInMetricSpace, DataType> (key, data);', ' newOne.distance = distance;', ' myList.add (newOne); ', ' }', ' ', ' // if we are full, reset the max distance', ' if (myList.size () == maxCount) {', ' large = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > large) {', ' large = myList.get (i).distance;', ' }', ' }', ' }', ' ', ' }', ' ', ' // extracts the contents of the queue', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> done () {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' for (int i = 0; i < myList.size (); i++) {', ' returnVal.add (myList.get (i).myData); ', ' }', ' ', ' return returnVal;', ' }', ' ', '}', '', '// this is a sphere in a particular metric space', 'class SphereABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the center of the sphere and its radius', ' private PointInMetricSpace center;', ' private double radius;', ' ', ' // build a sphere out of its center and its radius', ' public SphereABCD (PointInMetricSpace centerIn, double radiusIn) {', ' center = centerIn;', ' radius = radiusIn;', ' }', ' ', ' // increase the size of the sphere so it contains the object swallowMe', ' public void swallow (IObjectInMetricSpaceABCD <PointInMetricSpace> swallowMe) {', ' ', ' // see if we need to increase the radius to swallow this guy', ' double dist = swallowMe.maxDistanceTo (center);', ' if (dist > radius)', ' radius = dist;', ' }', ' ', ' // check to see if a sphere intersects another sphere', ' public boolean intersects (SphereABCD <PointInMetricSpace> me) {', ' return (me.center.getDistance (center) <= me.radius + radius);', ' }', ' ', ' // check to see if the sphere contains a point', ' public boolean contains (PointInMetricSpace checkMe) {', ' return (checkMe.getDistance (center) <= radius);', ' }', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return center; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return radius + checkMe.getDistance (center); ', ' }', '}', '', '', '', 'class OneDimPoint implements IPointInMetricSpace <OneDimPoint> {', ' ', ' // this is the actual double', ' Double value;', ' ', ' // construct this out of a double value', ' public OneDimPoint (double makeFromMe) {', ' value = new Double (makeFromMe);', ' }', ' ', ' // get the distance to another point', ' public double getDistance (OneDimPoint toMe) {', ' if (value > toMe.value)'] | [' return value - toMe.value;'] | [' else', ' return toMe.value - value;', ' }', ' ', '}', '', 'class MultiDimPoint implements IPointInMetricSpace <MultiDimPoint> {', ' ', ' // this is the point in a multidimensional space', ' IDoubleVector me;', ' ', ' // make this out of an IDoubleVector', ' public MultiDimPoint (IDoubleVector useMe) {', ' me = useMe;', ' }', ' ', ' // get the Euclidean distance to another point', ' public double getDistance (MultiDimPoint toMe) {', ' double distance = 0.0;', ' try {', ' for (int i = 0; i < me.getLength (); i++) {', ' double diff = me.getItem (i) - toMe.me.getItem (i);', ' diff *= diff;', ' distance += diff;', ' }', ' } catch (OutOfBoundsException e) {', ' throw new IndexOutOfBoundsException ("Can\'t compare two MultiDimPoint objects with different dimensionality!"); ', ' }', ' return Math.sqrt(distance);', ' }', ' ', '}', '// this is a leaf node', 'class LeafMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements ', ' IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myData;', ' ', ' // contructor that takes a data list and builds a node out of it', ' private LeafMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myDataIn) {', ' myData = myDataIn; ', ' }', ' ', ' // constructor that creates an empty node', ' public LeafMTreeNodeABCD () {', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> (); ', ' }', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // just add in the new data', ' myData.add (new PointABCD <PointInMetricSpace> (keyToAdd), dataToAdd);', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> newOne = myData.splitInTwo ();', ' LeafMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' myQ.insert (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData (), ', ' query.getDistance (myData.get (i).getKey ().getPointInInterior ()));', ' }', ' }', ' }', ' ', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' returnVal.add (new DataWrapper <PointInMetricSpace, DataType> (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData ()));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return 1; ', ' }', '', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', '// this silly little class is just a wrapper for a key, data pair', 'class DataWrapper <Key, Data> {', ' ', ' Key key;', ' Data data;', ' ', ' public DataWrapper (Key keyIn, Data dataIn) {', ' key = keyIn;', ' data = dataIn;', ' }', ' ', ' public Key getKey () {', ' return key;', ' }', ' ', ' public Data getData () {', ' return data;', ' }', '}', '', '', '// this is an internal node', 'class InternalMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType>', ' implements IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> myData;', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' // this constructs a new internal node that holds precisely the two nodes that are passed in', ' public InternalMTreeNodeABCD (IMTreeNodeABCD <PointInMetricSpace, DataType> refOne,', ' IMTreeNodeABCD <PointInMetricSpace, DataType> refTwo) {', ' ', ' // create a necw list and add the two guys in', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> ();', ' myData.add (refOne.getBoundingSphere (), refOne);', ' myData.add (refTwo.getBoundingSphere (), refTwo);', ' }', ' ', ' // this constructs a new node that holds the list of data that we were passed in', ' public InternalMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> useMe) {', ' myData = useMe; ', ' }', ' ', ' // from the interface', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // find the best child; this is the one we are closest to', ' double bestDist = 9e99;', ' int bestIndex = 0;', ' for (int i = 0; i < myData.size (); i++) {', ' ', ' double newDist = myData.get (i).getKey ().getPointInInterior ().getDistance (keyToAdd);', ' if (newDist < bestDist) {', ' bestDist = newDist;', ' bestIndex = i;', ' }', ' }', ' ', ' // do the recursive insert', ' IMTreeNodeABCD <PointInMetricSpace, DataType> newRef = myData.get (bestIndex).getData ().insert (keyToAdd, dataToAdd);', ' ', ' // if we got something back, then there was a split, so add the new node into our list', ' if (newRef != null) {', ' myData.add (newRef.getBoundingSphere (), newRef);', ' }', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> newOne = myData.splitInTwo ();', ' InternalMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.intersects (myData.get (i).getKey ())) {', ' myData.get (i).getData ().findKClosest (query, myQ);', ' }', ' }', ' }', ' ', ' // from the interface', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.intersects (myData.get (i).getKey ())) {', ' returnVal.addAll (myData.get (i).getData ().find (query));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return myData.get (0).getData ().depth () + 1; ', ' }', ' ', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', 'abstract class AMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> implements IMetricDataListABCD <PointInMetricSpace,KeyType, DataType> {', '', ' // this is the data that is actually stored in the list', ' private ArrayList <DataWrapper <KeyType, DataType>> myData;', ' ', ' // this is the sphere that bounds everything in the list', ' private SphereABCD <PointInMetricSpace> myBoundingSphere;', ' ', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myBoundingSphere; ', ' }', ' ', ' public int size () {', ' if (myData != null)', ' return myData.size (); ', ' else', ' return 0;', ' }', ' ', ' public DataWrapper <KeyType, DataType> get (int pos) {', ' return myData.get (pos);', ' }', ' ', ' public void replaceKey (int pos, KeyType keyToAdd) {', ' DataWrapper <KeyType, DataType> temp = myData.remove (pos);', ' DataWrapper <KeyType, DataType> newOne = new DataWrapper <KeyType, DataType> (keyToAdd, temp.getData ());', ' myData.add (pos, newOne);', ' }', ' ', ' public void add (KeyType keyToAdd, DataType dataToAdd) {', ' ', ' // if this is the first add, then set everyone up', ' if (myData == null) {', ' PointInMetricSpace myCentroid = keyToAdd.getPointInInterior ();', ' myBoundingSphere = new SphereABCD <PointInMetricSpace> (myCentroid, keyToAdd.maxDistanceTo (myCentroid));', ' myData = new ArrayList <DataWrapper <KeyType, DataType>> ();', ' ', ' // otherwise, extend the sphere if needed', ' } else {', ' myBoundingSphere.swallow (keyToAdd);', ' }', ' ', ' // add the data', ' myData.add (new DataWrapper <KeyType, DataType> (keyToAdd, dataToAdd));', ' }', ' ', ' // we want to potentially allow many implementations of the splitting lalgorithm', ' abstract public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // this is here so the actual splitting algorithn can access the list and change the sphere', ' protected ArrayList <DataWrapper <KeyType, DataType>> getList () {', ' return myData;', ' }', ' ', ' // this is here so the splitting algorithm can modify the list and the sphere', ' protected void replaceGuts (AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> withMe) {', ' myData = withMe.myData;', ' myBoundingSphere = withMe.myBoundingSphere;', ' }', ' ', '}', '', '// this is a particular implementation of the metric data list that uses a simple quadratic clustering', '// algorithm to perform a list split. It picks two "seeds" (the most distant objects) and then repeatedly', '// adds to the two new lists by choosing the objects closest to the seeds', 'class ChrisMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> extends AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> {', '', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo () {', ' ', ' // first, we need to find the two most distant points in the list', ' ArrayList <DataWrapper <KeyType, DataType>> myData = getList ();', ' int bestI = 0, bestJ = 0;', ' double maxDist = -1.0;', ' for (int i = 0; i < myData.size (); i++) {', ' for (int j = i + 1; j < myData.size (); j++) {', ' ', ' // get the two keys', ' DataWrapper <KeyType, DataType> pointOne = myData.get (i);', ' DataWrapper <KeyType, DataType> pointTwo = myData.get (j);', ' ', ' // find the difference between them', ' double curDist = pointOne.getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', '', ' // see if it is the biggest', ' if (curDist > maxDist) {', ' maxDist = curDist;', ' bestI = i;', ' bestJ = j;', ' }', ' }', ' }', ' ', ' // now, we have the best two points; those are seeds for the clustering', ' DataWrapper <KeyType, DataType> pointOne = myData.remove (bestI);', ' DataWrapper <KeyType, DataType> pointTwo = myData.remove (bestJ - 1);', ' ', ' // these are the two new lists', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listOne = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listTwo = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' ', ' // put the two seeds in', ' listOne.add (pointOne.getKey (), pointOne.getData ());', ' listTwo.add (pointTwo.getKey (), pointTwo.getData ());', ' ', ' // and add everyone else in', ' while (myData.size () != 0) {', ' ', ' // find the one closest to the first seed', ' int bestIndex = 0;', ' double bestDist = 9e99;', ' ', ' // loop thru all of the candidate data objects', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listOne.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' ', ' // break if no more data', ' if (myData.size () == 0)', ' break;', ' ', ' // loop thru all of the candidate data objects', ' bestDist = 9e99;', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listTwo.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' }', ' ', ' // now we replace our own guts with the first list', ' replaceGuts (listOne);', ' ', ' // and return the other list', ' return listTwo;', ' }', '}', '', 'interface IMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> {', ' ', ' // add a new pair to the list', ' public void add (KeyType keyToAdd, DataType dataToAdd);', ' ', ' // replace a key at the indicated position', ' public void replaceKey (int pos, KeyType keyToAdd);', ' ', ' // get the key, data pair that resides at a particular position', ' public DataWrapper <KeyType, DataType> get (int pos);', ' ', ' // return the number of items in the list', ' public int size ();', ' ', ' // split the list in two, using some clutering algorithm', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // get a sphere that totally bounds all of the objects in the list', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class MTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public MTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class SCMTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public SCMTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', '', 'public class MTreeTester extends TestCase {', ' ', ' // compare two lists of strings to see if the contents are the same', ' private boolean compareStringSets (ArrayList <String> setOne, ArrayList <String> setTwo) {', ' ', ' // sort the sets and make sure they are the same', ' boolean returnVal = true;', ' if (setOne.size () == setTwo.size ()) {', ' Collections.sort (setOne);', ' Collections.sort (setTwo);', ' for (int i = 0; i < setOne.size (); i++) {', ' if (!setOne.get (i).equals (setTwo.get (i))) {', ' returnVal = false;', ' break; ', ' }', ' }', ' } else {', ' returnVal = false;', ' }', ' ', ' // print out the result', ' System.out.println ("**** Expected:");', ' for (int i = 0; i < setOne.size (); i++) {', ' System.out.format (setOne.get (i) + " ");', ' }', ' System.out.println ("\\n**** Got:");', ' for (int i = 0; i < setTwo.size (); i++) {', ' System.out.format (setTwo.get (i) + " ");', ' }', ' System.out.println ("");', ' ', ' return returnVal;', ' }', ' ', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST SIMPLE ONE DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testOneDimRangeQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.find (query, expectedQuerySize / 2);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.find (query, expectedQuerySize / 2);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (numPoints);', ' result1 = myTree.find (query, expectedQuerySize);', ' result2 = hisTree.find (query, expectedQuerySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // like the last one, but runs a top k', ' private void testOneDimTopKQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (167);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.findKClosest (query, querySize);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (0);', ' result1 = myTree.findKClosest (query, querySize);', ' result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST MULTI-DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimRangeQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' double dist1 = 0;', ' double dist2 = 0;', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' dist1 = Math.sqrt (numDims) * expectedQuerySize / 2.0;', ' dist2 = Math.sqrt (numDims) * expectedQuerySize;', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' // do a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, (int) expectedQuerySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = myTree.findKClosest (query2, (int) expectedQuerySize);', ' ', ' // find the distance to the furthest point in both cases', ' for (int i = 0; i < (int) expectedQuerySize; i++) {', ' double newDist = result1.get (i).getKey ().getDistance (query1);', ' if (newDist > dist1)', ' dist1 = newDist;', ' newDist = result2.get (i).getKey ().getDistance (query2);', ' if (newDist > dist2)', ' dist2 = newDist;', ' }', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.find (query1, dist1);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.find (query1, dist1);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.find (query2, dist2);', ' result2 = hisTree.find (query2, dist2);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimTopKQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, querySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.findKClosest (query1, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.findKClosest (query2, querySize);', ' result2 = hisTree.findKClosest (query2, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' ', ' /**', ' * "TIER 1" TESTS', ' * NONE OF THESE REQUIRE ANY SPLITS', ' */', ' public void testEasy1() {', ' testOneDimRangeQuery (true, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy2() {', ' testOneDimRangeQuery (false, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy3() {', ' testOneDimRangeQuery (true, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy4() {', ' testOneDimRangeQuery (false, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy5() {', ' testMultiDimRangeQuery (true, 1, 5, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy6() {', ' testMultiDimRangeQuery (false, 1, 10, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy7() {', ' testMultiDimRangeQuery (true, 1, 5, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy8() {', ' testMultiDimRangeQuery (false, 1, 15, 10000, 10000, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 2" TESTS', ' * NONE OF THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testMod1() {', ' testOneDimRangeQuery (true, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod2() {', ' testOneDimRangeQuery (false, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod3() {', ' testOneDimRangeQuery (true, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod4() {', ' testOneDimRangeQuery (false, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod5() {', ' testMultiDimRangeQuery (true, 2, 5, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod6() {', ' testMultiDimRangeQuery (false, 2, 10, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod7() {', ' testMultiDimRangeQuery (true, 2, 5, 10000, 100, 1000, 10);', ' }', ' ', ' public void testMod8() {', ' testMultiDimRangeQuery (false, 2, 15, 10000, 100, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 3" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testHard1() {', ' testOneDimRangeQuery (true, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard2() {', ' testOneDimRangeQuery (false, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard3() {', ' testOneDimRangeQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard4() {', ' testOneDimRangeQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard5() {', ' testMultiDimRangeQuery (true, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard6() {', ' testMultiDimRangeQuery (false, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard7() {', ' testMultiDimRangeQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard8() {', ' testMultiDimRangeQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', ' ', ' /**', ' * "TIER 4" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE AND THEY TEST THE TOPK FUNCTIONALITY', ' */', ' ', ' public void testTopK1() {', ' testOneDimTopKQuery (true, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK2() {', ' testOneDimTopKQuery (false, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK3() {', ' testOneDimTopKQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK4() {', ' testOneDimTopKQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK5() {', ' testMultiDimTopKQuery (true, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK6() {', ' testMultiDimTopKQuery (false, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK7() {', ' testMultiDimTopKQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK8() {', ' testMultiDimTopKQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', '}'] | [{'reason_category': 'If Body', 'usage_line': 317}] | Global_Variable 'value' used at line 317 is defined at line 307 and has a Short-Range dependency.
Variable 'toMe' used at line 317 is defined at line 315 and has a Short-Range dependency. | {'If Body': 1} | {'Global_Variable Short-Range': 1, 'Variable Short-Range': 1} |
infilling_java | MTreeTester | 319 | 319 | ['import junit.framework.TestCase;', 'import java.util.ArrayList;', 'import java.util.Random;', 'import java.util.Collections;', '', '// this is a map from a set of keys of type PointInMetricSpace to a', '// set of data of type DataType', 'interface IMTree <Key extends IPointInMetricSpace <Key>, Data> {', ' ', ' // insert a new key/data pair into the map', ' void insert (Key keyToAdd, Data dataToAdd);', ' ', ' // find all of the key/data pairs in the map that fall within a', ' // particular distance of query point if no results are found, then', ' // an empty array is returned (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> find (Key query, double distance);', ' ', ' // find the k closest key/data pairs in the map to a particular', ' // query point ', ' //', ' // if the number of points in the map is less than k, then the', ' // returned list will have less than k pairs in it', ' //', ' // if the number of points is zero, then an empty array is returned', ' // (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> findKClosest (Key query, int k);', ' ', ' // returns the number of nodes that exist on a path from root to leaf in the tree...', ' // whtever the details of the implementation are, a tree with a single leaf node should return 1, and a tree', ' // with more than one lead node should return at least two (since it must have at least one internal node).', ' public int depth ();', ' ', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', '', 'interface IDoubleVector {', '', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '', '// this correponds to some geometric object in a metric space; the object is built out of', '// one or more points of type PointInMetricSpace', 'interface IObjectInMetricSpaceABCD <PointInMetricSpace extends IPointInMetricSpace<PointInMetricSpace>> {', ' ', ' // get the maximum distance from some point on the shape to a particular point in the metric space', ' double maxDistanceTo (PointInMetricSpace checkMe);', ' ', ' // return some arbitrary point on the interior of the geometric object', ' PointInMetricSpace getPointInInterior ();', '}', '', '', '// this interface corresponds to a point in some metric space', 'interface IPointInMetricSpace <PointInMetricSpace> {', ' ', ' // get the distance to another point', ' // ', ' // for this to work in an M-Tree, distances should be "metric" and', ' // obey the triangle inequality', ' double getDistance (PointInMetricSpace toMe);', '}', '', '// this is the basic node type in the structure', 'interface IMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> {', ' ', ' // insert a new key/data pair into the structure. The return value is a new MTreeNode if there was', ' // a split in response to the insertion, or a null if there was no split', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd);', ' ', ' // find all of the key/data pairs in the structure that fall within a particular query sphere', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query); ', ' ', ' // find the set of items closest to the given query point', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ);', ' ', ' // returns a sphere that totally encompasses everything in the node and its subtree', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', ' ', ' // returns the depth', ' public int depth ();', '}', '', '// this is a point in a particular metric space', 'class PointABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the point', ' private PointInMetricSpace me;', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return me; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return checkMe.getDistance (me); ', ' }', ' ', ' // contruct a point', ' public PointABCD (PointInMetricSpace useMe) {', ' me = useMe; ', ' }', '}', '', 'class PQueueABCD <PointInMetricSpace, DataType> {', ' ', ' // this is an object in the queue', ' private class Wrapper {', ' DataWrapper <PointInMetricSpace, DataType> myData;', ' double distance;', ' }', ' ', ' // this is the actual queue', ' ArrayList <Wrapper> myList;', ' ', ' // this is the largest distance value currently in the queue', ' double large;', ' ', ' // this is the max number of objects', ' int maxCount;', ' ', ' // create a priority queue with the speced number of slots', ' PQueueABCD (int maxCountIn) {', ' maxCount = maxCountIn;', ' myList = new ArrayList <Wrapper> ();', ' large = 9e99;', ' }', ' ', ' // get the largest distance in the queue', ' double getDist () {', ' return large;', ' }', ' ', ' // add a new object to the queue... the insertion is ignored if the distance value', ' // exceeds the largest that is in the queue and the queue is already full', ' void insert (PointInMetricSpace key, DataType data, double distance) {', ' ', ' // if we are full, remove the one with the largest distance', ' if (myList.size () == maxCount && distance < large) {', ' ', ' int badIndex = 0;', ' double maxDist = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > maxDist) {', ' maxDist = myList.get (i).distance;', ' badIndex = i;', ' }', ' }', ' ', ' myList.remove (badIndex);', ' }', ' ', ' // see if there is room', ' if (myList.size () < maxCount) {', ' ', ' // add it ', ' Wrapper newOne = new Wrapper ();', ' newOne.myData = new DataWrapper <PointInMetricSpace, DataType> (key, data);', ' newOne.distance = distance;', ' myList.add (newOne); ', ' }', ' ', ' // if we are full, reset the max distance', ' if (myList.size () == maxCount) {', ' large = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > large) {', ' large = myList.get (i).distance;', ' }', ' }', ' }', ' ', ' }', ' ', ' // extracts the contents of the queue', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> done () {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' for (int i = 0; i < myList.size (); i++) {', ' returnVal.add (myList.get (i).myData); ', ' }', ' ', ' return returnVal;', ' }', ' ', '}', '', '// this is a sphere in a particular metric space', 'class SphereABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the center of the sphere and its radius', ' private PointInMetricSpace center;', ' private double radius;', ' ', ' // build a sphere out of its center and its radius', ' public SphereABCD (PointInMetricSpace centerIn, double radiusIn) {', ' center = centerIn;', ' radius = radiusIn;', ' }', ' ', ' // increase the size of the sphere so it contains the object swallowMe', ' public void swallow (IObjectInMetricSpaceABCD <PointInMetricSpace> swallowMe) {', ' ', ' // see if we need to increase the radius to swallow this guy', ' double dist = swallowMe.maxDistanceTo (center);', ' if (dist > radius)', ' radius = dist;', ' }', ' ', ' // check to see if a sphere intersects another sphere', ' public boolean intersects (SphereABCD <PointInMetricSpace> me) {', ' return (me.center.getDistance (center) <= me.radius + radius);', ' }', ' ', ' // check to see if the sphere contains a point', ' public boolean contains (PointInMetricSpace checkMe) {', ' return (checkMe.getDistance (center) <= radius);', ' }', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return center; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return radius + checkMe.getDistance (center); ', ' }', '}', '', '', '', 'class OneDimPoint implements IPointInMetricSpace <OneDimPoint> {', ' ', ' // this is the actual double', ' Double value;', ' ', ' // construct this out of a double value', ' public OneDimPoint (double makeFromMe) {', ' value = new Double (makeFromMe);', ' }', ' ', ' // get the distance to another point', ' public double getDistance (OneDimPoint toMe) {', ' if (value > toMe.value)', ' return value - toMe.value;', ' else'] | [' return toMe.value - value;'] | [' }', ' ', '}', '', 'class MultiDimPoint implements IPointInMetricSpace <MultiDimPoint> {', ' ', ' // this is the point in a multidimensional space', ' IDoubleVector me;', ' ', ' // make this out of an IDoubleVector', ' public MultiDimPoint (IDoubleVector useMe) {', ' me = useMe;', ' }', ' ', ' // get the Euclidean distance to another point', ' public double getDistance (MultiDimPoint toMe) {', ' double distance = 0.0;', ' try {', ' for (int i = 0; i < me.getLength (); i++) {', ' double diff = me.getItem (i) - toMe.me.getItem (i);', ' diff *= diff;', ' distance += diff;', ' }', ' } catch (OutOfBoundsException e) {', ' throw new IndexOutOfBoundsException ("Can\'t compare two MultiDimPoint objects with different dimensionality!"); ', ' }', ' return Math.sqrt(distance);', ' }', ' ', '}', '// this is a leaf node', 'class LeafMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements ', ' IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myData;', ' ', ' // contructor that takes a data list and builds a node out of it', ' private LeafMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myDataIn) {', ' myData = myDataIn; ', ' }', ' ', ' // constructor that creates an empty node', ' public LeafMTreeNodeABCD () {', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> (); ', ' }', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // just add in the new data', ' myData.add (new PointABCD <PointInMetricSpace> (keyToAdd), dataToAdd);', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> newOne = myData.splitInTwo ();', ' LeafMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' myQ.insert (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData (), ', ' query.getDistance (myData.get (i).getKey ().getPointInInterior ()));', ' }', ' }', ' }', ' ', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' returnVal.add (new DataWrapper <PointInMetricSpace, DataType> (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData ()));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return 1; ', ' }', '', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', '// this silly little class is just a wrapper for a key, data pair', 'class DataWrapper <Key, Data> {', ' ', ' Key key;', ' Data data;', ' ', ' public DataWrapper (Key keyIn, Data dataIn) {', ' key = keyIn;', ' data = dataIn;', ' }', ' ', ' public Key getKey () {', ' return key;', ' }', ' ', ' public Data getData () {', ' return data;', ' }', '}', '', '', '// this is an internal node', 'class InternalMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType>', ' implements IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> myData;', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' // this constructs a new internal node that holds precisely the two nodes that are passed in', ' public InternalMTreeNodeABCD (IMTreeNodeABCD <PointInMetricSpace, DataType> refOne,', ' IMTreeNodeABCD <PointInMetricSpace, DataType> refTwo) {', ' ', ' // create a necw list and add the two guys in', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> ();', ' myData.add (refOne.getBoundingSphere (), refOne);', ' myData.add (refTwo.getBoundingSphere (), refTwo);', ' }', ' ', ' // this constructs a new node that holds the list of data that we were passed in', ' public InternalMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> useMe) {', ' myData = useMe; ', ' }', ' ', ' // from the interface', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // find the best child; this is the one we are closest to', ' double bestDist = 9e99;', ' int bestIndex = 0;', ' for (int i = 0; i < myData.size (); i++) {', ' ', ' double newDist = myData.get (i).getKey ().getPointInInterior ().getDistance (keyToAdd);', ' if (newDist < bestDist) {', ' bestDist = newDist;', ' bestIndex = i;', ' }', ' }', ' ', ' // do the recursive insert', ' IMTreeNodeABCD <PointInMetricSpace, DataType> newRef = myData.get (bestIndex).getData ().insert (keyToAdd, dataToAdd);', ' ', ' // if we got something back, then there was a split, so add the new node into our list', ' if (newRef != null) {', ' myData.add (newRef.getBoundingSphere (), newRef);', ' }', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> newOne = myData.splitInTwo ();', ' InternalMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.intersects (myData.get (i).getKey ())) {', ' myData.get (i).getData ().findKClosest (query, myQ);', ' }', ' }', ' }', ' ', ' // from the interface', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.intersects (myData.get (i).getKey ())) {', ' returnVal.addAll (myData.get (i).getData ().find (query));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return myData.get (0).getData ().depth () + 1; ', ' }', ' ', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', 'abstract class AMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> implements IMetricDataListABCD <PointInMetricSpace,KeyType, DataType> {', '', ' // this is the data that is actually stored in the list', ' private ArrayList <DataWrapper <KeyType, DataType>> myData;', ' ', ' // this is the sphere that bounds everything in the list', ' private SphereABCD <PointInMetricSpace> myBoundingSphere;', ' ', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myBoundingSphere; ', ' }', ' ', ' public int size () {', ' if (myData != null)', ' return myData.size (); ', ' else', ' return 0;', ' }', ' ', ' public DataWrapper <KeyType, DataType> get (int pos) {', ' return myData.get (pos);', ' }', ' ', ' public void replaceKey (int pos, KeyType keyToAdd) {', ' DataWrapper <KeyType, DataType> temp = myData.remove (pos);', ' DataWrapper <KeyType, DataType> newOne = new DataWrapper <KeyType, DataType> (keyToAdd, temp.getData ());', ' myData.add (pos, newOne);', ' }', ' ', ' public void add (KeyType keyToAdd, DataType dataToAdd) {', ' ', ' // if this is the first add, then set everyone up', ' if (myData == null) {', ' PointInMetricSpace myCentroid = keyToAdd.getPointInInterior ();', ' myBoundingSphere = new SphereABCD <PointInMetricSpace> (myCentroid, keyToAdd.maxDistanceTo (myCentroid));', ' myData = new ArrayList <DataWrapper <KeyType, DataType>> ();', ' ', ' // otherwise, extend the sphere if needed', ' } else {', ' myBoundingSphere.swallow (keyToAdd);', ' }', ' ', ' // add the data', ' myData.add (new DataWrapper <KeyType, DataType> (keyToAdd, dataToAdd));', ' }', ' ', ' // we want to potentially allow many implementations of the splitting lalgorithm', ' abstract public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // this is here so the actual splitting algorithn can access the list and change the sphere', ' protected ArrayList <DataWrapper <KeyType, DataType>> getList () {', ' return myData;', ' }', ' ', ' // this is here so the splitting algorithm can modify the list and the sphere', ' protected void replaceGuts (AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> withMe) {', ' myData = withMe.myData;', ' myBoundingSphere = withMe.myBoundingSphere;', ' }', ' ', '}', '', '// this is a particular implementation of the metric data list that uses a simple quadratic clustering', '// algorithm to perform a list split. It picks two "seeds" (the most distant objects) and then repeatedly', '// adds to the two new lists by choosing the objects closest to the seeds', 'class ChrisMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> extends AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> {', '', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo () {', ' ', ' // first, we need to find the two most distant points in the list', ' ArrayList <DataWrapper <KeyType, DataType>> myData = getList ();', ' int bestI = 0, bestJ = 0;', ' double maxDist = -1.0;', ' for (int i = 0; i < myData.size (); i++) {', ' for (int j = i + 1; j < myData.size (); j++) {', ' ', ' // get the two keys', ' DataWrapper <KeyType, DataType> pointOne = myData.get (i);', ' DataWrapper <KeyType, DataType> pointTwo = myData.get (j);', ' ', ' // find the difference between them', ' double curDist = pointOne.getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', '', ' // see if it is the biggest', ' if (curDist > maxDist) {', ' maxDist = curDist;', ' bestI = i;', ' bestJ = j;', ' }', ' }', ' }', ' ', ' // now, we have the best two points; those are seeds for the clustering', ' DataWrapper <KeyType, DataType> pointOne = myData.remove (bestI);', ' DataWrapper <KeyType, DataType> pointTwo = myData.remove (bestJ - 1);', ' ', ' // these are the two new lists', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listOne = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listTwo = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' ', ' // put the two seeds in', ' listOne.add (pointOne.getKey (), pointOne.getData ());', ' listTwo.add (pointTwo.getKey (), pointTwo.getData ());', ' ', ' // and add everyone else in', ' while (myData.size () != 0) {', ' ', ' // find the one closest to the first seed', ' int bestIndex = 0;', ' double bestDist = 9e99;', ' ', ' // loop thru all of the candidate data objects', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listOne.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' ', ' // break if no more data', ' if (myData.size () == 0)', ' break;', ' ', ' // loop thru all of the candidate data objects', ' bestDist = 9e99;', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listTwo.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' }', ' ', ' // now we replace our own guts with the first list', ' replaceGuts (listOne);', ' ', ' // and return the other list', ' return listTwo;', ' }', '}', '', 'interface IMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> {', ' ', ' // add a new pair to the list', ' public void add (KeyType keyToAdd, DataType dataToAdd);', ' ', ' // replace a key at the indicated position', ' public void replaceKey (int pos, KeyType keyToAdd);', ' ', ' // get the key, data pair that resides at a particular position', ' public DataWrapper <KeyType, DataType> get (int pos);', ' ', ' // return the number of items in the list', ' public int size ();', ' ', ' // split the list in two, using some clutering algorithm', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // get a sphere that totally bounds all of the objects in the list', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class MTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public MTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class SCMTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public SCMTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', '', 'public class MTreeTester extends TestCase {', ' ', ' // compare two lists of strings to see if the contents are the same', ' private boolean compareStringSets (ArrayList <String> setOne, ArrayList <String> setTwo) {', ' ', ' // sort the sets and make sure they are the same', ' boolean returnVal = true;', ' if (setOne.size () == setTwo.size ()) {', ' Collections.sort (setOne);', ' Collections.sort (setTwo);', ' for (int i = 0; i < setOne.size (); i++) {', ' if (!setOne.get (i).equals (setTwo.get (i))) {', ' returnVal = false;', ' break; ', ' }', ' }', ' } else {', ' returnVal = false;', ' }', ' ', ' // print out the result', ' System.out.println ("**** Expected:");', ' for (int i = 0; i < setOne.size (); i++) {', ' System.out.format (setOne.get (i) + " ");', ' }', ' System.out.println ("\\n**** Got:");', ' for (int i = 0; i < setTwo.size (); i++) {', ' System.out.format (setTwo.get (i) + " ");', ' }', ' System.out.println ("");', ' ', ' return returnVal;', ' }', ' ', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST SIMPLE ONE DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testOneDimRangeQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.find (query, expectedQuerySize / 2);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.find (query, expectedQuerySize / 2);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (numPoints);', ' result1 = myTree.find (query, expectedQuerySize);', ' result2 = hisTree.find (query, expectedQuerySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // like the last one, but runs a top k', ' private void testOneDimTopKQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (167);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.findKClosest (query, querySize);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (0);', ' result1 = myTree.findKClosest (query, querySize);', ' result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST MULTI-DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimRangeQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' double dist1 = 0;', ' double dist2 = 0;', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' dist1 = Math.sqrt (numDims) * expectedQuerySize / 2.0;', ' dist2 = Math.sqrt (numDims) * expectedQuerySize;', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' // do a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, (int) expectedQuerySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = myTree.findKClosest (query2, (int) expectedQuerySize);', ' ', ' // find the distance to the furthest point in both cases', ' for (int i = 0; i < (int) expectedQuerySize; i++) {', ' double newDist = result1.get (i).getKey ().getDistance (query1);', ' if (newDist > dist1)', ' dist1 = newDist;', ' newDist = result2.get (i).getKey ().getDistance (query2);', ' if (newDist > dist2)', ' dist2 = newDist;', ' }', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.find (query1, dist1);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.find (query1, dist1);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.find (query2, dist2);', ' result2 = hisTree.find (query2, dist2);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimTopKQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, querySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.findKClosest (query1, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.findKClosest (query2, querySize);', ' result2 = hisTree.findKClosest (query2, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' ', ' /**', ' * "TIER 1" TESTS', ' * NONE OF THESE REQUIRE ANY SPLITS', ' */', ' public void testEasy1() {', ' testOneDimRangeQuery (true, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy2() {', ' testOneDimRangeQuery (false, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy3() {', ' testOneDimRangeQuery (true, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy4() {', ' testOneDimRangeQuery (false, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy5() {', ' testMultiDimRangeQuery (true, 1, 5, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy6() {', ' testMultiDimRangeQuery (false, 1, 10, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy7() {', ' testMultiDimRangeQuery (true, 1, 5, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy8() {', ' testMultiDimRangeQuery (false, 1, 15, 10000, 10000, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 2" TESTS', ' * NONE OF THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testMod1() {', ' testOneDimRangeQuery (true, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod2() {', ' testOneDimRangeQuery (false, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod3() {', ' testOneDimRangeQuery (true, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod4() {', ' testOneDimRangeQuery (false, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod5() {', ' testMultiDimRangeQuery (true, 2, 5, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod6() {', ' testMultiDimRangeQuery (false, 2, 10, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod7() {', ' testMultiDimRangeQuery (true, 2, 5, 10000, 100, 1000, 10);', ' }', ' ', ' public void testMod8() {', ' testMultiDimRangeQuery (false, 2, 15, 10000, 100, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 3" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testHard1() {', ' testOneDimRangeQuery (true, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard2() {', ' testOneDimRangeQuery (false, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard3() {', ' testOneDimRangeQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard4() {', ' testOneDimRangeQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard5() {', ' testMultiDimRangeQuery (true, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard6() {', ' testMultiDimRangeQuery (false, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard7() {', ' testMultiDimRangeQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard8() {', ' testMultiDimRangeQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', ' ', ' /**', ' * "TIER 4" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE AND THEY TEST THE TOPK FUNCTIONALITY', ' */', ' ', ' public void testTopK1() {', ' testOneDimTopKQuery (true, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK2() {', ' testOneDimTopKQuery (false, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK3() {', ' testOneDimTopKQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK4() {', ' testOneDimTopKQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK5() {', ' testMultiDimTopKQuery (true, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK6() {', ' testMultiDimTopKQuery (false, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK7() {', ' testMultiDimTopKQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK8() {', ' testMultiDimTopKQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', '}'] | [{'reason_category': 'Else Reasoning', 'usage_line': 319}] | Variable 'toMe' used at line 319 is defined at line 315 and has a Short-Range dependency.
Global_Variable 'value' used at line 319 is defined at line 307 and has a Medium-Range dependency. | {'Else Reasoning': 1} | {'Variable Short-Range': 1, 'Global_Variable Medium-Range': 1} |
infilling_java | MTreeTester | 316 | 322 | ['import junit.framework.TestCase;', 'import java.util.ArrayList;', 'import java.util.Random;', 'import java.util.Collections;', '', '// this is a map from a set of keys of type PointInMetricSpace to a', '// set of data of type DataType', 'interface IMTree <Key extends IPointInMetricSpace <Key>, Data> {', ' ', ' // insert a new key/data pair into the map', ' void insert (Key keyToAdd, Data dataToAdd);', ' ', ' // find all of the key/data pairs in the map that fall within a', ' // particular distance of query point if no results are found, then', ' // an empty array is returned (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> find (Key query, double distance);', ' ', ' // find the k closest key/data pairs in the map to a particular', ' // query point ', ' //', ' // if the number of points in the map is less than k, then the', ' // returned list will have less than k pairs in it', ' //', ' // if the number of points is zero, then an empty array is returned', ' // (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> findKClosest (Key query, int k);', ' ', ' // returns the number of nodes that exist on a path from root to leaf in the tree...', ' // whtever the details of the implementation are, a tree with a single leaf node should return 1, and a tree', ' // with more than one lead node should return at least two (since it must have at least one internal node).', ' public int depth ();', ' ', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', '', 'interface IDoubleVector {', '', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '', '// this correponds to some geometric object in a metric space; the object is built out of', '// one or more points of type PointInMetricSpace', 'interface IObjectInMetricSpaceABCD <PointInMetricSpace extends IPointInMetricSpace<PointInMetricSpace>> {', ' ', ' // get the maximum distance from some point on the shape to a particular point in the metric space', ' double maxDistanceTo (PointInMetricSpace checkMe);', ' ', ' // return some arbitrary point on the interior of the geometric object', ' PointInMetricSpace getPointInInterior ();', '}', '', '', '// this interface corresponds to a point in some metric space', 'interface IPointInMetricSpace <PointInMetricSpace> {', ' ', ' // get the distance to another point', ' // ', ' // for this to work in an M-Tree, distances should be "metric" and', ' // obey the triangle inequality', ' double getDistance (PointInMetricSpace toMe);', '}', '', '// this is the basic node type in the structure', 'interface IMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> {', ' ', ' // insert a new key/data pair into the structure. The return value is a new MTreeNode if there was', ' // a split in response to the insertion, or a null if there was no split', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd);', ' ', ' // find all of the key/data pairs in the structure that fall within a particular query sphere', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query); ', ' ', ' // find the set of items closest to the given query point', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ);', ' ', ' // returns a sphere that totally encompasses everything in the node and its subtree', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', ' ', ' // returns the depth', ' public int depth ();', '}', '', '// this is a point in a particular metric space', 'class PointABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the point', ' private PointInMetricSpace me;', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return me; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return checkMe.getDistance (me); ', ' }', ' ', ' // contruct a point', ' public PointABCD (PointInMetricSpace useMe) {', ' me = useMe; ', ' }', '}', '', 'class PQueueABCD <PointInMetricSpace, DataType> {', ' ', ' // this is an object in the queue', ' private class Wrapper {', ' DataWrapper <PointInMetricSpace, DataType> myData;', ' double distance;', ' }', ' ', ' // this is the actual queue', ' ArrayList <Wrapper> myList;', ' ', ' // this is the largest distance value currently in the queue', ' double large;', ' ', ' // this is the max number of objects', ' int maxCount;', ' ', ' // create a priority queue with the speced number of slots', ' PQueueABCD (int maxCountIn) {', ' maxCount = maxCountIn;', ' myList = new ArrayList <Wrapper> ();', ' large = 9e99;', ' }', ' ', ' // get the largest distance in the queue', ' double getDist () {', ' return large;', ' }', ' ', ' // add a new object to the queue... the insertion is ignored if the distance value', ' // exceeds the largest that is in the queue and the queue is already full', ' void insert (PointInMetricSpace key, DataType data, double distance) {', ' ', ' // if we are full, remove the one with the largest distance', ' if (myList.size () == maxCount && distance < large) {', ' ', ' int badIndex = 0;', ' double maxDist = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > maxDist) {', ' maxDist = myList.get (i).distance;', ' badIndex = i;', ' }', ' }', ' ', ' myList.remove (badIndex);', ' }', ' ', ' // see if there is room', ' if (myList.size () < maxCount) {', ' ', ' // add it ', ' Wrapper newOne = new Wrapper ();', ' newOne.myData = new DataWrapper <PointInMetricSpace, DataType> (key, data);', ' newOne.distance = distance;', ' myList.add (newOne); ', ' }', ' ', ' // if we are full, reset the max distance', ' if (myList.size () == maxCount) {', ' large = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > large) {', ' large = myList.get (i).distance;', ' }', ' }', ' }', ' ', ' }', ' ', ' // extracts the contents of the queue', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> done () {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' for (int i = 0; i < myList.size (); i++) {', ' returnVal.add (myList.get (i).myData); ', ' }', ' ', ' return returnVal;', ' }', ' ', '}', '', '// this is a sphere in a particular metric space', 'class SphereABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the center of the sphere and its radius', ' private PointInMetricSpace center;', ' private double radius;', ' ', ' // build a sphere out of its center and its radius', ' public SphereABCD (PointInMetricSpace centerIn, double radiusIn) {', ' center = centerIn;', ' radius = radiusIn;', ' }', ' ', ' // increase the size of the sphere so it contains the object swallowMe', ' public void swallow (IObjectInMetricSpaceABCD <PointInMetricSpace> swallowMe) {', ' ', ' // see if we need to increase the radius to swallow this guy', ' double dist = swallowMe.maxDistanceTo (center);', ' if (dist > radius)', ' radius = dist;', ' }', ' ', ' // check to see if a sphere intersects another sphere', ' public boolean intersects (SphereABCD <PointInMetricSpace> me) {', ' return (me.center.getDistance (center) <= me.radius + radius);', ' }', ' ', ' // check to see if the sphere contains a point', ' public boolean contains (PointInMetricSpace checkMe) {', ' return (checkMe.getDistance (center) <= radius);', ' }', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return center; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return radius + checkMe.getDistance (center); ', ' }', '}', '', '', '', 'class OneDimPoint implements IPointInMetricSpace <OneDimPoint> {', ' ', ' // this is the actual double', ' Double value;', ' ', ' // construct this out of a double value', ' public OneDimPoint (double makeFromMe) {', ' value = new Double (makeFromMe);', ' }', ' ', ' // get the distance to another point', ' public double getDistance (OneDimPoint toMe) {'] | [' if (value > toMe.value)', ' return value - toMe.value;', ' else', ' return toMe.value - value;', ' }', ' ', '}'] | ['', 'class MultiDimPoint implements IPointInMetricSpace <MultiDimPoint> {', ' ', ' // this is the point in a multidimensional space', ' IDoubleVector me;', ' ', ' // make this out of an IDoubleVector', ' public MultiDimPoint (IDoubleVector useMe) {', ' me = useMe;', ' }', ' ', ' // get the Euclidean distance to another point', ' public double getDistance (MultiDimPoint toMe) {', ' double distance = 0.0;', ' try {', ' for (int i = 0; i < me.getLength (); i++) {', ' double diff = me.getItem (i) - toMe.me.getItem (i);', ' diff *= diff;', ' distance += diff;', ' }', ' } catch (OutOfBoundsException e) {', ' throw new IndexOutOfBoundsException ("Can\'t compare two MultiDimPoint objects with different dimensionality!"); ', ' }', ' return Math.sqrt(distance);', ' }', ' ', '}', '// this is a leaf node', 'class LeafMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements ', ' IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myData;', ' ', ' // contructor that takes a data list and builds a node out of it', ' private LeafMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myDataIn) {', ' myData = myDataIn; ', ' }', ' ', ' // constructor that creates an empty node', ' public LeafMTreeNodeABCD () {', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> (); ', ' }', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // just add in the new data', ' myData.add (new PointABCD <PointInMetricSpace> (keyToAdd), dataToAdd);', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> newOne = myData.splitInTwo ();', ' LeafMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' myQ.insert (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData (), ', ' query.getDistance (myData.get (i).getKey ().getPointInInterior ()));', ' }', ' }', ' }', ' ', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' returnVal.add (new DataWrapper <PointInMetricSpace, DataType> (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData ()));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return 1; ', ' }', '', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', '// this silly little class is just a wrapper for a key, data pair', 'class DataWrapper <Key, Data> {', ' ', ' Key key;', ' Data data;', ' ', ' public DataWrapper (Key keyIn, Data dataIn) {', ' key = keyIn;', ' data = dataIn;', ' }', ' ', ' public Key getKey () {', ' return key;', ' }', ' ', ' public Data getData () {', ' return data;', ' }', '}', '', '', '// this is an internal node', 'class InternalMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType>', ' implements IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> myData;', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' // this constructs a new internal node that holds precisely the two nodes that are passed in', ' public InternalMTreeNodeABCD (IMTreeNodeABCD <PointInMetricSpace, DataType> refOne,', ' IMTreeNodeABCD <PointInMetricSpace, DataType> refTwo) {', ' ', ' // create a necw list and add the two guys in', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> ();', ' myData.add (refOne.getBoundingSphere (), refOne);', ' myData.add (refTwo.getBoundingSphere (), refTwo);', ' }', ' ', ' // this constructs a new node that holds the list of data that we were passed in', ' public InternalMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> useMe) {', ' myData = useMe; ', ' }', ' ', ' // from the interface', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // find the best child; this is the one we are closest to', ' double bestDist = 9e99;', ' int bestIndex = 0;', ' for (int i = 0; i < myData.size (); i++) {', ' ', ' double newDist = myData.get (i).getKey ().getPointInInterior ().getDistance (keyToAdd);', ' if (newDist < bestDist) {', ' bestDist = newDist;', ' bestIndex = i;', ' }', ' }', ' ', ' // do the recursive insert', ' IMTreeNodeABCD <PointInMetricSpace, DataType> newRef = myData.get (bestIndex).getData ().insert (keyToAdd, dataToAdd);', ' ', ' // if we got something back, then there was a split, so add the new node into our list', ' if (newRef != null) {', ' myData.add (newRef.getBoundingSphere (), newRef);', ' }', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> newOne = myData.splitInTwo ();', ' InternalMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.intersects (myData.get (i).getKey ())) {', ' myData.get (i).getData ().findKClosest (query, myQ);', ' }', ' }', ' }', ' ', ' // from the interface', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.intersects (myData.get (i).getKey ())) {', ' returnVal.addAll (myData.get (i).getData ().find (query));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return myData.get (0).getData ().depth () + 1; ', ' }', ' ', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', 'abstract class AMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> implements IMetricDataListABCD <PointInMetricSpace,KeyType, DataType> {', '', ' // this is the data that is actually stored in the list', ' private ArrayList <DataWrapper <KeyType, DataType>> myData;', ' ', ' // this is the sphere that bounds everything in the list', ' private SphereABCD <PointInMetricSpace> myBoundingSphere;', ' ', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myBoundingSphere; ', ' }', ' ', ' public int size () {', ' if (myData != null)', ' return myData.size (); ', ' else', ' return 0;', ' }', ' ', ' public DataWrapper <KeyType, DataType> get (int pos) {', ' return myData.get (pos);', ' }', ' ', ' public void replaceKey (int pos, KeyType keyToAdd) {', ' DataWrapper <KeyType, DataType> temp = myData.remove (pos);', ' DataWrapper <KeyType, DataType> newOne = new DataWrapper <KeyType, DataType> (keyToAdd, temp.getData ());', ' myData.add (pos, newOne);', ' }', ' ', ' public void add (KeyType keyToAdd, DataType dataToAdd) {', ' ', ' // if this is the first add, then set everyone up', ' if (myData == null) {', ' PointInMetricSpace myCentroid = keyToAdd.getPointInInterior ();', ' myBoundingSphere = new SphereABCD <PointInMetricSpace> (myCentroid, keyToAdd.maxDistanceTo (myCentroid));', ' myData = new ArrayList <DataWrapper <KeyType, DataType>> ();', ' ', ' // otherwise, extend the sphere if needed', ' } else {', ' myBoundingSphere.swallow (keyToAdd);', ' }', ' ', ' // add the data', ' myData.add (new DataWrapper <KeyType, DataType> (keyToAdd, dataToAdd));', ' }', ' ', ' // we want to potentially allow many implementations of the splitting lalgorithm', ' abstract public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // this is here so the actual splitting algorithn can access the list and change the sphere', ' protected ArrayList <DataWrapper <KeyType, DataType>> getList () {', ' return myData;', ' }', ' ', ' // this is here so the splitting algorithm can modify the list and the sphere', ' protected void replaceGuts (AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> withMe) {', ' myData = withMe.myData;', ' myBoundingSphere = withMe.myBoundingSphere;', ' }', ' ', '}', '', '// this is a particular implementation of the metric data list that uses a simple quadratic clustering', '// algorithm to perform a list split. It picks two "seeds" (the most distant objects) and then repeatedly', '// adds to the two new lists by choosing the objects closest to the seeds', 'class ChrisMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> extends AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> {', '', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo () {', ' ', ' // first, we need to find the two most distant points in the list', ' ArrayList <DataWrapper <KeyType, DataType>> myData = getList ();', ' int bestI = 0, bestJ = 0;', ' double maxDist = -1.0;', ' for (int i = 0; i < myData.size (); i++) {', ' for (int j = i + 1; j < myData.size (); j++) {', ' ', ' // get the two keys', ' DataWrapper <KeyType, DataType> pointOne = myData.get (i);', ' DataWrapper <KeyType, DataType> pointTwo = myData.get (j);', ' ', ' // find the difference between them', ' double curDist = pointOne.getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', '', ' // see if it is the biggest', ' if (curDist > maxDist) {', ' maxDist = curDist;', ' bestI = i;', ' bestJ = j;', ' }', ' }', ' }', ' ', ' // now, we have the best two points; those are seeds for the clustering', ' DataWrapper <KeyType, DataType> pointOne = myData.remove (bestI);', ' DataWrapper <KeyType, DataType> pointTwo = myData.remove (bestJ - 1);', ' ', ' // these are the two new lists', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listOne = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listTwo = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' ', ' // put the two seeds in', ' listOne.add (pointOne.getKey (), pointOne.getData ());', ' listTwo.add (pointTwo.getKey (), pointTwo.getData ());', ' ', ' // and add everyone else in', ' while (myData.size () != 0) {', ' ', ' // find the one closest to the first seed', ' int bestIndex = 0;', ' double bestDist = 9e99;', ' ', ' // loop thru all of the candidate data objects', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listOne.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' ', ' // break if no more data', ' if (myData.size () == 0)', ' break;', ' ', ' // loop thru all of the candidate data objects', ' bestDist = 9e99;', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listTwo.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' }', ' ', ' // now we replace our own guts with the first list', ' replaceGuts (listOne);', ' ', ' // and return the other list', ' return listTwo;', ' }', '}', '', 'interface IMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> {', ' ', ' // add a new pair to the list', ' public void add (KeyType keyToAdd, DataType dataToAdd);', ' ', ' // replace a key at the indicated position', ' public void replaceKey (int pos, KeyType keyToAdd);', ' ', ' // get the key, data pair that resides at a particular position', ' public DataWrapper <KeyType, DataType> get (int pos);', ' ', ' // return the number of items in the list', ' public int size ();', ' ', ' // split the list in two, using some clutering algorithm', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // get a sphere that totally bounds all of the objects in the list', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class MTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public MTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class SCMTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public SCMTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', '', 'public class MTreeTester extends TestCase {', ' ', ' // compare two lists of strings to see if the contents are the same', ' private boolean compareStringSets (ArrayList <String> setOne, ArrayList <String> setTwo) {', ' ', ' // sort the sets and make sure they are the same', ' boolean returnVal = true;', ' if (setOne.size () == setTwo.size ()) {', ' Collections.sort (setOne);', ' Collections.sort (setTwo);', ' for (int i = 0; i < setOne.size (); i++) {', ' if (!setOne.get (i).equals (setTwo.get (i))) {', ' returnVal = false;', ' break; ', ' }', ' }', ' } else {', ' returnVal = false;', ' }', ' ', ' // print out the result', ' System.out.println ("**** Expected:");', ' for (int i = 0; i < setOne.size (); i++) {', ' System.out.format (setOne.get (i) + " ");', ' }', ' System.out.println ("\\n**** Got:");', ' for (int i = 0; i < setTwo.size (); i++) {', ' System.out.format (setTwo.get (i) + " ");', ' }', ' System.out.println ("");', ' ', ' return returnVal;', ' }', ' ', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST SIMPLE ONE DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testOneDimRangeQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.find (query, expectedQuerySize / 2);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.find (query, expectedQuerySize / 2);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (numPoints);', ' result1 = myTree.find (query, expectedQuerySize);', ' result2 = hisTree.find (query, expectedQuerySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // like the last one, but runs a top k', ' private void testOneDimTopKQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (167);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.findKClosest (query, querySize);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (0);', ' result1 = myTree.findKClosest (query, querySize);', ' result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST MULTI-DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimRangeQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' double dist1 = 0;', ' double dist2 = 0;', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' dist1 = Math.sqrt (numDims) * expectedQuerySize / 2.0;', ' dist2 = Math.sqrt (numDims) * expectedQuerySize;', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' // do a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, (int) expectedQuerySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = myTree.findKClosest (query2, (int) expectedQuerySize);', ' ', ' // find the distance to the furthest point in both cases', ' for (int i = 0; i < (int) expectedQuerySize; i++) {', ' double newDist = result1.get (i).getKey ().getDistance (query1);', ' if (newDist > dist1)', ' dist1 = newDist;', ' newDist = result2.get (i).getKey ().getDistance (query2);', ' if (newDist > dist2)', ' dist2 = newDist;', ' }', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.find (query1, dist1);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.find (query1, dist1);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.find (query2, dist2);', ' result2 = hisTree.find (query2, dist2);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimTopKQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, querySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.findKClosest (query1, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.findKClosest (query2, querySize);', ' result2 = hisTree.findKClosest (query2, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' ', ' /**', ' * "TIER 1" TESTS', ' * NONE OF THESE REQUIRE ANY SPLITS', ' */', ' public void testEasy1() {', ' testOneDimRangeQuery (true, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy2() {', ' testOneDimRangeQuery (false, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy3() {', ' testOneDimRangeQuery (true, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy4() {', ' testOneDimRangeQuery (false, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy5() {', ' testMultiDimRangeQuery (true, 1, 5, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy6() {', ' testMultiDimRangeQuery (false, 1, 10, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy7() {', ' testMultiDimRangeQuery (true, 1, 5, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy8() {', ' testMultiDimRangeQuery (false, 1, 15, 10000, 10000, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 2" TESTS', ' * NONE OF THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testMod1() {', ' testOneDimRangeQuery (true, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod2() {', ' testOneDimRangeQuery (false, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod3() {', ' testOneDimRangeQuery (true, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod4() {', ' testOneDimRangeQuery (false, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod5() {', ' testMultiDimRangeQuery (true, 2, 5, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod6() {', ' testMultiDimRangeQuery (false, 2, 10, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod7() {', ' testMultiDimRangeQuery (true, 2, 5, 10000, 100, 1000, 10);', ' }', ' ', ' public void testMod8() {', ' testMultiDimRangeQuery (false, 2, 15, 10000, 100, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 3" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testHard1() {', ' testOneDimRangeQuery (true, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard2() {', ' testOneDimRangeQuery (false, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard3() {', ' testOneDimRangeQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard4() {', ' testOneDimRangeQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard5() {', ' testMultiDimRangeQuery (true, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard6() {', ' testMultiDimRangeQuery (false, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard7() {', ' testMultiDimRangeQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard8() {', ' testMultiDimRangeQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', ' ', ' /**', ' * "TIER 4" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE AND THEY TEST THE TOPK FUNCTIONALITY', ' */', ' ', ' public void testTopK1() {', ' testOneDimTopKQuery (true, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK2() {', ' testOneDimTopKQuery (false, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK3() {', ' testOneDimTopKQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK4() {', ' testOneDimTopKQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK5() {', ' testMultiDimTopKQuery (true, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK6() {', ' testMultiDimTopKQuery (false, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK7() {', ' testMultiDimTopKQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK8() {', ' testMultiDimTopKQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', '}'] | [{'reason_category': 'If Condition', 'usage_line': 316}, {'reason_category': 'If Body', 'usage_line': 317}, {'reason_category': 'Else Reasoning', 'usage_line': 318}, {'reason_category': 'Else Reasoning', 'usage_line': 319}, {'reason_category': 'Else Reasoning', 'usage_line': 320}] | Global_Variable 'value' used at line 316 is defined at line 307 and has a Short-Range dependency.
Variable 'toMe' used at line 316 is defined at line 315 and has a Short-Range dependency.
Global_Variable 'value' used at line 317 is defined at line 307 and has a Short-Range dependency.
Variable 'toMe' used at line 317 is defined at line 315 and has a Short-Range dependency.
Variable 'toMe' used at line 319 is defined at line 315 and has a Short-Range dependency.
Global_Variable 'value' used at line 319 is defined at line 307 and has a Medium-Range dependency. | {'If Condition': 1, 'If Body': 1, 'Else Reasoning': 3} | {'Global_Variable Short-Range': 2, 'Variable Short-Range': 3, 'Global_Variable Medium-Range': 1} |
infilling_java | MTreeTester | 331 | 332 | ['import junit.framework.TestCase;', 'import java.util.ArrayList;', 'import java.util.Random;', 'import java.util.Collections;', '', '// this is a map from a set of keys of type PointInMetricSpace to a', '// set of data of type DataType', 'interface IMTree <Key extends IPointInMetricSpace <Key>, Data> {', ' ', ' // insert a new key/data pair into the map', ' void insert (Key keyToAdd, Data dataToAdd);', ' ', ' // find all of the key/data pairs in the map that fall within a', ' // particular distance of query point if no results are found, then', ' // an empty array is returned (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> find (Key query, double distance);', ' ', ' // find the k closest key/data pairs in the map to a particular', ' // query point ', ' //', ' // if the number of points in the map is less than k, then the', ' // returned list will have less than k pairs in it', ' //', ' // if the number of points is zero, then an empty array is returned', ' // (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> findKClosest (Key query, int k);', ' ', ' // returns the number of nodes that exist on a path from root to leaf in the tree...', ' // whtever the details of the implementation are, a tree with a single leaf node should return 1, and a tree', ' // with more than one lead node should return at least two (since it must have at least one internal node).', ' public int depth ();', ' ', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', '', 'interface IDoubleVector {', '', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '', '// this correponds to some geometric object in a metric space; the object is built out of', '// one or more points of type PointInMetricSpace', 'interface IObjectInMetricSpaceABCD <PointInMetricSpace extends IPointInMetricSpace<PointInMetricSpace>> {', ' ', ' // get the maximum distance from some point on the shape to a particular point in the metric space', ' double maxDistanceTo (PointInMetricSpace checkMe);', ' ', ' // return some arbitrary point on the interior of the geometric object', ' PointInMetricSpace getPointInInterior ();', '}', '', '', '// this interface corresponds to a point in some metric space', 'interface IPointInMetricSpace <PointInMetricSpace> {', ' ', ' // get the distance to another point', ' // ', ' // for this to work in an M-Tree, distances should be "metric" and', ' // obey the triangle inequality', ' double getDistance (PointInMetricSpace toMe);', '}', '', '// this is the basic node type in the structure', 'interface IMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> {', ' ', ' // insert a new key/data pair into the structure. The return value is a new MTreeNode if there was', ' // a split in response to the insertion, or a null if there was no split', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd);', ' ', ' // find all of the key/data pairs in the structure that fall within a particular query sphere', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query); ', ' ', ' // find the set of items closest to the given query point', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ);', ' ', ' // returns a sphere that totally encompasses everything in the node and its subtree', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', ' ', ' // returns the depth', ' public int depth ();', '}', '', '// this is a point in a particular metric space', 'class PointABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the point', ' private PointInMetricSpace me;', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return me; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return checkMe.getDistance (me); ', ' }', ' ', ' // contruct a point', ' public PointABCD (PointInMetricSpace useMe) {', ' me = useMe; ', ' }', '}', '', 'class PQueueABCD <PointInMetricSpace, DataType> {', ' ', ' // this is an object in the queue', ' private class Wrapper {', ' DataWrapper <PointInMetricSpace, DataType> myData;', ' double distance;', ' }', ' ', ' // this is the actual queue', ' ArrayList <Wrapper> myList;', ' ', ' // this is the largest distance value currently in the queue', ' double large;', ' ', ' // this is the max number of objects', ' int maxCount;', ' ', ' // create a priority queue with the speced number of slots', ' PQueueABCD (int maxCountIn) {', ' maxCount = maxCountIn;', ' myList = new ArrayList <Wrapper> ();', ' large = 9e99;', ' }', ' ', ' // get the largest distance in the queue', ' double getDist () {', ' return large;', ' }', ' ', ' // add a new object to the queue... the insertion is ignored if the distance value', ' // exceeds the largest that is in the queue and the queue is already full', ' void insert (PointInMetricSpace key, DataType data, double distance) {', ' ', ' // if we are full, remove the one with the largest distance', ' if (myList.size () == maxCount && distance < large) {', ' ', ' int badIndex = 0;', ' double maxDist = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > maxDist) {', ' maxDist = myList.get (i).distance;', ' badIndex = i;', ' }', ' }', ' ', ' myList.remove (badIndex);', ' }', ' ', ' // see if there is room', ' if (myList.size () < maxCount) {', ' ', ' // add it ', ' Wrapper newOne = new Wrapper ();', ' newOne.myData = new DataWrapper <PointInMetricSpace, DataType> (key, data);', ' newOne.distance = distance;', ' myList.add (newOne); ', ' }', ' ', ' // if we are full, reset the max distance', ' if (myList.size () == maxCount) {', ' large = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > large) {', ' large = myList.get (i).distance;', ' }', ' }', ' }', ' ', ' }', ' ', ' // extracts the contents of the queue', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> done () {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' for (int i = 0; i < myList.size (); i++) {', ' returnVal.add (myList.get (i).myData); ', ' }', ' ', ' return returnVal;', ' }', ' ', '}', '', '// this is a sphere in a particular metric space', 'class SphereABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the center of the sphere and its radius', ' private PointInMetricSpace center;', ' private double radius;', ' ', ' // build a sphere out of its center and its radius', ' public SphereABCD (PointInMetricSpace centerIn, double radiusIn) {', ' center = centerIn;', ' radius = radiusIn;', ' }', ' ', ' // increase the size of the sphere so it contains the object swallowMe', ' public void swallow (IObjectInMetricSpaceABCD <PointInMetricSpace> swallowMe) {', ' ', ' // see if we need to increase the radius to swallow this guy', ' double dist = swallowMe.maxDistanceTo (center);', ' if (dist > radius)', ' radius = dist;', ' }', ' ', ' // check to see if a sphere intersects another sphere', ' public boolean intersects (SphereABCD <PointInMetricSpace> me) {', ' return (me.center.getDistance (center) <= me.radius + radius);', ' }', ' ', ' // check to see if the sphere contains a point', ' public boolean contains (PointInMetricSpace checkMe) {', ' return (checkMe.getDistance (center) <= radius);', ' }', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return center; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return radius + checkMe.getDistance (center); ', ' }', '}', '', '', '', 'class OneDimPoint implements IPointInMetricSpace <OneDimPoint> {', ' ', ' // this is the actual double', ' Double value;', ' ', ' // construct this out of a double value', ' public OneDimPoint (double makeFromMe) {', ' value = new Double (makeFromMe);', ' }', ' ', ' // get the distance to another point', ' public double getDistance (OneDimPoint toMe) {', ' if (value > toMe.value)', ' return value - toMe.value;', ' else', ' return toMe.value - value;', ' }', ' ', '}', '', 'class MultiDimPoint implements IPointInMetricSpace <MultiDimPoint> {', ' ', ' // this is the point in a multidimensional space', ' IDoubleVector me;', ' ', ' // make this out of an IDoubleVector', ' public MultiDimPoint (IDoubleVector useMe) {'] | [' me = useMe;', ' }'] | [' ', ' // get the Euclidean distance to another point', ' public double getDistance (MultiDimPoint toMe) {', ' double distance = 0.0;', ' try {', ' for (int i = 0; i < me.getLength (); i++) {', ' double diff = me.getItem (i) - toMe.me.getItem (i);', ' diff *= diff;', ' distance += diff;', ' }', ' } catch (OutOfBoundsException e) {', ' throw new IndexOutOfBoundsException ("Can\'t compare two MultiDimPoint objects with different dimensionality!"); ', ' }', ' return Math.sqrt(distance);', ' }', ' ', '}', '// this is a leaf node', 'class LeafMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements ', ' IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myData;', ' ', ' // contructor that takes a data list and builds a node out of it', ' private LeafMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myDataIn) {', ' myData = myDataIn; ', ' }', ' ', ' // constructor that creates an empty node', ' public LeafMTreeNodeABCD () {', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> (); ', ' }', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // just add in the new data', ' myData.add (new PointABCD <PointInMetricSpace> (keyToAdd), dataToAdd);', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> newOne = myData.splitInTwo ();', ' LeafMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' myQ.insert (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData (), ', ' query.getDistance (myData.get (i).getKey ().getPointInInterior ()));', ' }', ' }', ' }', ' ', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' returnVal.add (new DataWrapper <PointInMetricSpace, DataType> (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData ()));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return 1; ', ' }', '', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', '// this silly little class is just a wrapper for a key, data pair', 'class DataWrapper <Key, Data> {', ' ', ' Key key;', ' Data data;', ' ', ' public DataWrapper (Key keyIn, Data dataIn) {', ' key = keyIn;', ' data = dataIn;', ' }', ' ', ' public Key getKey () {', ' return key;', ' }', ' ', ' public Data getData () {', ' return data;', ' }', '}', '', '', '// this is an internal node', 'class InternalMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType>', ' implements IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> myData;', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' // this constructs a new internal node that holds precisely the two nodes that are passed in', ' public InternalMTreeNodeABCD (IMTreeNodeABCD <PointInMetricSpace, DataType> refOne,', ' IMTreeNodeABCD <PointInMetricSpace, DataType> refTwo) {', ' ', ' // create a necw list and add the two guys in', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> ();', ' myData.add (refOne.getBoundingSphere (), refOne);', ' myData.add (refTwo.getBoundingSphere (), refTwo);', ' }', ' ', ' // this constructs a new node that holds the list of data that we were passed in', ' public InternalMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> useMe) {', ' myData = useMe; ', ' }', ' ', ' // from the interface', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // find the best child; this is the one we are closest to', ' double bestDist = 9e99;', ' int bestIndex = 0;', ' for (int i = 0; i < myData.size (); i++) {', ' ', ' double newDist = myData.get (i).getKey ().getPointInInterior ().getDistance (keyToAdd);', ' if (newDist < bestDist) {', ' bestDist = newDist;', ' bestIndex = i;', ' }', ' }', ' ', ' // do the recursive insert', ' IMTreeNodeABCD <PointInMetricSpace, DataType> newRef = myData.get (bestIndex).getData ().insert (keyToAdd, dataToAdd);', ' ', ' // if we got something back, then there was a split, so add the new node into our list', ' if (newRef != null) {', ' myData.add (newRef.getBoundingSphere (), newRef);', ' }', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> newOne = myData.splitInTwo ();', ' InternalMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.intersects (myData.get (i).getKey ())) {', ' myData.get (i).getData ().findKClosest (query, myQ);', ' }', ' }', ' }', ' ', ' // from the interface', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.intersects (myData.get (i).getKey ())) {', ' returnVal.addAll (myData.get (i).getData ().find (query));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return myData.get (0).getData ().depth () + 1; ', ' }', ' ', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', 'abstract class AMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> implements IMetricDataListABCD <PointInMetricSpace,KeyType, DataType> {', '', ' // this is the data that is actually stored in the list', ' private ArrayList <DataWrapper <KeyType, DataType>> myData;', ' ', ' // this is the sphere that bounds everything in the list', ' private SphereABCD <PointInMetricSpace> myBoundingSphere;', ' ', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myBoundingSphere; ', ' }', ' ', ' public int size () {', ' if (myData != null)', ' return myData.size (); ', ' else', ' return 0;', ' }', ' ', ' public DataWrapper <KeyType, DataType> get (int pos) {', ' return myData.get (pos);', ' }', ' ', ' public void replaceKey (int pos, KeyType keyToAdd) {', ' DataWrapper <KeyType, DataType> temp = myData.remove (pos);', ' DataWrapper <KeyType, DataType> newOne = new DataWrapper <KeyType, DataType> (keyToAdd, temp.getData ());', ' myData.add (pos, newOne);', ' }', ' ', ' public void add (KeyType keyToAdd, DataType dataToAdd) {', ' ', ' // if this is the first add, then set everyone up', ' if (myData == null) {', ' PointInMetricSpace myCentroid = keyToAdd.getPointInInterior ();', ' myBoundingSphere = new SphereABCD <PointInMetricSpace> (myCentroid, keyToAdd.maxDistanceTo (myCentroid));', ' myData = new ArrayList <DataWrapper <KeyType, DataType>> ();', ' ', ' // otherwise, extend the sphere if needed', ' } else {', ' myBoundingSphere.swallow (keyToAdd);', ' }', ' ', ' // add the data', ' myData.add (new DataWrapper <KeyType, DataType> (keyToAdd, dataToAdd));', ' }', ' ', ' // we want to potentially allow many implementations of the splitting lalgorithm', ' abstract public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // this is here so the actual splitting algorithn can access the list and change the sphere', ' protected ArrayList <DataWrapper <KeyType, DataType>> getList () {', ' return myData;', ' }', ' ', ' // this is here so the splitting algorithm can modify the list and the sphere', ' protected void replaceGuts (AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> withMe) {', ' myData = withMe.myData;', ' myBoundingSphere = withMe.myBoundingSphere;', ' }', ' ', '}', '', '// this is a particular implementation of the metric data list that uses a simple quadratic clustering', '// algorithm to perform a list split. It picks two "seeds" (the most distant objects) and then repeatedly', '// adds to the two new lists by choosing the objects closest to the seeds', 'class ChrisMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> extends AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> {', '', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo () {', ' ', ' // first, we need to find the two most distant points in the list', ' ArrayList <DataWrapper <KeyType, DataType>> myData = getList ();', ' int bestI = 0, bestJ = 0;', ' double maxDist = -1.0;', ' for (int i = 0; i < myData.size (); i++) {', ' for (int j = i + 1; j < myData.size (); j++) {', ' ', ' // get the two keys', ' DataWrapper <KeyType, DataType> pointOne = myData.get (i);', ' DataWrapper <KeyType, DataType> pointTwo = myData.get (j);', ' ', ' // find the difference between them', ' double curDist = pointOne.getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', '', ' // see if it is the biggest', ' if (curDist > maxDist) {', ' maxDist = curDist;', ' bestI = i;', ' bestJ = j;', ' }', ' }', ' }', ' ', ' // now, we have the best two points; those are seeds for the clustering', ' DataWrapper <KeyType, DataType> pointOne = myData.remove (bestI);', ' DataWrapper <KeyType, DataType> pointTwo = myData.remove (bestJ - 1);', ' ', ' // these are the two new lists', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listOne = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listTwo = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' ', ' // put the two seeds in', ' listOne.add (pointOne.getKey (), pointOne.getData ());', ' listTwo.add (pointTwo.getKey (), pointTwo.getData ());', ' ', ' // and add everyone else in', ' while (myData.size () != 0) {', ' ', ' // find the one closest to the first seed', ' int bestIndex = 0;', ' double bestDist = 9e99;', ' ', ' // loop thru all of the candidate data objects', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listOne.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' ', ' // break if no more data', ' if (myData.size () == 0)', ' break;', ' ', ' // loop thru all of the candidate data objects', ' bestDist = 9e99;', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listTwo.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' }', ' ', ' // now we replace our own guts with the first list', ' replaceGuts (listOne);', ' ', ' // and return the other list', ' return listTwo;', ' }', '}', '', 'interface IMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> {', ' ', ' // add a new pair to the list', ' public void add (KeyType keyToAdd, DataType dataToAdd);', ' ', ' // replace a key at the indicated position', ' public void replaceKey (int pos, KeyType keyToAdd);', ' ', ' // get the key, data pair that resides at a particular position', ' public DataWrapper <KeyType, DataType> get (int pos);', ' ', ' // return the number of items in the list', ' public int size ();', ' ', ' // split the list in two, using some clutering algorithm', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // get a sphere that totally bounds all of the objects in the list', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class MTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public MTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class SCMTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public SCMTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', '', 'public class MTreeTester extends TestCase {', ' ', ' // compare two lists of strings to see if the contents are the same', ' private boolean compareStringSets (ArrayList <String> setOne, ArrayList <String> setTwo) {', ' ', ' // sort the sets and make sure they are the same', ' boolean returnVal = true;', ' if (setOne.size () == setTwo.size ()) {', ' Collections.sort (setOne);', ' Collections.sort (setTwo);', ' for (int i = 0; i < setOne.size (); i++) {', ' if (!setOne.get (i).equals (setTwo.get (i))) {', ' returnVal = false;', ' break; ', ' }', ' }', ' } else {', ' returnVal = false;', ' }', ' ', ' // print out the result', ' System.out.println ("**** Expected:");', ' for (int i = 0; i < setOne.size (); i++) {', ' System.out.format (setOne.get (i) + " ");', ' }', ' System.out.println ("\\n**** Got:");', ' for (int i = 0; i < setTwo.size (); i++) {', ' System.out.format (setTwo.get (i) + " ");', ' }', ' System.out.println ("");', ' ', ' return returnVal;', ' }', ' ', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST SIMPLE ONE DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testOneDimRangeQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.find (query, expectedQuerySize / 2);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.find (query, expectedQuerySize / 2);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (numPoints);', ' result1 = myTree.find (query, expectedQuerySize);', ' result2 = hisTree.find (query, expectedQuerySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // like the last one, but runs a top k', ' private void testOneDimTopKQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (167);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.findKClosest (query, querySize);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (0);', ' result1 = myTree.findKClosest (query, querySize);', ' result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST MULTI-DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimRangeQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' double dist1 = 0;', ' double dist2 = 0;', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' dist1 = Math.sqrt (numDims) * expectedQuerySize / 2.0;', ' dist2 = Math.sqrt (numDims) * expectedQuerySize;', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' // do a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, (int) expectedQuerySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = myTree.findKClosest (query2, (int) expectedQuerySize);', ' ', ' // find the distance to the furthest point in both cases', ' for (int i = 0; i < (int) expectedQuerySize; i++) {', ' double newDist = result1.get (i).getKey ().getDistance (query1);', ' if (newDist > dist1)', ' dist1 = newDist;', ' newDist = result2.get (i).getKey ().getDistance (query2);', ' if (newDist > dist2)', ' dist2 = newDist;', ' }', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.find (query1, dist1);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.find (query1, dist1);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.find (query2, dist2);', ' result2 = hisTree.find (query2, dist2);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimTopKQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, querySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.findKClosest (query1, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.findKClosest (query2, querySize);', ' result2 = hisTree.findKClosest (query2, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' ', ' /**', ' * "TIER 1" TESTS', ' * NONE OF THESE REQUIRE ANY SPLITS', ' */', ' public void testEasy1() {', ' testOneDimRangeQuery (true, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy2() {', ' testOneDimRangeQuery (false, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy3() {', ' testOneDimRangeQuery (true, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy4() {', ' testOneDimRangeQuery (false, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy5() {', ' testMultiDimRangeQuery (true, 1, 5, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy6() {', ' testMultiDimRangeQuery (false, 1, 10, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy7() {', ' testMultiDimRangeQuery (true, 1, 5, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy8() {', ' testMultiDimRangeQuery (false, 1, 15, 10000, 10000, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 2" TESTS', ' * NONE OF THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testMod1() {', ' testOneDimRangeQuery (true, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod2() {', ' testOneDimRangeQuery (false, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod3() {', ' testOneDimRangeQuery (true, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod4() {', ' testOneDimRangeQuery (false, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod5() {', ' testMultiDimRangeQuery (true, 2, 5, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod6() {', ' testMultiDimRangeQuery (false, 2, 10, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod7() {', ' testMultiDimRangeQuery (true, 2, 5, 10000, 100, 1000, 10);', ' }', ' ', ' public void testMod8() {', ' testMultiDimRangeQuery (false, 2, 15, 10000, 100, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 3" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testHard1() {', ' testOneDimRangeQuery (true, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard2() {', ' testOneDimRangeQuery (false, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard3() {', ' testOneDimRangeQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard4() {', ' testOneDimRangeQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard5() {', ' testMultiDimRangeQuery (true, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard6() {', ' testMultiDimRangeQuery (false, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard7() {', ' testMultiDimRangeQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard8() {', ' testMultiDimRangeQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', ' ', ' /**', ' * "TIER 4" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE AND THEY TEST THE TOPK FUNCTIONALITY', ' */', ' ', ' public void testTopK1() {', ' testOneDimTopKQuery (true, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK2() {', ' testOneDimTopKQuery (false, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK3() {', ' testOneDimTopKQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK4() {', ' testOneDimTopKQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK5() {', ' testMultiDimTopKQuery (true, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK6() {', ' testMultiDimTopKQuery (false, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK7() {', ' testMultiDimTopKQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK8() {', ' testMultiDimTopKQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', '}'] | [] | Variable 'useMe' used at line 331 is defined at line 330 and has a Short-Range dependency.
Global_Variable 'me' used at line 331 is defined at line 327 and has a Short-Range dependency. | {} | {'Variable Short-Range': 1, 'Global_Variable Short-Range': 1} |
infilling_java | MTreeTester | 339 | 342 | ['import junit.framework.TestCase;', 'import java.util.ArrayList;', 'import java.util.Random;', 'import java.util.Collections;', '', '// this is a map from a set of keys of type PointInMetricSpace to a', '// set of data of type DataType', 'interface IMTree <Key extends IPointInMetricSpace <Key>, Data> {', ' ', ' // insert a new key/data pair into the map', ' void insert (Key keyToAdd, Data dataToAdd);', ' ', ' // find all of the key/data pairs in the map that fall within a', ' // particular distance of query point if no results are found, then', ' // an empty array is returned (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> find (Key query, double distance);', ' ', ' // find the k closest key/data pairs in the map to a particular', ' // query point ', ' //', ' // if the number of points in the map is less than k, then the', ' // returned list will have less than k pairs in it', ' //', ' // if the number of points is zero, then an empty array is returned', ' // (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> findKClosest (Key query, int k);', ' ', ' // returns the number of nodes that exist on a path from root to leaf in the tree...', ' // whtever the details of the implementation are, a tree with a single leaf node should return 1, and a tree', ' // with more than one lead node should return at least two (since it must have at least one internal node).', ' public int depth ();', ' ', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', '', 'interface IDoubleVector {', '', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '', '// this correponds to some geometric object in a metric space; the object is built out of', '// one or more points of type PointInMetricSpace', 'interface IObjectInMetricSpaceABCD <PointInMetricSpace extends IPointInMetricSpace<PointInMetricSpace>> {', ' ', ' // get the maximum distance from some point on the shape to a particular point in the metric space', ' double maxDistanceTo (PointInMetricSpace checkMe);', ' ', ' // return some arbitrary point on the interior of the geometric object', ' PointInMetricSpace getPointInInterior ();', '}', '', '', '// this interface corresponds to a point in some metric space', 'interface IPointInMetricSpace <PointInMetricSpace> {', ' ', ' // get the distance to another point', ' // ', ' // for this to work in an M-Tree, distances should be "metric" and', ' // obey the triangle inequality', ' double getDistance (PointInMetricSpace toMe);', '}', '', '// this is the basic node type in the structure', 'interface IMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> {', ' ', ' // insert a new key/data pair into the structure. The return value is a new MTreeNode if there was', ' // a split in response to the insertion, or a null if there was no split', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd);', ' ', ' // find all of the key/data pairs in the structure that fall within a particular query sphere', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query); ', ' ', ' // find the set of items closest to the given query point', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ);', ' ', ' // returns a sphere that totally encompasses everything in the node and its subtree', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', ' ', ' // returns the depth', ' public int depth ();', '}', '', '// this is a point in a particular metric space', 'class PointABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the point', ' private PointInMetricSpace me;', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return me; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return checkMe.getDistance (me); ', ' }', ' ', ' // contruct a point', ' public PointABCD (PointInMetricSpace useMe) {', ' me = useMe; ', ' }', '}', '', 'class PQueueABCD <PointInMetricSpace, DataType> {', ' ', ' // this is an object in the queue', ' private class Wrapper {', ' DataWrapper <PointInMetricSpace, DataType> myData;', ' double distance;', ' }', ' ', ' // this is the actual queue', ' ArrayList <Wrapper> myList;', ' ', ' // this is the largest distance value currently in the queue', ' double large;', ' ', ' // this is the max number of objects', ' int maxCount;', ' ', ' // create a priority queue with the speced number of slots', ' PQueueABCD (int maxCountIn) {', ' maxCount = maxCountIn;', ' myList = new ArrayList <Wrapper> ();', ' large = 9e99;', ' }', ' ', ' // get the largest distance in the queue', ' double getDist () {', ' return large;', ' }', ' ', ' // add a new object to the queue... the insertion is ignored if the distance value', ' // exceeds the largest that is in the queue and the queue is already full', ' void insert (PointInMetricSpace key, DataType data, double distance) {', ' ', ' // if we are full, remove the one with the largest distance', ' if (myList.size () == maxCount && distance < large) {', ' ', ' int badIndex = 0;', ' double maxDist = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > maxDist) {', ' maxDist = myList.get (i).distance;', ' badIndex = i;', ' }', ' }', ' ', ' myList.remove (badIndex);', ' }', ' ', ' // see if there is room', ' if (myList.size () < maxCount) {', ' ', ' // add it ', ' Wrapper newOne = new Wrapper ();', ' newOne.myData = new DataWrapper <PointInMetricSpace, DataType> (key, data);', ' newOne.distance = distance;', ' myList.add (newOne); ', ' }', ' ', ' // if we are full, reset the max distance', ' if (myList.size () == maxCount) {', ' large = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > large) {', ' large = myList.get (i).distance;', ' }', ' }', ' }', ' ', ' }', ' ', ' // extracts the contents of the queue', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> done () {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' for (int i = 0; i < myList.size (); i++) {', ' returnVal.add (myList.get (i).myData); ', ' }', ' ', ' return returnVal;', ' }', ' ', '}', '', '// this is a sphere in a particular metric space', 'class SphereABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the center of the sphere and its radius', ' private PointInMetricSpace center;', ' private double radius;', ' ', ' // build a sphere out of its center and its radius', ' public SphereABCD (PointInMetricSpace centerIn, double radiusIn) {', ' center = centerIn;', ' radius = radiusIn;', ' }', ' ', ' // increase the size of the sphere so it contains the object swallowMe', ' public void swallow (IObjectInMetricSpaceABCD <PointInMetricSpace> swallowMe) {', ' ', ' // see if we need to increase the radius to swallow this guy', ' double dist = swallowMe.maxDistanceTo (center);', ' if (dist > radius)', ' radius = dist;', ' }', ' ', ' // check to see if a sphere intersects another sphere', ' public boolean intersects (SphereABCD <PointInMetricSpace> me) {', ' return (me.center.getDistance (center) <= me.radius + radius);', ' }', ' ', ' // check to see if the sphere contains a point', ' public boolean contains (PointInMetricSpace checkMe) {', ' return (checkMe.getDistance (center) <= radius);', ' }', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return center; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return radius + checkMe.getDistance (center); ', ' }', '}', '', '', '', 'class OneDimPoint implements IPointInMetricSpace <OneDimPoint> {', ' ', ' // this is the actual double', ' Double value;', ' ', ' // construct this out of a double value', ' public OneDimPoint (double makeFromMe) {', ' value = new Double (makeFromMe);', ' }', ' ', ' // get the distance to another point', ' public double getDistance (OneDimPoint toMe) {', ' if (value > toMe.value)', ' return value - toMe.value;', ' else', ' return toMe.value - value;', ' }', ' ', '}', '', 'class MultiDimPoint implements IPointInMetricSpace <MultiDimPoint> {', ' ', ' // this is the point in a multidimensional space', ' IDoubleVector me;', ' ', ' // make this out of an IDoubleVector', ' public MultiDimPoint (IDoubleVector useMe) {', ' me = useMe;', ' }', ' ', ' // get the Euclidean distance to another point', ' public double getDistance (MultiDimPoint toMe) {', ' double distance = 0.0;', ' try {', ' for (int i = 0; i < me.getLength (); i++) {'] | [' double diff = me.getItem (i) - toMe.me.getItem (i);', ' diff *= diff;', ' distance += diff;', ' }'] | [' } catch (OutOfBoundsException e) {', ' throw new IndexOutOfBoundsException ("Can\'t compare two MultiDimPoint objects with different dimensionality!"); ', ' }', ' return Math.sqrt(distance);', ' }', ' ', '}', '// this is a leaf node', 'class LeafMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements ', ' IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myData;', ' ', ' // contructor that takes a data list and builds a node out of it', ' private LeafMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myDataIn) {', ' myData = myDataIn; ', ' }', ' ', ' // constructor that creates an empty node', ' public LeafMTreeNodeABCD () {', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> (); ', ' }', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // just add in the new data', ' myData.add (new PointABCD <PointInMetricSpace> (keyToAdd), dataToAdd);', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> newOne = myData.splitInTwo ();', ' LeafMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' myQ.insert (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData (), ', ' query.getDistance (myData.get (i).getKey ().getPointInInterior ()));', ' }', ' }', ' }', ' ', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' returnVal.add (new DataWrapper <PointInMetricSpace, DataType> (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData ()));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return 1; ', ' }', '', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', '// this silly little class is just a wrapper for a key, data pair', 'class DataWrapper <Key, Data> {', ' ', ' Key key;', ' Data data;', ' ', ' public DataWrapper (Key keyIn, Data dataIn) {', ' key = keyIn;', ' data = dataIn;', ' }', ' ', ' public Key getKey () {', ' return key;', ' }', ' ', ' public Data getData () {', ' return data;', ' }', '}', '', '', '// this is an internal node', 'class InternalMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType>', ' implements IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> myData;', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' // this constructs a new internal node that holds precisely the two nodes that are passed in', ' public InternalMTreeNodeABCD (IMTreeNodeABCD <PointInMetricSpace, DataType> refOne,', ' IMTreeNodeABCD <PointInMetricSpace, DataType> refTwo) {', ' ', ' // create a necw list and add the two guys in', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> ();', ' myData.add (refOne.getBoundingSphere (), refOne);', ' myData.add (refTwo.getBoundingSphere (), refTwo);', ' }', ' ', ' // this constructs a new node that holds the list of data that we were passed in', ' public InternalMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> useMe) {', ' myData = useMe; ', ' }', ' ', ' // from the interface', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // find the best child; this is the one we are closest to', ' double bestDist = 9e99;', ' int bestIndex = 0;', ' for (int i = 0; i < myData.size (); i++) {', ' ', ' double newDist = myData.get (i).getKey ().getPointInInterior ().getDistance (keyToAdd);', ' if (newDist < bestDist) {', ' bestDist = newDist;', ' bestIndex = i;', ' }', ' }', ' ', ' // do the recursive insert', ' IMTreeNodeABCD <PointInMetricSpace, DataType> newRef = myData.get (bestIndex).getData ().insert (keyToAdd, dataToAdd);', ' ', ' // if we got something back, then there was a split, so add the new node into our list', ' if (newRef != null) {', ' myData.add (newRef.getBoundingSphere (), newRef);', ' }', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> newOne = myData.splitInTwo ();', ' InternalMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.intersects (myData.get (i).getKey ())) {', ' myData.get (i).getData ().findKClosest (query, myQ);', ' }', ' }', ' }', ' ', ' // from the interface', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.intersects (myData.get (i).getKey ())) {', ' returnVal.addAll (myData.get (i).getData ().find (query));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return myData.get (0).getData ().depth () + 1; ', ' }', ' ', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', 'abstract class AMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> implements IMetricDataListABCD <PointInMetricSpace,KeyType, DataType> {', '', ' // this is the data that is actually stored in the list', ' private ArrayList <DataWrapper <KeyType, DataType>> myData;', ' ', ' // this is the sphere that bounds everything in the list', ' private SphereABCD <PointInMetricSpace> myBoundingSphere;', ' ', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myBoundingSphere; ', ' }', ' ', ' public int size () {', ' if (myData != null)', ' return myData.size (); ', ' else', ' return 0;', ' }', ' ', ' public DataWrapper <KeyType, DataType> get (int pos) {', ' return myData.get (pos);', ' }', ' ', ' public void replaceKey (int pos, KeyType keyToAdd) {', ' DataWrapper <KeyType, DataType> temp = myData.remove (pos);', ' DataWrapper <KeyType, DataType> newOne = new DataWrapper <KeyType, DataType> (keyToAdd, temp.getData ());', ' myData.add (pos, newOne);', ' }', ' ', ' public void add (KeyType keyToAdd, DataType dataToAdd) {', ' ', ' // if this is the first add, then set everyone up', ' if (myData == null) {', ' PointInMetricSpace myCentroid = keyToAdd.getPointInInterior ();', ' myBoundingSphere = new SphereABCD <PointInMetricSpace> (myCentroid, keyToAdd.maxDistanceTo (myCentroid));', ' myData = new ArrayList <DataWrapper <KeyType, DataType>> ();', ' ', ' // otherwise, extend the sphere if needed', ' } else {', ' myBoundingSphere.swallow (keyToAdd);', ' }', ' ', ' // add the data', ' myData.add (new DataWrapper <KeyType, DataType> (keyToAdd, dataToAdd));', ' }', ' ', ' // we want to potentially allow many implementations of the splitting lalgorithm', ' abstract public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // this is here so the actual splitting algorithn can access the list and change the sphere', ' protected ArrayList <DataWrapper <KeyType, DataType>> getList () {', ' return myData;', ' }', ' ', ' // this is here so the splitting algorithm can modify the list and the sphere', ' protected void replaceGuts (AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> withMe) {', ' myData = withMe.myData;', ' myBoundingSphere = withMe.myBoundingSphere;', ' }', ' ', '}', '', '// this is a particular implementation of the metric data list that uses a simple quadratic clustering', '// algorithm to perform a list split. It picks two "seeds" (the most distant objects) and then repeatedly', '// adds to the two new lists by choosing the objects closest to the seeds', 'class ChrisMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> extends AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> {', '', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo () {', ' ', ' // first, we need to find the two most distant points in the list', ' ArrayList <DataWrapper <KeyType, DataType>> myData = getList ();', ' int bestI = 0, bestJ = 0;', ' double maxDist = -1.0;', ' for (int i = 0; i < myData.size (); i++) {', ' for (int j = i + 1; j < myData.size (); j++) {', ' ', ' // get the two keys', ' DataWrapper <KeyType, DataType> pointOne = myData.get (i);', ' DataWrapper <KeyType, DataType> pointTwo = myData.get (j);', ' ', ' // find the difference between them', ' double curDist = pointOne.getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', '', ' // see if it is the biggest', ' if (curDist > maxDist) {', ' maxDist = curDist;', ' bestI = i;', ' bestJ = j;', ' }', ' }', ' }', ' ', ' // now, we have the best two points; those are seeds for the clustering', ' DataWrapper <KeyType, DataType> pointOne = myData.remove (bestI);', ' DataWrapper <KeyType, DataType> pointTwo = myData.remove (bestJ - 1);', ' ', ' // these are the two new lists', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listOne = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listTwo = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' ', ' // put the two seeds in', ' listOne.add (pointOne.getKey (), pointOne.getData ());', ' listTwo.add (pointTwo.getKey (), pointTwo.getData ());', ' ', ' // and add everyone else in', ' while (myData.size () != 0) {', ' ', ' // find the one closest to the first seed', ' int bestIndex = 0;', ' double bestDist = 9e99;', ' ', ' // loop thru all of the candidate data objects', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listOne.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' ', ' // break if no more data', ' if (myData.size () == 0)', ' break;', ' ', ' // loop thru all of the candidate data objects', ' bestDist = 9e99;', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listTwo.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' }', ' ', ' // now we replace our own guts with the first list', ' replaceGuts (listOne);', ' ', ' // and return the other list', ' return listTwo;', ' }', '}', '', 'interface IMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> {', ' ', ' // add a new pair to the list', ' public void add (KeyType keyToAdd, DataType dataToAdd);', ' ', ' // replace a key at the indicated position', ' public void replaceKey (int pos, KeyType keyToAdd);', ' ', ' // get the key, data pair that resides at a particular position', ' public DataWrapper <KeyType, DataType> get (int pos);', ' ', ' // return the number of items in the list', ' public int size ();', ' ', ' // split the list in two, using some clutering algorithm', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // get a sphere that totally bounds all of the objects in the list', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class MTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public MTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class SCMTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public SCMTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', '', 'public class MTreeTester extends TestCase {', ' ', ' // compare two lists of strings to see if the contents are the same', ' private boolean compareStringSets (ArrayList <String> setOne, ArrayList <String> setTwo) {', ' ', ' // sort the sets and make sure they are the same', ' boolean returnVal = true;', ' if (setOne.size () == setTwo.size ()) {', ' Collections.sort (setOne);', ' Collections.sort (setTwo);', ' for (int i = 0; i < setOne.size (); i++) {', ' if (!setOne.get (i).equals (setTwo.get (i))) {', ' returnVal = false;', ' break; ', ' }', ' }', ' } else {', ' returnVal = false;', ' }', ' ', ' // print out the result', ' System.out.println ("**** Expected:");', ' for (int i = 0; i < setOne.size (); i++) {', ' System.out.format (setOne.get (i) + " ");', ' }', ' System.out.println ("\\n**** Got:");', ' for (int i = 0; i < setTwo.size (); i++) {', ' System.out.format (setTwo.get (i) + " ");', ' }', ' System.out.println ("");', ' ', ' return returnVal;', ' }', ' ', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST SIMPLE ONE DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testOneDimRangeQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.find (query, expectedQuerySize / 2);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.find (query, expectedQuerySize / 2);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (numPoints);', ' result1 = myTree.find (query, expectedQuerySize);', ' result2 = hisTree.find (query, expectedQuerySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // like the last one, but runs a top k', ' private void testOneDimTopKQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (167);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.findKClosest (query, querySize);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (0);', ' result1 = myTree.findKClosest (query, querySize);', ' result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST MULTI-DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimRangeQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' double dist1 = 0;', ' double dist2 = 0;', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' dist1 = Math.sqrt (numDims) * expectedQuerySize / 2.0;', ' dist2 = Math.sqrt (numDims) * expectedQuerySize;', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' // do a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, (int) expectedQuerySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = myTree.findKClosest (query2, (int) expectedQuerySize);', ' ', ' // find the distance to the furthest point in both cases', ' for (int i = 0; i < (int) expectedQuerySize; i++) {', ' double newDist = result1.get (i).getKey ().getDistance (query1);', ' if (newDist > dist1)', ' dist1 = newDist;', ' newDist = result2.get (i).getKey ().getDistance (query2);', ' if (newDist > dist2)', ' dist2 = newDist;', ' }', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.find (query1, dist1);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.find (query1, dist1);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.find (query2, dist2);', ' result2 = hisTree.find (query2, dist2);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimTopKQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, querySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.findKClosest (query1, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.findKClosest (query2, querySize);', ' result2 = hisTree.findKClosest (query2, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' ', ' /**', ' * "TIER 1" TESTS', ' * NONE OF THESE REQUIRE ANY SPLITS', ' */', ' public void testEasy1() {', ' testOneDimRangeQuery (true, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy2() {', ' testOneDimRangeQuery (false, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy3() {', ' testOneDimRangeQuery (true, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy4() {', ' testOneDimRangeQuery (false, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy5() {', ' testMultiDimRangeQuery (true, 1, 5, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy6() {', ' testMultiDimRangeQuery (false, 1, 10, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy7() {', ' testMultiDimRangeQuery (true, 1, 5, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy8() {', ' testMultiDimRangeQuery (false, 1, 15, 10000, 10000, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 2" TESTS', ' * NONE OF THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testMod1() {', ' testOneDimRangeQuery (true, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod2() {', ' testOneDimRangeQuery (false, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod3() {', ' testOneDimRangeQuery (true, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod4() {', ' testOneDimRangeQuery (false, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod5() {', ' testMultiDimRangeQuery (true, 2, 5, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod6() {', ' testMultiDimRangeQuery (false, 2, 10, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod7() {', ' testMultiDimRangeQuery (true, 2, 5, 10000, 100, 1000, 10);', ' }', ' ', ' public void testMod8() {', ' testMultiDimRangeQuery (false, 2, 15, 10000, 100, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 3" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testHard1() {', ' testOneDimRangeQuery (true, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard2() {', ' testOneDimRangeQuery (false, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard3() {', ' testOneDimRangeQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard4() {', ' testOneDimRangeQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard5() {', ' testMultiDimRangeQuery (true, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard6() {', ' testMultiDimRangeQuery (false, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard7() {', ' testMultiDimRangeQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard8() {', ' testMultiDimRangeQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', ' ', ' /**', ' * "TIER 4" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE AND THEY TEST THE TOPK FUNCTIONALITY', ' */', ' ', ' public void testTopK1() {', ' testOneDimTopKQuery (true, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK2() {', ' testOneDimTopKQuery (false, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK3() {', ' testOneDimTopKQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK4() {', ' testOneDimTopKQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK5() {', ' testMultiDimTopKQuery (true, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK6() {', ' testMultiDimTopKQuery (false, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK7() {', ' testMultiDimTopKQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK8() {', ' testMultiDimTopKQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', '}'] | [{'reason_category': 'Loop Body', 'usage_line': 339}, {'reason_category': 'Loop Body', 'usage_line': 340}, {'reason_category': 'Loop Body', 'usage_line': 341}, {'reason_category': 'Loop Body', 'usage_line': 342}] | Global_Variable 'me' used at line 339 is defined at line 327 and has a Medium-Range dependency.
Variable 'i' used at line 339 is defined at line 338 and has a Short-Range dependency.
Variable 'diff' used at line 340 is defined at line 339 and has a Short-Range dependency.
Variable 'diff' used at line 341 is defined at line 340 and has a Short-Range dependency.
Variable 'distance' used at line 341 is defined at line 336 and has a Short-Range dependency. | {'Loop Body': 4} | {'Global_Variable Medium-Range': 1, 'Variable Short-Range': 4} |
infilling_java | MTreeTester | 359 | 360 | ['import junit.framework.TestCase;', 'import java.util.ArrayList;', 'import java.util.Random;', 'import java.util.Collections;', '', '// this is a map from a set of keys of type PointInMetricSpace to a', '// set of data of type DataType', 'interface IMTree <Key extends IPointInMetricSpace <Key>, Data> {', ' ', ' // insert a new key/data pair into the map', ' void insert (Key keyToAdd, Data dataToAdd);', ' ', ' // find all of the key/data pairs in the map that fall within a', ' // particular distance of query point if no results are found, then', ' // an empty array is returned (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> find (Key query, double distance);', ' ', ' // find the k closest key/data pairs in the map to a particular', ' // query point ', ' //', ' // if the number of points in the map is less than k, then the', ' // returned list will have less than k pairs in it', ' //', ' // if the number of points is zero, then an empty array is returned', ' // (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> findKClosest (Key query, int k);', ' ', ' // returns the number of nodes that exist on a path from root to leaf in the tree...', ' // whtever the details of the implementation are, a tree with a single leaf node should return 1, and a tree', ' // with more than one lead node should return at least two (since it must have at least one internal node).', ' public int depth ();', ' ', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', '', 'interface IDoubleVector {', '', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '', '// this correponds to some geometric object in a metric space; the object is built out of', '// one or more points of type PointInMetricSpace', 'interface IObjectInMetricSpaceABCD <PointInMetricSpace extends IPointInMetricSpace<PointInMetricSpace>> {', ' ', ' // get the maximum distance from some point on the shape to a particular point in the metric space', ' double maxDistanceTo (PointInMetricSpace checkMe);', ' ', ' // return some arbitrary point on the interior of the geometric object', ' PointInMetricSpace getPointInInterior ();', '}', '', '', '// this interface corresponds to a point in some metric space', 'interface IPointInMetricSpace <PointInMetricSpace> {', ' ', ' // get the distance to another point', ' // ', ' // for this to work in an M-Tree, distances should be "metric" and', ' // obey the triangle inequality', ' double getDistance (PointInMetricSpace toMe);', '}', '', '// this is the basic node type in the structure', 'interface IMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> {', ' ', ' // insert a new key/data pair into the structure. The return value is a new MTreeNode if there was', ' // a split in response to the insertion, or a null if there was no split', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd);', ' ', ' // find all of the key/data pairs in the structure that fall within a particular query sphere', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query); ', ' ', ' // find the set of items closest to the given query point', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ);', ' ', ' // returns a sphere that totally encompasses everything in the node and its subtree', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', ' ', ' // returns the depth', ' public int depth ();', '}', '', '// this is a point in a particular metric space', 'class PointABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the point', ' private PointInMetricSpace me;', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return me; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return checkMe.getDistance (me); ', ' }', ' ', ' // contruct a point', ' public PointABCD (PointInMetricSpace useMe) {', ' me = useMe; ', ' }', '}', '', 'class PQueueABCD <PointInMetricSpace, DataType> {', ' ', ' // this is an object in the queue', ' private class Wrapper {', ' DataWrapper <PointInMetricSpace, DataType> myData;', ' double distance;', ' }', ' ', ' // this is the actual queue', ' ArrayList <Wrapper> myList;', ' ', ' // this is the largest distance value currently in the queue', ' double large;', ' ', ' // this is the max number of objects', ' int maxCount;', ' ', ' // create a priority queue with the speced number of slots', ' PQueueABCD (int maxCountIn) {', ' maxCount = maxCountIn;', ' myList = new ArrayList <Wrapper> ();', ' large = 9e99;', ' }', ' ', ' // get the largest distance in the queue', ' double getDist () {', ' return large;', ' }', ' ', ' // add a new object to the queue... the insertion is ignored if the distance value', ' // exceeds the largest that is in the queue and the queue is already full', ' void insert (PointInMetricSpace key, DataType data, double distance) {', ' ', ' // if we are full, remove the one with the largest distance', ' if (myList.size () == maxCount && distance < large) {', ' ', ' int badIndex = 0;', ' double maxDist = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > maxDist) {', ' maxDist = myList.get (i).distance;', ' badIndex = i;', ' }', ' }', ' ', ' myList.remove (badIndex);', ' }', ' ', ' // see if there is room', ' if (myList.size () < maxCount) {', ' ', ' // add it ', ' Wrapper newOne = new Wrapper ();', ' newOne.myData = new DataWrapper <PointInMetricSpace, DataType> (key, data);', ' newOne.distance = distance;', ' myList.add (newOne); ', ' }', ' ', ' // if we are full, reset the max distance', ' if (myList.size () == maxCount) {', ' large = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > large) {', ' large = myList.get (i).distance;', ' }', ' }', ' }', ' ', ' }', ' ', ' // extracts the contents of the queue', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> done () {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' for (int i = 0; i < myList.size (); i++) {', ' returnVal.add (myList.get (i).myData); ', ' }', ' ', ' return returnVal;', ' }', ' ', '}', '', '// this is a sphere in a particular metric space', 'class SphereABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the center of the sphere and its radius', ' private PointInMetricSpace center;', ' private double radius;', ' ', ' // build a sphere out of its center and its radius', ' public SphereABCD (PointInMetricSpace centerIn, double radiusIn) {', ' center = centerIn;', ' radius = radiusIn;', ' }', ' ', ' // increase the size of the sphere so it contains the object swallowMe', ' public void swallow (IObjectInMetricSpaceABCD <PointInMetricSpace> swallowMe) {', ' ', ' // see if we need to increase the radius to swallow this guy', ' double dist = swallowMe.maxDistanceTo (center);', ' if (dist > radius)', ' radius = dist;', ' }', ' ', ' // check to see if a sphere intersects another sphere', ' public boolean intersects (SphereABCD <PointInMetricSpace> me) {', ' return (me.center.getDistance (center) <= me.radius + radius);', ' }', ' ', ' // check to see if the sphere contains a point', ' public boolean contains (PointInMetricSpace checkMe) {', ' return (checkMe.getDistance (center) <= radius);', ' }', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return center; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return radius + checkMe.getDistance (center); ', ' }', '}', '', '', '', 'class OneDimPoint implements IPointInMetricSpace <OneDimPoint> {', ' ', ' // this is the actual double', ' Double value;', ' ', ' // construct this out of a double value', ' public OneDimPoint (double makeFromMe) {', ' value = new Double (makeFromMe);', ' }', ' ', ' // get the distance to another point', ' public double getDistance (OneDimPoint toMe) {', ' if (value > toMe.value)', ' return value - toMe.value;', ' else', ' return toMe.value - value;', ' }', ' ', '}', '', 'class MultiDimPoint implements IPointInMetricSpace <MultiDimPoint> {', ' ', ' // this is the point in a multidimensional space', ' IDoubleVector me;', ' ', ' // make this out of an IDoubleVector', ' public MultiDimPoint (IDoubleVector useMe) {', ' me = useMe;', ' }', ' ', ' // get the Euclidean distance to another point', ' public double getDistance (MultiDimPoint toMe) {', ' double distance = 0.0;', ' try {', ' for (int i = 0; i < me.getLength (); i++) {', ' double diff = me.getItem (i) - toMe.me.getItem (i);', ' diff *= diff;', ' distance += diff;', ' }', ' } catch (OutOfBoundsException e) {', ' throw new IndexOutOfBoundsException ("Can\'t compare two MultiDimPoint objects with different dimensionality!"); ', ' }', ' return Math.sqrt(distance);', ' }', ' ', '}', '// this is a leaf node', 'class LeafMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements ', ' IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myData;', ' ', ' // contructor that takes a data list and builds a node out of it', ' private LeafMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myDataIn) {'] | [' myData = myDataIn; ', ' }'] | [' ', ' // constructor that creates an empty node', ' public LeafMTreeNodeABCD () {', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> (); ', ' }', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // just add in the new data', ' myData.add (new PointABCD <PointInMetricSpace> (keyToAdd), dataToAdd);', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> newOne = myData.splitInTwo ();', ' LeafMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' myQ.insert (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData (), ', ' query.getDistance (myData.get (i).getKey ().getPointInInterior ()));', ' }', ' }', ' }', ' ', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' returnVal.add (new DataWrapper <PointInMetricSpace, DataType> (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData ()));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return 1; ', ' }', '', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', '// this silly little class is just a wrapper for a key, data pair', 'class DataWrapper <Key, Data> {', ' ', ' Key key;', ' Data data;', ' ', ' public DataWrapper (Key keyIn, Data dataIn) {', ' key = keyIn;', ' data = dataIn;', ' }', ' ', ' public Key getKey () {', ' return key;', ' }', ' ', ' public Data getData () {', ' return data;', ' }', '}', '', '', '// this is an internal node', 'class InternalMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType>', ' implements IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> myData;', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' // this constructs a new internal node that holds precisely the two nodes that are passed in', ' public InternalMTreeNodeABCD (IMTreeNodeABCD <PointInMetricSpace, DataType> refOne,', ' IMTreeNodeABCD <PointInMetricSpace, DataType> refTwo) {', ' ', ' // create a necw list and add the two guys in', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> ();', ' myData.add (refOne.getBoundingSphere (), refOne);', ' myData.add (refTwo.getBoundingSphere (), refTwo);', ' }', ' ', ' // this constructs a new node that holds the list of data that we were passed in', ' public InternalMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> useMe) {', ' myData = useMe; ', ' }', ' ', ' // from the interface', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // find the best child; this is the one we are closest to', ' double bestDist = 9e99;', ' int bestIndex = 0;', ' for (int i = 0; i < myData.size (); i++) {', ' ', ' double newDist = myData.get (i).getKey ().getPointInInterior ().getDistance (keyToAdd);', ' if (newDist < bestDist) {', ' bestDist = newDist;', ' bestIndex = i;', ' }', ' }', ' ', ' // do the recursive insert', ' IMTreeNodeABCD <PointInMetricSpace, DataType> newRef = myData.get (bestIndex).getData ().insert (keyToAdd, dataToAdd);', ' ', ' // if we got something back, then there was a split, so add the new node into our list', ' if (newRef != null) {', ' myData.add (newRef.getBoundingSphere (), newRef);', ' }', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> newOne = myData.splitInTwo ();', ' InternalMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.intersects (myData.get (i).getKey ())) {', ' myData.get (i).getData ().findKClosest (query, myQ);', ' }', ' }', ' }', ' ', ' // from the interface', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.intersects (myData.get (i).getKey ())) {', ' returnVal.addAll (myData.get (i).getData ().find (query));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return myData.get (0).getData ().depth () + 1; ', ' }', ' ', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', 'abstract class AMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> implements IMetricDataListABCD <PointInMetricSpace,KeyType, DataType> {', '', ' // this is the data that is actually stored in the list', ' private ArrayList <DataWrapper <KeyType, DataType>> myData;', ' ', ' // this is the sphere that bounds everything in the list', ' private SphereABCD <PointInMetricSpace> myBoundingSphere;', ' ', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myBoundingSphere; ', ' }', ' ', ' public int size () {', ' if (myData != null)', ' return myData.size (); ', ' else', ' return 0;', ' }', ' ', ' public DataWrapper <KeyType, DataType> get (int pos) {', ' return myData.get (pos);', ' }', ' ', ' public void replaceKey (int pos, KeyType keyToAdd) {', ' DataWrapper <KeyType, DataType> temp = myData.remove (pos);', ' DataWrapper <KeyType, DataType> newOne = new DataWrapper <KeyType, DataType> (keyToAdd, temp.getData ());', ' myData.add (pos, newOne);', ' }', ' ', ' public void add (KeyType keyToAdd, DataType dataToAdd) {', ' ', ' // if this is the first add, then set everyone up', ' if (myData == null) {', ' PointInMetricSpace myCentroid = keyToAdd.getPointInInterior ();', ' myBoundingSphere = new SphereABCD <PointInMetricSpace> (myCentroid, keyToAdd.maxDistanceTo (myCentroid));', ' myData = new ArrayList <DataWrapper <KeyType, DataType>> ();', ' ', ' // otherwise, extend the sphere if needed', ' } else {', ' myBoundingSphere.swallow (keyToAdd);', ' }', ' ', ' // add the data', ' myData.add (new DataWrapper <KeyType, DataType> (keyToAdd, dataToAdd));', ' }', ' ', ' // we want to potentially allow many implementations of the splitting lalgorithm', ' abstract public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // this is here so the actual splitting algorithn can access the list and change the sphere', ' protected ArrayList <DataWrapper <KeyType, DataType>> getList () {', ' return myData;', ' }', ' ', ' // this is here so the splitting algorithm can modify the list and the sphere', ' protected void replaceGuts (AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> withMe) {', ' myData = withMe.myData;', ' myBoundingSphere = withMe.myBoundingSphere;', ' }', ' ', '}', '', '// this is a particular implementation of the metric data list that uses a simple quadratic clustering', '// algorithm to perform a list split. It picks two "seeds" (the most distant objects) and then repeatedly', '// adds to the two new lists by choosing the objects closest to the seeds', 'class ChrisMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> extends AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> {', '', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo () {', ' ', ' // first, we need to find the two most distant points in the list', ' ArrayList <DataWrapper <KeyType, DataType>> myData = getList ();', ' int bestI = 0, bestJ = 0;', ' double maxDist = -1.0;', ' for (int i = 0; i < myData.size (); i++) {', ' for (int j = i + 1; j < myData.size (); j++) {', ' ', ' // get the two keys', ' DataWrapper <KeyType, DataType> pointOne = myData.get (i);', ' DataWrapper <KeyType, DataType> pointTwo = myData.get (j);', ' ', ' // find the difference between them', ' double curDist = pointOne.getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', '', ' // see if it is the biggest', ' if (curDist > maxDist) {', ' maxDist = curDist;', ' bestI = i;', ' bestJ = j;', ' }', ' }', ' }', ' ', ' // now, we have the best two points; those are seeds for the clustering', ' DataWrapper <KeyType, DataType> pointOne = myData.remove (bestI);', ' DataWrapper <KeyType, DataType> pointTwo = myData.remove (bestJ - 1);', ' ', ' // these are the two new lists', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listOne = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listTwo = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' ', ' // put the two seeds in', ' listOne.add (pointOne.getKey (), pointOne.getData ());', ' listTwo.add (pointTwo.getKey (), pointTwo.getData ());', ' ', ' // and add everyone else in', ' while (myData.size () != 0) {', ' ', ' // find the one closest to the first seed', ' int bestIndex = 0;', ' double bestDist = 9e99;', ' ', ' // loop thru all of the candidate data objects', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listOne.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' ', ' // break if no more data', ' if (myData.size () == 0)', ' break;', ' ', ' // loop thru all of the candidate data objects', ' bestDist = 9e99;', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listTwo.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' }', ' ', ' // now we replace our own guts with the first list', ' replaceGuts (listOne);', ' ', ' // and return the other list', ' return listTwo;', ' }', '}', '', 'interface IMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> {', ' ', ' // add a new pair to the list', ' public void add (KeyType keyToAdd, DataType dataToAdd);', ' ', ' // replace a key at the indicated position', ' public void replaceKey (int pos, KeyType keyToAdd);', ' ', ' // get the key, data pair that resides at a particular position', ' public DataWrapper <KeyType, DataType> get (int pos);', ' ', ' // return the number of items in the list', ' public int size ();', ' ', ' // split the list in two, using some clutering algorithm', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // get a sphere that totally bounds all of the objects in the list', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class MTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public MTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class SCMTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public SCMTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', '', 'public class MTreeTester extends TestCase {', ' ', ' // compare two lists of strings to see if the contents are the same', ' private boolean compareStringSets (ArrayList <String> setOne, ArrayList <String> setTwo) {', ' ', ' // sort the sets and make sure they are the same', ' boolean returnVal = true;', ' if (setOne.size () == setTwo.size ()) {', ' Collections.sort (setOne);', ' Collections.sort (setTwo);', ' for (int i = 0; i < setOne.size (); i++) {', ' if (!setOne.get (i).equals (setTwo.get (i))) {', ' returnVal = false;', ' break; ', ' }', ' }', ' } else {', ' returnVal = false;', ' }', ' ', ' // print out the result', ' System.out.println ("**** Expected:");', ' for (int i = 0; i < setOne.size (); i++) {', ' System.out.format (setOne.get (i) + " ");', ' }', ' System.out.println ("\\n**** Got:");', ' for (int i = 0; i < setTwo.size (); i++) {', ' System.out.format (setTwo.get (i) + " ");', ' }', ' System.out.println ("");', ' ', ' return returnVal;', ' }', ' ', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST SIMPLE ONE DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testOneDimRangeQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.find (query, expectedQuerySize / 2);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.find (query, expectedQuerySize / 2);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (numPoints);', ' result1 = myTree.find (query, expectedQuerySize);', ' result2 = hisTree.find (query, expectedQuerySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // like the last one, but runs a top k', ' private void testOneDimTopKQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (167);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.findKClosest (query, querySize);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (0);', ' result1 = myTree.findKClosest (query, querySize);', ' result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST MULTI-DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimRangeQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' double dist1 = 0;', ' double dist2 = 0;', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' dist1 = Math.sqrt (numDims) * expectedQuerySize / 2.0;', ' dist2 = Math.sqrt (numDims) * expectedQuerySize;', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' // do a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, (int) expectedQuerySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = myTree.findKClosest (query2, (int) expectedQuerySize);', ' ', ' // find the distance to the furthest point in both cases', ' for (int i = 0; i < (int) expectedQuerySize; i++) {', ' double newDist = result1.get (i).getKey ().getDistance (query1);', ' if (newDist > dist1)', ' dist1 = newDist;', ' newDist = result2.get (i).getKey ().getDistance (query2);', ' if (newDist > dist2)', ' dist2 = newDist;', ' }', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.find (query1, dist1);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.find (query1, dist1);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.find (query2, dist2);', ' result2 = hisTree.find (query2, dist2);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimTopKQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, querySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.findKClosest (query1, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.findKClosest (query2, querySize);', ' result2 = hisTree.findKClosest (query2, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' ', ' /**', ' * "TIER 1" TESTS', ' * NONE OF THESE REQUIRE ANY SPLITS', ' */', ' public void testEasy1() {', ' testOneDimRangeQuery (true, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy2() {', ' testOneDimRangeQuery (false, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy3() {', ' testOneDimRangeQuery (true, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy4() {', ' testOneDimRangeQuery (false, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy5() {', ' testMultiDimRangeQuery (true, 1, 5, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy6() {', ' testMultiDimRangeQuery (false, 1, 10, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy7() {', ' testMultiDimRangeQuery (true, 1, 5, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy8() {', ' testMultiDimRangeQuery (false, 1, 15, 10000, 10000, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 2" TESTS', ' * NONE OF THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testMod1() {', ' testOneDimRangeQuery (true, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod2() {', ' testOneDimRangeQuery (false, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod3() {', ' testOneDimRangeQuery (true, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod4() {', ' testOneDimRangeQuery (false, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod5() {', ' testMultiDimRangeQuery (true, 2, 5, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod6() {', ' testMultiDimRangeQuery (false, 2, 10, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod7() {', ' testMultiDimRangeQuery (true, 2, 5, 10000, 100, 1000, 10);', ' }', ' ', ' public void testMod8() {', ' testMultiDimRangeQuery (false, 2, 15, 10000, 100, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 3" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testHard1() {', ' testOneDimRangeQuery (true, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard2() {', ' testOneDimRangeQuery (false, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard3() {', ' testOneDimRangeQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard4() {', ' testOneDimRangeQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard5() {', ' testMultiDimRangeQuery (true, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard6() {', ' testMultiDimRangeQuery (false, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard7() {', ' testMultiDimRangeQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard8() {', ' testMultiDimRangeQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', ' ', ' /**', ' * "TIER 4" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE AND THEY TEST THE TOPK FUNCTIONALITY', ' */', ' ', ' public void testTopK1() {', ' testOneDimTopKQuery (true, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK2() {', ' testOneDimTopKQuery (false, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK3() {', ' testOneDimTopKQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK4() {', ' testOneDimTopKQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK5() {', ' testMultiDimTopKQuery (true, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK6() {', ' testMultiDimTopKQuery (false, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK7() {', ' testMultiDimTopKQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK8() {', ' testMultiDimTopKQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', '}'] | [] | Variable 'myDataIn' used at line 359 is defined at line 358 and has a Short-Range dependency.
Global_Variable 'myData' used at line 359 is defined at line 355 and has a Short-Range dependency. | {} | {'Variable Short-Range': 1, 'Global_Variable Short-Range': 1} |
infilling_java | MTreeTester | 364 | 365 | ['import junit.framework.TestCase;', 'import java.util.ArrayList;', 'import java.util.Random;', 'import java.util.Collections;', '', '// this is a map from a set of keys of type PointInMetricSpace to a', '// set of data of type DataType', 'interface IMTree <Key extends IPointInMetricSpace <Key>, Data> {', ' ', ' // insert a new key/data pair into the map', ' void insert (Key keyToAdd, Data dataToAdd);', ' ', ' // find all of the key/data pairs in the map that fall within a', ' // particular distance of query point if no results are found, then', ' // an empty array is returned (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> find (Key query, double distance);', ' ', ' // find the k closest key/data pairs in the map to a particular', ' // query point ', ' //', ' // if the number of points in the map is less than k, then the', ' // returned list will have less than k pairs in it', ' //', ' // if the number of points is zero, then an empty array is returned', ' // (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> findKClosest (Key query, int k);', ' ', ' // returns the number of nodes that exist on a path from root to leaf in the tree...', ' // whtever the details of the implementation are, a tree with a single leaf node should return 1, and a tree', ' // with more than one lead node should return at least two (since it must have at least one internal node).', ' public int depth ();', ' ', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', '', 'interface IDoubleVector {', '', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '', '// this correponds to some geometric object in a metric space; the object is built out of', '// one or more points of type PointInMetricSpace', 'interface IObjectInMetricSpaceABCD <PointInMetricSpace extends IPointInMetricSpace<PointInMetricSpace>> {', ' ', ' // get the maximum distance from some point on the shape to a particular point in the metric space', ' double maxDistanceTo (PointInMetricSpace checkMe);', ' ', ' // return some arbitrary point on the interior of the geometric object', ' PointInMetricSpace getPointInInterior ();', '}', '', '', '// this interface corresponds to a point in some metric space', 'interface IPointInMetricSpace <PointInMetricSpace> {', ' ', ' // get the distance to another point', ' // ', ' // for this to work in an M-Tree, distances should be "metric" and', ' // obey the triangle inequality', ' double getDistance (PointInMetricSpace toMe);', '}', '', '// this is the basic node type in the structure', 'interface IMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> {', ' ', ' // insert a new key/data pair into the structure. The return value is a new MTreeNode if there was', ' // a split in response to the insertion, or a null if there was no split', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd);', ' ', ' // find all of the key/data pairs in the structure that fall within a particular query sphere', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query); ', ' ', ' // find the set of items closest to the given query point', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ);', ' ', ' // returns a sphere that totally encompasses everything in the node and its subtree', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', ' ', ' // returns the depth', ' public int depth ();', '}', '', '// this is a point in a particular metric space', 'class PointABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the point', ' private PointInMetricSpace me;', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return me; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return checkMe.getDistance (me); ', ' }', ' ', ' // contruct a point', ' public PointABCD (PointInMetricSpace useMe) {', ' me = useMe; ', ' }', '}', '', 'class PQueueABCD <PointInMetricSpace, DataType> {', ' ', ' // this is an object in the queue', ' private class Wrapper {', ' DataWrapper <PointInMetricSpace, DataType> myData;', ' double distance;', ' }', ' ', ' // this is the actual queue', ' ArrayList <Wrapper> myList;', ' ', ' // this is the largest distance value currently in the queue', ' double large;', ' ', ' // this is the max number of objects', ' int maxCount;', ' ', ' // create a priority queue with the speced number of slots', ' PQueueABCD (int maxCountIn) {', ' maxCount = maxCountIn;', ' myList = new ArrayList <Wrapper> ();', ' large = 9e99;', ' }', ' ', ' // get the largest distance in the queue', ' double getDist () {', ' return large;', ' }', ' ', ' // add a new object to the queue... the insertion is ignored if the distance value', ' // exceeds the largest that is in the queue and the queue is already full', ' void insert (PointInMetricSpace key, DataType data, double distance) {', ' ', ' // if we are full, remove the one with the largest distance', ' if (myList.size () == maxCount && distance < large) {', ' ', ' int badIndex = 0;', ' double maxDist = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > maxDist) {', ' maxDist = myList.get (i).distance;', ' badIndex = i;', ' }', ' }', ' ', ' myList.remove (badIndex);', ' }', ' ', ' // see if there is room', ' if (myList.size () < maxCount) {', ' ', ' // add it ', ' Wrapper newOne = new Wrapper ();', ' newOne.myData = new DataWrapper <PointInMetricSpace, DataType> (key, data);', ' newOne.distance = distance;', ' myList.add (newOne); ', ' }', ' ', ' // if we are full, reset the max distance', ' if (myList.size () == maxCount) {', ' large = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > large) {', ' large = myList.get (i).distance;', ' }', ' }', ' }', ' ', ' }', ' ', ' // extracts the contents of the queue', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> done () {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' for (int i = 0; i < myList.size (); i++) {', ' returnVal.add (myList.get (i).myData); ', ' }', ' ', ' return returnVal;', ' }', ' ', '}', '', '// this is a sphere in a particular metric space', 'class SphereABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the center of the sphere and its radius', ' private PointInMetricSpace center;', ' private double radius;', ' ', ' // build a sphere out of its center and its radius', ' public SphereABCD (PointInMetricSpace centerIn, double radiusIn) {', ' center = centerIn;', ' radius = radiusIn;', ' }', ' ', ' // increase the size of the sphere so it contains the object swallowMe', ' public void swallow (IObjectInMetricSpaceABCD <PointInMetricSpace> swallowMe) {', ' ', ' // see if we need to increase the radius to swallow this guy', ' double dist = swallowMe.maxDistanceTo (center);', ' if (dist > radius)', ' radius = dist;', ' }', ' ', ' // check to see if a sphere intersects another sphere', ' public boolean intersects (SphereABCD <PointInMetricSpace> me) {', ' return (me.center.getDistance (center) <= me.radius + radius);', ' }', ' ', ' // check to see if the sphere contains a point', ' public boolean contains (PointInMetricSpace checkMe) {', ' return (checkMe.getDistance (center) <= radius);', ' }', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return center; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return radius + checkMe.getDistance (center); ', ' }', '}', '', '', '', 'class OneDimPoint implements IPointInMetricSpace <OneDimPoint> {', ' ', ' // this is the actual double', ' Double value;', ' ', ' // construct this out of a double value', ' public OneDimPoint (double makeFromMe) {', ' value = new Double (makeFromMe);', ' }', ' ', ' // get the distance to another point', ' public double getDistance (OneDimPoint toMe) {', ' if (value > toMe.value)', ' return value - toMe.value;', ' else', ' return toMe.value - value;', ' }', ' ', '}', '', 'class MultiDimPoint implements IPointInMetricSpace <MultiDimPoint> {', ' ', ' // this is the point in a multidimensional space', ' IDoubleVector me;', ' ', ' // make this out of an IDoubleVector', ' public MultiDimPoint (IDoubleVector useMe) {', ' me = useMe;', ' }', ' ', ' // get the Euclidean distance to another point', ' public double getDistance (MultiDimPoint toMe) {', ' double distance = 0.0;', ' try {', ' for (int i = 0; i < me.getLength (); i++) {', ' double diff = me.getItem (i) - toMe.me.getItem (i);', ' diff *= diff;', ' distance += diff;', ' }', ' } catch (OutOfBoundsException e) {', ' throw new IndexOutOfBoundsException ("Can\'t compare two MultiDimPoint objects with different dimensionality!"); ', ' }', ' return Math.sqrt(distance);', ' }', ' ', '}', '// this is a leaf node', 'class LeafMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements ', ' IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myData;', ' ', ' // contructor that takes a data list and builds a node out of it', ' private LeafMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myDataIn) {', ' myData = myDataIn; ', ' }', ' ', ' // constructor that creates an empty node', ' public LeafMTreeNodeABCD () {'] | [' myData = new ChrisMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> (); ', ' }'] | [' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // just add in the new data', ' myData.add (new PointABCD <PointInMetricSpace> (keyToAdd), dataToAdd);', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> newOne = myData.splitInTwo ();', ' LeafMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' myQ.insert (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData (), ', ' query.getDistance (myData.get (i).getKey ().getPointInInterior ()));', ' }', ' }', ' }', ' ', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' returnVal.add (new DataWrapper <PointInMetricSpace, DataType> (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData ()));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return 1; ', ' }', '', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', '// this silly little class is just a wrapper for a key, data pair', 'class DataWrapper <Key, Data> {', ' ', ' Key key;', ' Data data;', ' ', ' public DataWrapper (Key keyIn, Data dataIn) {', ' key = keyIn;', ' data = dataIn;', ' }', ' ', ' public Key getKey () {', ' return key;', ' }', ' ', ' public Data getData () {', ' return data;', ' }', '}', '', '', '// this is an internal node', 'class InternalMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType>', ' implements IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> myData;', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' // this constructs a new internal node that holds precisely the two nodes that are passed in', ' public InternalMTreeNodeABCD (IMTreeNodeABCD <PointInMetricSpace, DataType> refOne,', ' IMTreeNodeABCD <PointInMetricSpace, DataType> refTwo) {', ' ', ' // create a necw list and add the two guys in', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> ();', ' myData.add (refOne.getBoundingSphere (), refOne);', ' myData.add (refTwo.getBoundingSphere (), refTwo);', ' }', ' ', ' // this constructs a new node that holds the list of data that we were passed in', ' public InternalMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> useMe) {', ' myData = useMe; ', ' }', ' ', ' // from the interface', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // find the best child; this is the one we are closest to', ' double bestDist = 9e99;', ' int bestIndex = 0;', ' for (int i = 0; i < myData.size (); i++) {', ' ', ' double newDist = myData.get (i).getKey ().getPointInInterior ().getDistance (keyToAdd);', ' if (newDist < bestDist) {', ' bestDist = newDist;', ' bestIndex = i;', ' }', ' }', ' ', ' // do the recursive insert', ' IMTreeNodeABCD <PointInMetricSpace, DataType> newRef = myData.get (bestIndex).getData ().insert (keyToAdd, dataToAdd);', ' ', ' // if we got something back, then there was a split, so add the new node into our list', ' if (newRef != null) {', ' myData.add (newRef.getBoundingSphere (), newRef);', ' }', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> newOne = myData.splitInTwo ();', ' InternalMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.intersects (myData.get (i).getKey ())) {', ' myData.get (i).getData ().findKClosest (query, myQ);', ' }', ' }', ' }', ' ', ' // from the interface', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.intersects (myData.get (i).getKey ())) {', ' returnVal.addAll (myData.get (i).getData ().find (query));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return myData.get (0).getData ().depth () + 1; ', ' }', ' ', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', 'abstract class AMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> implements IMetricDataListABCD <PointInMetricSpace,KeyType, DataType> {', '', ' // this is the data that is actually stored in the list', ' private ArrayList <DataWrapper <KeyType, DataType>> myData;', ' ', ' // this is the sphere that bounds everything in the list', ' private SphereABCD <PointInMetricSpace> myBoundingSphere;', ' ', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myBoundingSphere; ', ' }', ' ', ' public int size () {', ' if (myData != null)', ' return myData.size (); ', ' else', ' return 0;', ' }', ' ', ' public DataWrapper <KeyType, DataType> get (int pos) {', ' return myData.get (pos);', ' }', ' ', ' public void replaceKey (int pos, KeyType keyToAdd) {', ' DataWrapper <KeyType, DataType> temp = myData.remove (pos);', ' DataWrapper <KeyType, DataType> newOne = new DataWrapper <KeyType, DataType> (keyToAdd, temp.getData ());', ' myData.add (pos, newOne);', ' }', ' ', ' public void add (KeyType keyToAdd, DataType dataToAdd) {', ' ', ' // if this is the first add, then set everyone up', ' if (myData == null) {', ' PointInMetricSpace myCentroid = keyToAdd.getPointInInterior ();', ' myBoundingSphere = new SphereABCD <PointInMetricSpace> (myCentroid, keyToAdd.maxDistanceTo (myCentroid));', ' myData = new ArrayList <DataWrapper <KeyType, DataType>> ();', ' ', ' // otherwise, extend the sphere if needed', ' } else {', ' myBoundingSphere.swallow (keyToAdd);', ' }', ' ', ' // add the data', ' myData.add (new DataWrapper <KeyType, DataType> (keyToAdd, dataToAdd));', ' }', ' ', ' // we want to potentially allow many implementations of the splitting lalgorithm', ' abstract public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // this is here so the actual splitting algorithn can access the list and change the sphere', ' protected ArrayList <DataWrapper <KeyType, DataType>> getList () {', ' return myData;', ' }', ' ', ' // this is here so the splitting algorithm can modify the list and the sphere', ' protected void replaceGuts (AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> withMe) {', ' myData = withMe.myData;', ' myBoundingSphere = withMe.myBoundingSphere;', ' }', ' ', '}', '', '// this is a particular implementation of the metric data list that uses a simple quadratic clustering', '// algorithm to perform a list split. It picks two "seeds" (the most distant objects) and then repeatedly', '// adds to the two new lists by choosing the objects closest to the seeds', 'class ChrisMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> extends AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> {', '', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo () {', ' ', ' // first, we need to find the two most distant points in the list', ' ArrayList <DataWrapper <KeyType, DataType>> myData = getList ();', ' int bestI = 0, bestJ = 0;', ' double maxDist = -1.0;', ' for (int i = 0; i < myData.size (); i++) {', ' for (int j = i + 1; j < myData.size (); j++) {', ' ', ' // get the two keys', ' DataWrapper <KeyType, DataType> pointOne = myData.get (i);', ' DataWrapper <KeyType, DataType> pointTwo = myData.get (j);', ' ', ' // find the difference between them', ' double curDist = pointOne.getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', '', ' // see if it is the biggest', ' if (curDist > maxDist) {', ' maxDist = curDist;', ' bestI = i;', ' bestJ = j;', ' }', ' }', ' }', ' ', ' // now, we have the best two points; those are seeds for the clustering', ' DataWrapper <KeyType, DataType> pointOne = myData.remove (bestI);', ' DataWrapper <KeyType, DataType> pointTwo = myData.remove (bestJ - 1);', ' ', ' // these are the two new lists', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listOne = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listTwo = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' ', ' // put the two seeds in', ' listOne.add (pointOne.getKey (), pointOne.getData ());', ' listTwo.add (pointTwo.getKey (), pointTwo.getData ());', ' ', ' // and add everyone else in', ' while (myData.size () != 0) {', ' ', ' // find the one closest to the first seed', ' int bestIndex = 0;', ' double bestDist = 9e99;', ' ', ' // loop thru all of the candidate data objects', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listOne.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' ', ' // break if no more data', ' if (myData.size () == 0)', ' break;', ' ', ' // loop thru all of the candidate data objects', ' bestDist = 9e99;', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listTwo.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' }', ' ', ' // now we replace our own guts with the first list', ' replaceGuts (listOne);', ' ', ' // and return the other list', ' return listTwo;', ' }', '}', '', 'interface IMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> {', ' ', ' // add a new pair to the list', ' public void add (KeyType keyToAdd, DataType dataToAdd);', ' ', ' // replace a key at the indicated position', ' public void replaceKey (int pos, KeyType keyToAdd);', ' ', ' // get the key, data pair that resides at a particular position', ' public DataWrapper <KeyType, DataType> get (int pos);', ' ', ' // return the number of items in the list', ' public int size ();', ' ', ' // split the list in two, using some clutering algorithm', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // get a sphere that totally bounds all of the objects in the list', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class MTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public MTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class SCMTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public SCMTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', '', 'public class MTreeTester extends TestCase {', ' ', ' // compare two lists of strings to see if the contents are the same', ' private boolean compareStringSets (ArrayList <String> setOne, ArrayList <String> setTwo) {', ' ', ' // sort the sets and make sure they are the same', ' boolean returnVal = true;', ' if (setOne.size () == setTwo.size ()) {', ' Collections.sort (setOne);', ' Collections.sort (setTwo);', ' for (int i = 0; i < setOne.size (); i++) {', ' if (!setOne.get (i).equals (setTwo.get (i))) {', ' returnVal = false;', ' break; ', ' }', ' }', ' } else {', ' returnVal = false;', ' }', ' ', ' // print out the result', ' System.out.println ("**** Expected:");', ' for (int i = 0; i < setOne.size (); i++) {', ' System.out.format (setOne.get (i) + " ");', ' }', ' System.out.println ("\\n**** Got:");', ' for (int i = 0; i < setTwo.size (); i++) {', ' System.out.format (setTwo.get (i) + " ");', ' }', ' System.out.println ("");', ' ', ' return returnVal;', ' }', ' ', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST SIMPLE ONE DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testOneDimRangeQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.find (query, expectedQuerySize / 2);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.find (query, expectedQuerySize / 2);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (numPoints);', ' result1 = myTree.find (query, expectedQuerySize);', ' result2 = hisTree.find (query, expectedQuerySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // like the last one, but runs a top k', ' private void testOneDimTopKQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (167);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.findKClosest (query, querySize);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (0);', ' result1 = myTree.findKClosest (query, querySize);', ' result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST MULTI-DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimRangeQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' double dist1 = 0;', ' double dist2 = 0;', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' dist1 = Math.sqrt (numDims) * expectedQuerySize / 2.0;', ' dist2 = Math.sqrt (numDims) * expectedQuerySize;', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' // do a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, (int) expectedQuerySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = myTree.findKClosest (query2, (int) expectedQuerySize);', ' ', ' // find the distance to the furthest point in both cases', ' for (int i = 0; i < (int) expectedQuerySize; i++) {', ' double newDist = result1.get (i).getKey ().getDistance (query1);', ' if (newDist > dist1)', ' dist1 = newDist;', ' newDist = result2.get (i).getKey ().getDistance (query2);', ' if (newDist > dist2)', ' dist2 = newDist;', ' }', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.find (query1, dist1);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.find (query1, dist1);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.find (query2, dist2);', ' result2 = hisTree.find (query2, dist2);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimTopKQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, querySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.findKClosest (query1, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.findKClosest (query2, querySize);', ' result2 = hisTree.findKClosest (query2, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' ', ' /**', ' * "TIER 1" TESTS', ' * NONE OF THESE REQUIRE ANY SPLITS', ' */', ' public void testEasy1() {', ' testOneDimRangeQuery (true, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy2() {', ' testOneDimRangeQuery (false, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy3() {', ' testOneDimRangeQuery (true, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy4() {', ' testOneDimRangeQuery (false, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy5() {', ' testMultiDimRangeQuery (true, 1, 5, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy6() {', ' testMultiDimRangeQuery (false, 1, 10, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy7() {', ' testMultiDimRangeQuery (true, 1, 5, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy8() {', ' testMultiDimRangeQuery (false, 1, 15, 10000, 10000, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 2" TESTS', ' * NONE OF THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testMod1() {', ' testOneDimRangeQuery (true, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod2() {', ' testOneDimRangeQuery (false, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod3() {', ' testOneDimRangeQuery (true, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod4() {', ' testOneDimRangeQuery (false, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod5() {', ' testMultiDimRangeQuery (true, 2, 5, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod6() {', ' testMultiDimRangeQuery (false, 2, 10, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod7() {', ' testMultiDimRangeQuery (true, 2, 5, 10000, 100, 1000, 10);', ' }', ' ', ' public void testMod8() {', ' testMultiDimRangeQuery (false, 2, 15, 10000, 100, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 3" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testHard1() {', ' testOneDimRangeQuery (true, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard2() {', ' testOneDimRangeQuery (false, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard3() {', ' testOneDimRangeQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard4() {', ' testOneDimRangeQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard5() {', ' testMultiDimRangeQuery (true, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard6() {', ' testMultiDimRangeQuery (false, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard7() {', ' testMultiDimRangeQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard8() {', ' testMultiDimRangeQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', ' ', ' /**', ' * "TIER 4" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE AND THEY TEST THE TOPK FUNCTIONALITY', ' */', ' ', ' public void testTopK1() {', ' testOneDimTopKQuery (true, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK2() {', ' testOneDimTopKQuery (false, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK3() {', ' testOneDimTopKQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK4() {', ' testOneDimTopKQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK5() {', ' testMultiDimTopKQuery (true, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK6() {', ' testMultiDimTopKQuery (false, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK7() {', ' testMultiDimTopKQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK8() {', ' testMultiDimTopKQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', '}'] | [] | Class 'ChrisMetricDataListABCD' used at line 364 is defined at line 616 and has a Long-Range dependency.
Global_Variable 'myData' used at line 364 is defined at line 355 and has a Short-Range dependency. | {} | {'Class Long-Range': 1, 'Global_Variable Short-Range': 1} |
infilling_java | MTreeTester | 369 | 370 | ['import junit.framework.TestCase;', 'import java.util.ArrayList;', 'import java.util.Random;', 'import java.util.Collections;', '', '// this is a map from a set of keys of type PointInMetricSpace to a', '// set of data of type DataType', 'interface IMTree <Key extends IPointInMetricSpace <Key>, Data> {', ' ', ' // insert a new key/data pair into the map', ' void insert (Key keyToAdd, Data dataToAdd);', ' ', ' // find all of the key/data pairs in the map that fall within a', ' // particular distance of query point if no results are found, then', ' // an empty array is returned (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> find (Key query, double distance);', ' ', ' // find the k closest key/data pairs in the map to a particular', ' // query point ', ' //', ' // if the number of points in the map is less than k, then the', ' // returned list will have less than k pairs in it', ' //', ' // if the number of points is zero, then an empty array is returned', ' // (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> findKClosest (Key query, int k);', ' ', ' // returns the number of nodes that exist on a path from root to leaf in the tree...', ' // whtever the details of the implementation are, a tree with a single leaf node should return 1, and a tree', ' // with more than one lead node should return at least two (since it must have at least one internal node).', ' public int depth ();', ' ', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', '', 'interface IDoubleVector {', '', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '', '// this correponds to some geometric object in a metric space; the object is built out of', '// one or more points of type PointInMetricSpace', 'interface IObjectInMetricSpaceABCD <PointInMetricSpace extends IPointInMetricSpace<PointInMetricSpace>> {', ' ', ' // get the maximum distance from some point on the shape to a particular point in the metric space', ' double maxDistanceTo (PointInMetricSpace checkMe);', ' ', ' // return some arbitrary point on the interior of the geometric object', ' PointInMetricSpace getPointInInterior ();', '}', '', '', '// this interface corresponds to a point in some metric space', 'interface IPointInMetricSpace <PointInMetricSpace> {', ' ', ' // get the distance to another point', ' // ', ' // for this to work in an M-Tree, distances should be "metric" and', ' // obey the triangle inequality', ' double getDistance (PointInMetricSpace toMe);', '}', '', '// this is the basic node type in the structure', 'interface IMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> {', ' ', ' // insert a new key/data pair into the structure. The return value is a new MTreeNode if there was', ' // a split in response to the insertion, or a null if there was no split', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd);', ' ', ' // find all of the key/data pairs in the structure that fall within a particular query sphere', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query); ', ' ', ' // find the set of items closest to the given query point', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ);', ' ', ' // returns a sphere that totally encompasses everything in the node and its subtree', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', ' ', ' // returns the depth', ' public int depth ();', '}', '', '// this is a point in a particular metric space', 'class PointABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the point', ' private PointInMetricSpace me;', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return me; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return checkMe.getDistance (me); ', ' }', ' ', ' // contruct a point', ' public PointABCD (PointInMetricSpace useMe) {', ' me = useMe; ', ' }', '}', '', 'class PQueueABCD <PointInMetricSpace, DataType> {', ' ', ' // this is an object in the queue', ' private class Wrapper {', ' DataWrapper <PointInMetricSpace, DataType> myData;', ' double distance;', ' }', ' ', ' // this is the actual queue', ' ArrayList <Wrapper> myList;', ' ', ' // this is the largest distance value currently in the queue', ' double large;', ' ', ' // this is the max number of objects', ' int maxCount;', ' ', ' // create a priority queue with the speced number of slots', ' PQueueABCD (int maxCountIn) {', ' maxCount = maxCountIn;', ' myList = new ArrayList <Wrapper> ();', ' large = 9e99;', ' }', ' ', ' // get the largest distance in the queue', ' double getDist () {', ' return large;', ' }', ' ', ' // add a new object to the queue... the insertion is ignored if the distance value', ' // exceeds the largest that is in the queue and the queue is already full', ' void insert (PointInMetricSpace key, DataType data, double distance) {', ' ', ' // if we are full, remove the one with the largest distance', ' if (myList.size () == maxCount && distance < large) {', ' ', ' int badIndex = 0;', ' double maxDist = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > maxDist) {', ' maxDist = myList.get (i).distance;', ' badIndex = i;', ' }', ' }', ' ', ' myList.remove (badIndex);', ' }', ' ', ' // see if there is room', ' if (myList.size () < maxCount) {', ' ', ' // add it ', ' Wrapper newOne = new Wrapper ();', ' newOne.myData = new DataWrapper <PointInMetricSpace, DataType> (key, data);', ' newOne.distance = distance;', ' myList.add (newOne); ', ' }', ' ', ' // if we are full, reset the max distance', ' if (myList.size () == maxCount) {', ' large = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > large) {', ' large = myList.get (i).distance;', ' }', ' }', ' }', ' ', ' }', ' ', ' // extracts the contents of the queue', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> done () {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' for (int i = 0; i < myList.size (); i++) {', ' returnVal.add (myList.get (i).myData); ', ' }', ' ', ' return returnVal;', ' }', ' ', '}', '', '// this is a sphere in a particular metric space', 'class SphereABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the center of the sphere and its radius', ' private PointInMetricSpace center;', ' private double radius;', ' ', ' // build a sphere out of its center and its radius', ' public SphereABCD (PointInMetricSpace centerIn, double radiusIn) {', ' center = centerIn;', ' radius = radiusIn;', ' }', ' ', ' // increase the size of the sphere so it contains the object swallowMe', ' public void swallow (IObjectInMetricSpaceABCD <PointInMetricSpace> swallowMe) {', ' ', ' // see if we need to increase the radius to swallow this guy', ' double dist = swallowMe.maxDistanceTo (center);', ' if (dist > radius)', ' radius = dist;', ' }', ' ', ' // check to see if a sphere intersects another sphere', ' public boolean intersects (SphereABCD <PointInMetricSpace> me) {', ' return (me.center.getDistance (center) <= me.radius + radius);', ' }', ' ', ' // check to see if the sphere contains a point', ' public boolean contains (PointInMetricSpace checkMe) {', ' return (checkMe.getDistance (center) <= radius);', ' }', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return center; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return radius + checkMe.getDistance (center); ', ' }', '}', '', '', '', 'class OneDimPoint implements IPointInMetricSpace <OneDimPoint> {', ' ', ' // this is the actual double', ' Double value;', ' ', ' // construct this out of a double value', ' public OneDimPoint (double makeFromMe) {', ' value = new Double (makeFromMe);', ' }', ' ', ' // get the distance to another point', ' public double getDistance (OneDimPoint toMe) {', ' if (value > toMe.value)', ' return value - toMe.value;', ' else', ' return toMe.value - value;', ' }', ' ', '}', '', 'class MultiDimPoint implements IPointInMetricSpace <MultiDimPoint> {', ' ', ' // this is the point in a multidimensional space', ' IDoubleVector me;', ' ', ' // make this out of an IDoubleVector', ' public MultiDimPoint (IDoubleVector useMe) {', ' me = useMe;', ' }', ' ', ' // get the Euclidean distance to another point', ' public double getDistance (MultiDimPoint toMe) {', ' double distance = 0.0;', ' try {', ' for (int i = 0; i < me.getLength (); i++) {', ' double diff = me.getItem (i) - toMe.me.getItem (i);', ' diff *= diff;', ' distance += diff;', ' }', ' } catch (OutOfBoundsException e) {', ' throw new IndexOutOfBoundsException ("Can\'t compare two MultiDimPoint objects with different dimensionality!"); ', ' }', ' return Math.sqrt(distance);', ' }', ' ', '}', '// this is a leaf node', 'class LeafMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements ', ' IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myData;', ' ', ' // contructor that takes a data list and builds a node out of it', ' private LeafMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myDataIn) {', ' myData = myDataIn; ', ' }', ' ', ' // constructor that creates an empty node', ' public LeafMTreeNodeABCD () {', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> (); ', ' }', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {'] | [' return myData.getBoundingSphere (); ', ' }'] | [' ', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // just add in the new data', ' myData.add (new PointABCD <PointInMetricSpace> (keyToAdd), dataToAdd);', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> newOne = myData.splitInTwo ();', ' LeafMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' myQ.insert (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData (), ', ' query.getDistance (myData.get (i).getKey ().getPointInInterior ()));', ' }', ' }', ' }', ' ', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' returnVal.add (new DataWrapper <PointInMetricSpace, DataType> (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData ()));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return 1; ', ' }', '', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', '// this silly little class is just a wrapper for a key, data pair', 'class DataWrapper <Key, Data> {', ' ', ' Key key;', ' Data data;', ' ', ' public DataWrapper (Key keyIn, Data dataIn) {', ' key = keyIn;', ' data = dataIn;', ' }', ' ', ' public Key getKey () {', ' return key;', ' }', ' ', ' public Data getData () {', ' return data;', ' }', '}', '', '', '// this is an internal node', 'class InternalMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType>', ' implements IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> myData;', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' // this constructs a new internal node that holds precisely the two nodes that are passed in', ' public InternalMTreeNodeABCD (IMTreeNodeABCD <PointInMetricSpace, DataType> refOne,', ' IMTreeNodeABCD <PointInMetricSpace, DataType> refTwo) {', ' ', ' // create a necw list and add the two guys in', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> ();', ' myData.add (refOne.getBoundingSphere (), refOne);', ' myData.add (refTwo.getBoundingSphere (), refTwo);', ' }', ' ', ' // this constructs a new node that holds the list of data that we were passed in', ' public InternalMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> useMe) {', ' myData = useMe; ', ' }', ' ', ' // from the interface', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // find the best child; this is the one we are closest to', ' double bestDist = 9e99;', ' int bestIndex = 0;', ' for (int i = 0; i < myData.size (); i++) {', ' ', ' double newDist = myData.get (i).getKey ().getPointInInterior ().getDistance (keyToAdd);', ' if (newDist < bestDist) {', ' bestDist = newDist;', ' bestIndex = i;', ' }', ' }', ' ', ' // do the recursive insert', ' IMTreeNodeABCD <PointInMetricSpace, DataType> newRef = myData.get (bestIndex).getData ().insert (keyToAdd, dataToAdd);', ' ', ' // if we got something back, then there was a split, so add the new node into our list', ' if (newRef != null) {', ' myData.add (newRef.getBoundingSphere (), newRef);', ' }', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> newOne = myData.splitInTwo ();', ' InternalMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.intersects (myData.get (i).getKey ())) {', ' myData.get (i).getData ().findKClosest (query, myQ);', ' }', ' }', ' }', ' ', ' // from the interface', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.intersects (myData.get (i).getKey ())) {', ' returnVal.addAll (myData.get (i).getData ().find (query));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return myData.get (0).getData ().depth () + 1; ', ' }', ' ', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', 'abstract class AMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> implements IMetricDataListABCD <PointInMetricSpace,KeyType, DataType> {', '', ' // this is the data that is actually stored in the list', ' private ArrayList <DataWrapper <KeyType, DataType>> myData;', ' ', ' // this is the sphere that bounds everything in the list', ' private SphereABCD <PointInMetricSpace> myBoundingSphere;', ' ', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myBoundingSphere; ', ' }', ' ', ' public int size () {', ' if (myData != null)', ' return myData.size (); ', ' else', ' return 0;', ' }', ' ', ' public DataWrapper <KeyType, DataType> get (int pos) {', ' return myData.get (pos);', ' }', ' ', ' public void replaceKey (int pos, KeyType keyToAdd) {', ' DataWrapper <KeyType, DataType> temp = myData.remove (pos);', ' DataWrapper <KeyType, DataType> newOne = new DataWrapper <KeyType, DataType> (keyToAdd, temp.getData ());', ' myData.add (pos, newOne);', ' }', ' ', ' public void add (KeyType keyToAdd, DataType dataToAdd) {', ' ', ' // if this is the first add, then set everyone up', ' if (myData == null) {', ' PointInMetricSpace myCentroid = keyToAdd.getPointInInterior ();', ' myBoundingSphere = new SphereABCD <PointInMetricSpace> (myCentroid, keyToAdd.maxDistanceTo (myCentroid));', ' myData = new ArrayList <DataWrapper <KeyType, DataType>> ();', ' ', ' // otherwise, extend the sphere if needed', ' } else {', ' myBoundingSphere.swallow (keyToAdd);', ' }', ' ', ' // add the data', ' myData.add (new DataWrapper <KeyType, DataType> (keyToAdd, dataToAdd));', ' }', ' ', ' // we want to potentially allow many implementations of the splitting lalgorithm', ' abstract public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // this is here so the actual splitting algorithn can access the list and change the sphere', ' protected ArrayList <DataWrapper <KeyType, DataType>> getList () {', ' return myData;', ' }', ' ', ' // this is here so the splitting algorithm can modify the list and the sphere', ' protected void replaceGuts (AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> withMe) {', ' myData = withMe.myData;', ' myBoundingSphere = withMe.myBoundingSphere;', ' }', ' ', '}', '', '// this is a particular implementation of the metric data list that uses a simple quadratic clustering', '// algorithm to perform a list split. It picks two "seeds" (the most distant objects) and then repeatedly', '// adds to the two new lists by choosing the objects closest to the seeds', 'class ChrisMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> extends AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> {', '', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo () {', ' ', ' // first, we need to find the two most distant points in the list', ' ArrayList <DataWrapper <KeyType, DataType>> myData = getList ();', ' int bestI = 0, bestJ = 0;', ' double maxDist = -1.0;', ' for (int i = 0; i < myData.size (); i++) {', ' for (int j = i + 1; j < myData.size (); j++) {', ' ', ' // get the two keys', ' DataWrapper <KeyType, DataType> pointOne = myData.get (i);', ' DataWrapper <KeyType, DataType> pointTwo = myData.get (j);', ' ', ' // find the difference between them', ' double curDist = pointOne.getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', '', ' // see if it is the biggest', ' if (curDist > maxDist) {', ' maxDist = curDist;', ' bestI = i;', ' bestJ = j;', ' }', ' }', ' }', ' ', ' // now, we have the best two points; those are seeds for the clustering', ' DataWrapper <KeyType, DataType> pointOne = myData.remove (bestI);', ' DataWrapper <KeyType, DataType> pointTwo = myData.remove (bestJ - 1);', ' ', ' // these are the two new lists', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listOne = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listTwo = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' ', ' // put the two seeds in', ' listOne.add (pointOne.getKey (), pointOne.getData ());', ' listTwo.add (pointTwo.getKey (), pointTwo.getData ());', ' ', ' // and add everyone else in', ' while (myData.size () != 0) {', ' ', ' // find the one closest to the first seed', ' int bestIndex = 0;', ' double bestDist = 9e99;', ' ', ' // loop thru all of the candidate data objects', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listOne.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' ', ' // break if no more data', ' if (myData.size () == 0)', ' break;', ' ', ' // loop thru all of the candidate data objects', ' bestDist = 9e99;', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listTwo.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' }', ' ', ' // now we replace our own guts with the first list', ' replaceGuts (listOne);', ' ', ' // and return the other list', ' return listTwo;', ' }', '}', '', 'interface IMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> {', ' ', ' // add a new pair to the list', ' public void add (KeyType keyToAdd, DataType dataToAdd);', ' ', ' // replace a key at the indicated position', ' public void replaceKey (int pos, KeyType keyToAdd);', ' ', ' // get the key, data pair that resides at a particular position', ' public DataWrapper <KeyType, DataType> get (int pos);', ' ', ' // return the number of items in the list', ' public int size ();', ' ', ' // split the list in two, using some clutering algorithm', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // get a sphere that totally bounds all of the objects in the list', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class MTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public MTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class SCMTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public SCMTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', '', 'public class MTreeTester extends TestCase {', ' ', ' // compare two lists of strings to see if the contents are the same', ' private boolean compareStringSets (ArrayList <String> setOne, ArrayList <String> setTwo) {', ' ', ' // sort the sets and make sure they are the same', ' boolean returnVal = true;', ' if (setOne.size () == setTwo.size ()) {', ' Collections.sort (setOne);', ' Collections.sort (setTwo);', ' for (int i = 0; i < setOne.size (); i++) {', ' if (!setOne.get (i).equals (setTwo.get (i))) {', ' returnVal = false;', ' break; ', ' }', ' }', ' } else {', ' returnVal = false;', ' }', ' ', ' // print out the result', ' System.out.println ("**** Expected:");', ' for (int i = 0; i < setOne.size (); i++) {', ' System.out.format (setOne.get (i) + " ");', ' }', ' System.out.println ("\\n**** Got:");', ' for (int i = 0; i < setTwo.size (); i++) {', ' System.out.format (setTwo.get (i) + " ");', ' }', ' System.out.println ("");', ' ', ' return returnVal;', ' }', ' ', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST SIMPLE ONE DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testOneDimRangeQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.find (query, expectedQuerySize / 2);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.find (query, expectedQuerySize / 2);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (numPoints);', ' result1 = myTree.find (query, expectedQuerySize);', ' result2 = hisTree.find (query, expectedQuerySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // like the last one, but runs a top k', ' private void testOneDimTopKQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (167);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.findKClosest (query, querySize);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (0);', ' result1 = myTree.findKClosest (query, querySize);', ' result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST MULTI-DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimRangeQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' double dist1 = 0;', ' double dist2 = 0;', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' dist1 = Math.sqrt (numDims) * expectedQuerySize / 2.0;', ' dist2 = Math.sqrt (numDims) * expectedQuerySize;', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' // do a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, (int) expectedQuerySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = myTree.findKClosest (query2, (int) expectedQuerySize);', ' ', ' // find the distance to the furthest point in both cases', ' for (int i = 0; i < (int) expectedQuerySize; i++) {', ' double newDist = result1.get (i).getKey ().getDistance (query1);', ' if (newDist > dist1)', ' dist1 = newDist;', ' newDist = result2.get (i).getKey ().getDistance (query2);', ' if (newDist > dist2)', ' dist2 = newDist;', ' }', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.find (query1, dist1);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.find (query1, dist1);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.find (query2, dist2);', ' result2 = hisTree.find (query2, dist2);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimTopKQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, querySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.findKClosest (query1, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.findKClosest (query2, querySize);', ' result2 = hisTree.findKClosest (query2, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' ', ' /**', ' * "TIER 1" TESTS', ' * NONE OF THESE REQUIRE ANY SPLITS', ' */', ' public void testEasy1() {', ' testOneDimRangeQuery (true, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy2() {', ' testOneDimRangeQuery (false, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy3() {', ' testOneDimRangeQuery (true, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy4() {', ' testOneDimRangeQuery (false, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy5() {', ' testMultiDimRangeQuery (true, 1, 5, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy6() {', ' testMultiDimRangeQuery (false, 1, 10, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy7() {', ' testMultiDimRangeQuery (true, 1, 5, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy8() {', ' testMultiDimRangeQuery (false, 1, 15, 10000, 10000, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 2" TESTS', ' * NONE OF THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testMod1() {', ' testOneDimRangeQuery (true, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod2() {', ' testOneDimRangeQuery (false, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod3() {', ' testOneDimRangeQuery (true, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod4() {', ' testOneDimRangeQuery (false, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod5() {', ' testMultiDimRangeQuery (true, 2, 5, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod6() {', ' testMultiDimRangeQuery (false, 2, 10, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod7() {', ' testMultiDimRangeQuery (true, 2, 5, 10000, 100, 1000, 10);', ' }', ' ', ' public void testMod8() {', ' testMultiDimRangeQuery (false, 2, 15, 10000, 100, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 3" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testHard1() {', ' testOneDimRangeQuery (true, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard2() {', ' testOneDimRangeQuery (false, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard3() {', ' testOneDimRangeQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard4() {', ' testOneDimRangeQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard5() {', ' testMultiDimRangeQuery (true, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard6() {', ' testMultiDimRangeQuery (false, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard7() {', ' testMultiDimRangeQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard8() {', ' testMultiDimRangeQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', ' ', ' /**', ' * "TIER 4" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE AND THEY TEST THE TOPK FUNCTIONALITY', ' */', ' ', ' public void testTopK1() {', ' testOneDimTopKQuery (true, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK2() {', ' testOneDimTopKQuery (false, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK3() {', ' testOneDimTopKQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK4() {', ' testOneDimTopKQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK5() {', ' testMultiDimTopKQuery (true, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK6() {', ' testMultiDimTopKQuery (false, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK7() {', ' testMultiDimTopKQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK8() {', ' testMultiDimTopKQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', '}'] | [] | Global_Variable 'myData' used at line 369 is defined at line 355 and has a Medium-Range dependency. | {} | {'Global_Variable Medium-Range': 1} |
infilling_java | MTreeTester | 379 | 382 | ['import junit.framework.TestCase;', 'import java.util.ArrayList;', 'import java.util.Random;', 'import java.util.Collections;', '', '// this is a map from a set of keys of type PointInMetricSpace to a', '// set of data of type DataType', 'interface IMTree <Key extends IPointInMetricSpace <Key>, Data> {', ' ', ' // insert a new key/data pair into the map', ' void insert (Key keyToAdd, Data dataToAdd);', ' ', ' // find all of the key/data pairs in the map that fall within a', ' // particular distance of query point if no results are found, then', ' // an empty array is returned (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> find (Key query, double distance);', ' ', ' // find the k closest key/data pairs in the map to a particular', ' // query point ', ' //', ' // if the number of points in the map is less than k, then the', ' // returned list will have less than k pairs in it', ' //', ' // if the number of points is zero, then an empty array is returned', ' // (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> findKClosest (Key query, int k);', ' ', ' // returns the number of nodes that exist on a path from root to leaf in the tree...', ' // whtever the details of the implementation are, a tree with a single leaf node should return 1, and a tree', ' // with more than one lead node should return at least two (since it must have at least one internal node).', ' public int depth ();', ' ', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', '', 'interface IDoubleVector {', '', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '', '// this correponds to some geometric object in a metric space; the object is built out of', '// one or more points of type PointInMetricSpace', 'interface IObjectInMetricSpaceABCD <PointInMetricSpace extends IPointInMetricSpace<PointInMetricSpace>> {', ' ', ' // get the maximum distance from some point on the shape to a particular point in the metric space', ' double maxDistanceTo (PointInMetricSpace checkMe);', ' ', ' // return some arbitrary point on the interior of the geometric object', ' PointInMetricSpace getPointInInterior ();', '}', '', '', '// this interface corresponds to a point in some metric space', 'interface IPointInMetricSpace <PointInMetricSpace> {', ' ', ' // get the distance to another point', ' // ', ' // for this to work in an M-Tree, distances should be "metric" and', ' // obey the triangle inequality', ' double getDistance (PointInMetricSpace toMe);', '}', '', '// this is the basic node type in the structure', 'interface IMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> {', ' ', ' // insert a new key/data pair into the structure. The return value is a new MTreeNode if there was', ' // a split in response to the insertion, or a null if there was no split', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd);', ' ', ' // find all of the key/data pairs in the structure that fall within a particular query sphere', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query); ', ' ', ' // find the set of items closest to the given query point', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ);', ' ', ' // returns a sphere that totally encompasses everything in the node and its subtree', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', ' ', ' // returns the depth', ' public int depth ();', '}', '', '// this is a point in a particular metric space', 'class PointABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the point', ' private PointInMetricSpace me;', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return me; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return checkMe.getDistance (me); ', ' }', ' ', ' // contruct a point', ' public PointABCD (PointInMetricSpace useMe) {', ' me = useMe; ', ' }', '}', '', 'class PQueueABCD <PointInMetricSpace, DataType> {', ' ', ' // this is an object in the queue', ' private class Wrapper {', ' DataWrapper <PointInMetricSpace, DataType> myData;', ' double distance;', ' }', ' ', ' // this is the actual queue', ' ArrayList <Wrapper> myList;', ' ', ' // this is the largest distance value currently in the queue', ' double large;', ' ', ' // this is the max number of objects', ' int maxCount;', ' ', ' // create a priority queue with the speced number of slots', ' PQueueABCD (int maxCountIn) {', ' maxCount = maxCountIn;', ' myList = new ArrayList <Wrapper> ();', ' large = 9e99;', ' }', ' ', ' // get the largest distance in the queue', ' double getDist () {', ' return large;', ' }', ' ', ' // add a new object to the queue... the insertion is ignored if the distance value', ' // exceeds the largest that is in the queue and the queue is already full', ' void insert (PointInMetricSpace key, DataType data, double distance) {', ' ', ' // if we are full, remove the one with the largest distance', ' if (myList.size () == maxCount && distance < large) {', ' ', ' int badIndex = 0;', ' double maxDist = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > maxDist) {', ' maxDist = myList.get (i).distance;', ' badIndex = i;', ' }', ' }', ' ', ' myList.remove (badIndex);', ' }', ' ', ' // see if there is room', ' if (myList.size () < maxCount) {', ' ', ' // add it ', ' Wrapper newOne = new Wrapper ();', ' newOne.myData = new DataWrapper <PointInMetricSpace, DataType> (key, data);', ' newOne.distance = distance;', ' myList.add (newOne); ', ' }', ' ', ' // if we are full, reset the max distance', ' if (myList.size () == maxCount) {', ' large = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > large) {', ' large = myList.get (i).distance;', ' }', ' }', ' }', ' ', ' }', ' ', ' // extracts the contents of the queue', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> done () {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' for (int i = 0; i < myList.size (); i++) {', ' returnVal.add (myList.get (i).myData); ', ' }', ' ', ' return returnVal;', ' }', ' ', '}', '', '// this is a sphere in a particular metric space', 'class SphereABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the center of the sphere and its radius', ' private PointInMetricSpace center;', ' private double radius;', ' ', ' // build a sphere out of its center and its radius', ' public SphereABCD (PointInMetricSpace centerIn, double radiusIn) {', ' center = centerIn;', ' radius = radiusIn;', ' }', ' ', ' // increase the size of the sphere so it contains the object swallowMe', ' public void swallow (IObjectInMetricSpaceABCD <PointInMetricSpace> swallowMe) {', ' ', ' // see if we need to increase the radius to swallow this guy', ' double dist = swallowMe.maxDistanceTo (center);', ' if (dist > radius)', ' radius = dist;', ' }', ' ', ' // check to see if a sphere intersects another sphere', ' public boolean intersects (SphereABCD <PointInMetricSpace> me) {', ' return (me.center.getDistance (center) <= me.radius + radius);', ' }', ' ', ' // check to see if the sphere contains a point', ' public boolean contains (PointInMetricSpace checkMe) {', ' return (checkMe.getDistance (center) <= radius);', ' }', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return center; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return radius + checkMe.getDistance (center); ', ' }', '}', '', '', '', 'class OneDimPoint implements IPointInMetricSpace <OneDimPoint> {', ' ', ' // this is the actual double', ' Double value;', ' ', ' // construct this out of a double value', ' public OneDimPoint (double makeFromMe) {', ' value = new Double (makeFromMe);', ' }', ' ', ' // get the distance to another point', ' public double getDistance (OneDimPoint toMe) {', ' if (value > toMe.value)', ' return value - toMe.value;', ' else', ' return toMe.value - value;', ' }', ' ', '}', '', 'class MultiDimPoint implements IPointInMetricSpace <MultiDimPoint> {', ' ', ' // this is the point in a multidimensional space', ' IDoubleVector me;', ' ', ' // make this out of an IDoubleVector', ' public MultiDimPoint (IDoubleVector useMe) {', ' me = useMe;', ' }', ' ', ' // get the Euclidean distance to another point', ' public double getDistance (MultiDimPoint toMe) {', ' double distance = 0.0;', ' try {', ' for (int i = 0; i < me.getLength (); i++) {', ' double diff = me.getItem (i) - toMe.me.getItem (i);', ' diff *= diff;', ' distance += diff;', ' }', ' } catch (OutOfBoundsException e) {', ' throw new IndexOutOfBoundsException ("Can\'t compare two MultiDimPoint objects with different dimensionality!"); ', ' }', ' return Math.sqrt(distance);', ' }', ' ', '}', '// this is a leaf node', 'class LeafMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements ', ' IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myData;', ' ', ' // contructor that takes a data list and builds a node out of it', ' private LeafMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myDataIn) {', ' myData = myDataIn; ', ' }', ' ', ' // constructor that creates an empty node', ' public LeafMTreeNodeABCD () {', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> (); ', ' }', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // just add in the new data', ' myData.add (new PointABCD <PointInMetricSpace> (keyToAdd), dataToAdd);', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {'] | [' IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> newOne = myData.splitInTwo ();', ' LeafMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }'] | [' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' myQ.insert (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData (), ', ' query.getDistance (myData.get (i).getKey ().getPointInInterior ()));', ' }', ' }', ' }', ' ', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' returnVal.add (new DataWrapper <PointInMetricSpace, DataType> (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData ()));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return 1; ', ' }', '', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', '// this silly little class is just a wrapper for a key, data pair', 'class DataWrapper <Key, Data> {', ' ', ' Key key;', ' Data data;', ' ', ' public DataWrapper (Key keyIn, Data dataIn) {', ' key = keyIn;', ' data = dataIn;', ' }', ' ', ' public Key getKey () {', ' return key;', ' }', ' ', ' public Data getData () {', ' return data;', ' }', '}', '', '', '// this is an internal node', 'class InternalMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType>', ' implements IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> myData;', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' // this constructs a new internal node that holds precisely the two nodes that are passed in', ' public InternalMTreeNodeABCD (IMTreeNodeABCD <PointInMetricSpace, DataType> refOne,', ' IMTreeNodeABCD <PointInMetricSpace, DataType> refTwo) {', ' ', ' // create a necw list and add the two guys in', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> ();', ' myData.add (refOne.getBoundingSphere (), refOne);', ' myData.add (refTwo.getBoundingSphere (), refTwo);', ' }', ' ', ' // this constructs a new node that holds the list of data that we were passed in', ' public InternalMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> useMe) {', ' myData = useMe; ', ' }', ' ', ' // from the interface', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // find the best child; this is the one we are closest to', ' double bestDist = 9e99;', ' int bestIndex = 0;', ' for (int i = 0; i < myData.size (); i++) {', ' ', ' double newDist = myData.get (i).getKey ().getPointInInterior ().getDistance (keyToAdd);', ' if (newDist < bestDist) {', ' bestDist = newDist;', ' bestIndex = i;', ' }', ' }', ' ', ' // do the recursive insert', ' IMTreeNodeABCD <PointInMetricSpace, DataType> newRef = myData.get (bestIndex).getData ().insert (keyToAdd, dataToAdd);', ' ', ' // if we got something back, then there was a split, so add the new node into our list', ' if (newRef != null) {', ' myData.add (newRef.getBoundingSphere (), newRef);', ' }', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> newOne = myData.splitInTwo ();', ' InternalMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.intersects (myData.get (i).getKey ())) {', ' myData.get (i).getData ().findKClosest (query, myQ);', ' }', ' }', ' }', ' ', ' // from the interface', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.intersects (myData.get (i).getKey ())) {', ' returnVal.addAll (myData.get (i).getData ().find (query));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return myData.get (0).getData ().depth () + 1; ', ' }', ' ', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', 'abstract class AMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> implements IMetricDataListABCD <PointInMetricSpace,KeyType, DataType> {', '', ' // this is the data that is actually stored in the list', ' private ArrayList <DataWrapper <KeyType, DataType>> myData;', ' ', ' // this is the sphere that bounds everything in the list', ' private SphereABCD <PointInMetricSpace> myBoundingSphere;', ' ', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myBoundingSphere; ', ' }', ' ', ' public int size () {', ' if (myData != null)', ' return myData.size (); ', ' else', ' return 0;', ' }', ' ', ' public DataWrapper <KeyType, DataType> get (int pos) {', ' return myData.get (pos);', ' }', ' ', ' public void replaceKey (int pos, KeyType keyToAdd) {', ' DataWrapper <KeyType, DataType> temp = myData.remove (pos);', ' DataWrapper <KeyType, DataType> newOne = new DataWrapper <KeyType, DataType> (keyToAdd, temp.getData ());', ' myData.add (pos, newOne);', ' }', ' ', ' public void add (KeyType keyToAdd, DataType dataToAdd) {', ' ', ' // if this is the first add, then set everyone up', ' if (myData == null) {', ' PointInMetricSpace myCentroid = keyToAdd.getPointInInterior ();', ' myBoundingSphere = new SphereABCD <PointInMetricSpace> (myCentroid, keyToAdd.maxDistanceTo (myCentroid));', ' myData = new ArrayList <DataWrapper <KeyType, DataType>> ();', ' ', ' // otherwise, extend the sphere if needed', ' } else {', ' myBoundingSphere.swallow (keyToAdd);', ' }', ' ', ' // add the data', ' myData.add (new DataWrapper <KeyType, DataType> (keyToAdd, dataToAdd));', ' }', ' ', ' // we want to potentially allow many implementations of the splitting lalgorithm', ' abstract public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // this is here so the actual splitting algorithn can access the list and change the sphere', ' protected ArrayList <DataWrapper <KeyType, DataType>> getList () {', ' return myData;', ' }', ' ', ' // this is here so the splitting algorithm can modify the list and the sphere', ' protected void replaceGuts (AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> withMe) {', ' myData = withMe.myData;', ' myBoundingSphere = withMe.myBoundingSphere;', ' }', ' ', '}', '', '// this is a particular implementation of the metric data list that uses a simple quadratic clustering', '// algorithm to perform a list split. It picks two "seeds" (the most distant objects) and then repeatedly', '// adds to the two new lists by choosing the objects closest to the seeds', 'class ChrisMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> extends AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> {', '', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo () {', ' ', ' // first, we need to find the two most distant points in the list', ' ArrayList <DataWrapper <KeyType, DataType>> myData = getList ();', ' int bestI = 0, bestJ = 0;', ' double maxDist = -1.0;', ' for (int i = 0; i < myData.size (); i++) {', ' for (int j = i + 1; j < myData.size (); j++) {', ' ', ' // get the two keys', ' DataWrapper <KeyType, DataType> pointOne = myData.get (i);', ' DataWrapper <KeyType, DataType> pointTwo = myData.get (j);', ' ', ' // find the difference between them', ' double curDist = pointOne.getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', '', ' // see if it is the biggest', ' if (curDist > maxDist) {', ' maxDist = curDist;', ' bestI = i;', ' bestJ = j;', ' }', ' }', ' }', ' ', ' // now, we have the best two points; those are seeds for the clustering', ' DataWrapper <KeyType, DataType> pointOne = myData.remove (bestI);', ' DataWrapper <KeyType, DataType> pointTwo = myData.remove (bestJ - 1);', ' ', ' // these are the two new lists', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listOne = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listTwo = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' ', ' // put the two seeds in', ' listOne.add (pointOne.getKey (), pointOne.getData ());', ' listTwo.add (pointTwo.getKey (), pointTwo.getData ());', ' ', ' // and add everyone else in', ' while (myData.size () != 0) {', ' ', ' // find the one closest to the first seed', ' int bestIndex = 0;', ' double bestDist = 9e99;', ' ', ' // loop thru all of the candidate data objects', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listOne.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' ', ' // break if no more data', ' if (myData.size () == 0)', ' break;', ' ', ' // loop thru all of the candidate data objects', ' bestDist = 9e99;', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listTwo.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' }', ' ', ' // now we replace our own guts with the first list', ' replaceGuts (listOne);', ' ', ' // and return the other list', ' return listTwo;', ' }', '}', '', 'interface IMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> {', ' ', ' // add a new pair to the list', ' public void add (KeyType keyToAdd, DataType dataToAdd);', ' ', ' // replace a key at the indicated position', ' public void replaceKey (int pos, KeyType keyToAdd);', ' ', ' // get the key, data pair that resides at a particular position', ' public DataWrapper <KeyType, DataType> get (int pos);', ' ', ' // return the number of items in the list', ' public int size ();', ' ', ' // split the list in two, using some clutering algorithm', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // get a sphere that totally bounds all of the objects in the list', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class MTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public MTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class SCMTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public SCMTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', '', 'public class MTreeTester extends TestCase {', ' ', ' // compare two lists of strings to see if the contents are the same', ' private boolean compareStringSets (ArrayList <String> setOne, ArrayList <String> setTwo) {', ' ', ' // sort the sets and make sure they are the same', ' boolean returnVal = true;', ' if (setOne.size () == setTwo.size ()) {', ' Collections.sort (setOne);', ' Collections.sort (setTwo);', ' for (int i = 0; i < setOne.size (); i++) {', ' if (!setOne.get (i).equals (setTwo.get (i))) {', ' returnVal = false;', ' break; ', ' }', ' }', ' } else {', ' returnVal = false;', ' }', ' ', ' // print out the result', ' System.out.println ("**** Expected:");', ' for (int i = 0; i < setOne.size (); i++) {', ' System.out.format (setOne.get (i) + " ");', ' }', ' System.out.println ("\\n**** Got:");', ' for (int i = 0; i < setTwo.size (); i++) {', ' System.out.format (setTwo.get (i) + " ");', ' }', ' System.out.println ("");', ' ', ' return returnVal;', ' }', ' ', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST SIMPLE ONE DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testOneDimRangeQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.find (query, expectedQuerySize / 2);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.find (query, expectedQuerySize / 2);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (numPoints);', ' result1 = myTree.find (query, expectedQuerySize);', ' result2 = hisTree.find (query, expectedQuerySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // like the last one, but runs a top k', ' private void testOneDimTopKQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (167);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.findKClosest (query, querySize);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (0);', ' result1 = myTree.findKClosest (query, querySize);', ' result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST MULTI-DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimRangeQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' double dist1 = 0;', ' double dist2 = 0;', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' dist1 = Math.sqrt (numDims) * expectedQuerySize / 2.0;', ' dist2 = Math.sqrt (numDims) * expectedQuerySize;', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' // do a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, (int) expectedQuerySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = myTree.findKClosest (query2, (int) expectedQuerySize);', ' ', ' // find the distance to the furthest point in both cases', ' for (int i = 0; i < (int) expectedQuerySize; i++) {', ' double newDist = result1.get (i).getKey ().getDistance (query1);', ' if (newDist > dist1)', ' dist1 = newDist;', ' newDist = result2.get (i).getKey ().getDistance (query2);', ' if (newDist > dist2)', ' dist2 = newDist;', ' }', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.find (query1, dist1);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.find (query1, dist1);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.find (query2, dist2);', ' result2 = hisTree.find (query2, dist2);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimTopKQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, querySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.findKClosest (query1, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.findKClosest (query2, querySize);', ' result2 = hisTree.findKClosest (query2, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' ', ' /**', ' * "TIER 1" TESTS', ' * NONE OF THESE REQUIRE ANY SPLITS', ' */', ' public void testEasy1() {', ' testOneDimRangeQuery (true, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy2() {', ' testOneDimRangeQuery (false, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy3() {', ' testOneDimRangeQuery (true, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy4() {', ' testOneDimRangeQuery (false, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy5() {', ' testMultiDimRangeQuery (true, 1, 5, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy6() {', ' testMultiDimRangeQuery (false, 1, 10, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy7() {', ' testMultiDimRangeQuery (true, 1, 5, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy8() {', ' testMultiDimRangeQuery (false, 1, 15, 10000, 10000, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 2" TESTS', ' * NONE OF THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testMod1() {', ' testOneDimRangeQuery (true, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod2() {', ' testOneDimRangeQuery (false, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod3() {', ' testOneDimRangeQuery (true, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod4() {', ' testOneDimRangeQuery (false, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod5() {', ' testMultiDimRangeQuery (true, 2, 5, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod6() {', ' testMultiDimRangeQuery (false, 2, 10, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod7() {', ' testMultiDimRangeQuery (true, 2, 5, 10000, 100, 1000, 10);', ' }', ' ', ' public void testMod8() {', ' testMultiDimRangeQuery (false, 2, 15, 10000, 100, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 3" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testHard1() {', ' testOneDimRangeQuery (true, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard2() {', ' testOneDimRangeQuery (false, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard3() {', ' testOneDimRangeQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard4() {', ' testOneDimRangeQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard5() {', ' testMultiDimRangeQuery (true, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard6() {', ' testMultiDimRangeQuery (false, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard7() {', ' testMultiDimRangeQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard8() {', ' testMultiDimRangeQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', ' ', ' /**', ' * "TIER 4" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE AND THEY TEST THE TOPK FUNCTIONALITY', ' */', ' ', ' public void testTopK1() {', ' testOneDimTopKQuery (true, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK2() {', ' testOneDimTopKQuery (false, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK3() {', ' testOneDimTopKQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK4() {', ' testOneDimTopKQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK5() {', ' testMultiDimTopKQuery (true, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK6() {', ' testMultiDimTopKQuery (false, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK7() {', ' testMultiDimTopKQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK8() {', ' testMultiDimTopKQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', '}'] | [{'reason_category': 'If Body', 'usage_line': 379}, {'reason_category': 'If Body', 'usage_line': 380}, {'reason_category': 'If Body', 'usage_line': 381}, {'reason_category': 'If Body', 'usage_line': 382}] | Class 'PointABCD' used at line 379 is defined at line 157 and has a Long-Range dependency.
Global_Variable 'myData' used at line 379 is defined at line 355 and has a Medium-Range dependency.
Class 'LeafMTreeNodeABCD' used at line 380 is defined at line 351 and has a Medium-Range dependency.
Variable 'newOne' used at line 380 is defined at line 379 and has a Short-Range dependency.
Variable 'returnVal' used at line 381 is defined at line 380 and has a Short-Range dependency. | {'If Body': 4} | {'Class Long-Range': 1, 'Global_Variable Medium-Range': 1, 'Class Medium-Range': 1, 'Variable Short-Range': 2} |
infilling_java | MTreeTester | 392 | 394 | ['import junit.framework.TestCase;', 'import java.util.ArrayList;', 'import java.util.Random;', 'import java.util.Collections;', '', '// this is a map from a set of keys of type PointInMetricSpace to a', '// set of data of type DataType', 'interface IMTree <Key extends IPointInMetricSpace <Key>, Data> {', ' ', ' // insert a new key/data pair into the map', ' void insert (Key keyToAdd, Data dataToAdd);', ' ', ' // find all of the key/data pairs in the map that fall within a', ' // particular distance of query point if no results are found, then', ' // an empty array is returned (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> find (Key query, double distance);', ' ', ' // find the k closest key/data pairs in the map to a particular', ' // query point ', ' //', ' // if the number of points in the map is less than k, then the', ' // returned list will have less than k pairs in it', ' //', ' // if the number of points is zero, then an empty array is returned', ' // (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> findKClosest (Key query, int k);', ' ', ' // returns the number of nodes that exist on a path from root to leaf in the tree...', ' // whtever the details of the implementation are, a tree with a single leaf node should return 1, and a tree', ' // with more than one lead node should return at least two (since it must have at least one internal node).', ' public int depth ();', ' ', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', '', 'interface IDoubleVector {', '', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '', '// this correponds to some geometric object in a metric space; the object is built out of', '// one or more points of type PointInMetricSpace', 'interface IObjectInMetricSpaceABCD <PointInMetricSpace extends IPointInMetricSpace<PointInMetricSpace>> {', ' ', ' // get the maximum distance from some point on the shape to a particular point in the metric space', ' double maxDistanceTo (PointInMetricSpace checkMe);', ' ', ' // return some arbitrary point on the interior of the geometric object', ' PointInMetricSpace getPointInInterior ();', '}', '', '', '// this interface corresponds to a point in some metric space', 'interface IPointInMetricSpace <PointInMetricSpace> {', ' ', ' // get the distance to another point', ' // ', ' // for this to work in an M-Tree, distances should be "metric" and', ' // obey the triangle inequality', ' double getDistance (PointInMetricSpace toMe);', '}', '', '// this is the basic node type in the structure', 'interface IMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> {', ' ', ' // insert a new key/data pair into the structure. The return value is a new MTreeNode if there was', ' // a split in response to the insertion, or a null if there was no split', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd);', ' ', ' // find all of the key/data pairs in the structure that fall within a particular query sphere', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query); ', ' ', ' // find the set of items closest to the given query point', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ);', ' ', ' // returns a sphere that totally encompasses everything in the node and its subtree', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', ' ', ' // returns the depth', ' public int depth ();', '}', '', '// this is a point in a particular metric space', 'class PointABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the point', ' private PointInMetricSpace me;', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return me; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return checkMe.getDistance (me); ', ' }', ' ', ' // contruct a point', ' public PointABCD (PointInMetricSpace useMe) {', ' me = useMe; ', ' }', '}', '', 'class PQueueABCD <PointInMetricSpace, DataType> {', ' ', ' // this is an object in the queue', ' private class Wrapper {', ' DataWrapper <PointInMetricSpace, DataType> myData;', ' double distance;', ' }', ' ', ' // this is the actual queue', ' ArrayList <Wrapper> myList;', ' ', ' // this is the largest distance value currently in the queue', ' double large;', ' ', ' // this is the max number of objects', ' int maxCount;', ' ', ' // create a priority queue with the speced number of slots', ' PQueueABCD (int maxCountIn) {', ' maxCount = maxCountIn;', ' myList = new ArrayList <Wrapper> ();', ' large = 9e99;', ' }', ' ', ' // get the largest distance in the queue', ' double getDist () {', ' return large;', ' }', ' ', ' // add a new object to the queue... the insertion is ignored if the distance value', ' // exceeds the largest that is in the queue and the queue is already full', ' void insert (PointInMetricSpace key, DataType data, double distance) {', ' ', ' // if we are full, remove the one with the largest distance', ' if (myList.size () == maxCount && distance < large) {', ' ', ' int badIndex = 0;', ' double maxDist = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > maxDist) {', ' maxDist = myList.get (i).distance;', ' badIndex = i;', ' }', ' }', ' ', ' myList.remove (badIndex);', ' }', ' ', ' // see if there is room', ' if (myList.size () < maxCount) {', ' ', ' // add it ', ' Wrapper newOne = new Wrapper ();', ' newOne.myData = new DataWrapper <PointInMetricSpace, DataType> (key, data);', ' newOne.distance = distance;', ' myList.add (newOne); ', ' }', ' ', ' // if we are full, reset the max distance', ' if (myList.size () == maxCount) {', ' large = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > large) {', ' large = myList.get (i).distance;', ' }', ' }', ' }', ' ', ' }', ' ', ' // extracts the contents of the queue', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> done () {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' for (int i = 0; i < myList.size (); i++) {', ' returnVal.add (myList.get (i).myData); ', ' }', ' ', ' return returnVal;', ' }', ' ', '}', '', '// this is a sphere in a particular metric space', 'class SphereABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the center of the sphere and its radius', ' private PointInMetricSpace center;', ' private double radius;', ' ', ' // build a sphere out of its center and its radius', ' public SphereABCD (PointInMetricSpace centerIn, double radiusIn) {', ' center = centerIn;', ' radius = radiusIn;', ' }', ' ', ' // increase the size of the sphere so it contains the object swallowMe', ' public void swallow (IObjectInMetricSpaceABCD <PointInMetricSpace> swallowMe) {', ' ', ' // see if we need to increase the radius to swallow this guy', ' double dist = swallowMe.maxDistanceTo (center);', ' if (dist > radius)', ' radius = dist;', ' }', ' ', ' // check to see if a sphere intersects another sphere', ' public boolean intersects (SphereABCD <PointInMetricSpace> me) {', ' return (me.center.getDistance (center) <= me.radius + radius);', ' }', ' ', ' // check to see if the sphere contains a point', ' public boolean contains (PointInMetricSpace checkMe) {', ' return (checkMe.getDistance (center) <= radius);', ' }', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return center; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return radius + checkMe.getDistance (center); ', ' }', '}', '', '', '', 'class OneDimPoint implements IPointInMetricSpace <OneDimPoint> {', ' ', ' // this is the actual double', ' Double value;', ' ', ' // construct this out of a double value', ' public OneDimPoint (double makeFromMe) {', ' value = new Double (makeFromMe);', ' }', ' ', ' // get the distance to another point', ' public double getDistance (OneDimPoint toMe) {', ' if (value > toMe.value)', ' return value - toMe.value;', ' else', ' return toMe.value - value;', ' }', ' ', '}', '', 'class MultiDimPoint implements IPointInMetricSpace <MultiDimPoint> {', ' ', ' // this is the point in a multidimensional space', ' IDoubleVector me;', ' ', ' // make this out of an IDoubleVector', ' public MultiDimPoint (IDoubleVector useMe) {', ' me = useMe;', ' }', ' ', ' // get the Euclidean distance to another point', ' public double getDistance (MultiDimPoint toMe) {', ' double distance = 0.0;', ' try {', ' for (int i = 0; i < me.getLength (); i++) {', ' double diff = me.getItem (i) - toMe.me.getItem (i);', ' diff *= diff;', ' distance += diff;', ' }', ' } catch (OutOfBoundsException e) {', ' throw new IndexOutOfBoundsException ("Can\'t compare two MultiDimPoint objects with different dimensionality!"); ', ' }', ' return Math.sqrt(distance);', ' }', ' ', '}', '// this is a leaf node', 'class LeafMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements ', ' IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myData;', ' ', ' // contructor that takes a data list and builds a node out of it', ' private LeafMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myDataIn) {', ' myData = myDataIn; ', ' }', ' ', ' // constructor that creates an empty node', ' public LeafMTreeNodeABCD () {', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> (); ', ' }', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // just add in the new data', ' myData.add (new PointABCD <PointInMetricSpace> (keyToAdd), dataToAdd);', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> newOne = myData.splitInTwo ();', ' LeafMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.contains (myData.get (i).getKey ().getPointInInterior ())) {'] | [' myQ.insert (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData (), ', ' query.getDistance (myData.get (i).getKey ().getPointInInterior ()));', ' }'] | [' }', ' }', ' ', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' returnVal.add (new DataWrapper <PointInMetricSpace, DataType> (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData ()));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return 1; ', ' }', '', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', '// this silly little class is just a wrapper for a key, data pair', 'class DataWrapper <Key, Data> {', ' ', ' Key key;', ' Data data;', ' ', ' public DataWrapper (Key keyIn, Data dataIn) {', ' key = keyIn;', ' data = dataIn;', ' }', ' ', ' public Key getKey () {', ' return key;', ' }', ' ', ' public Data getData () {', ' return data;', ' }', '}', '', '', '// this is an internal node', 'class InternalMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType>', ' implements IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> myData;', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' // this constructs a new internal node that holds precisely the two nodes that are passed in', ' public InternalMTreeNodeABCD (IMTreeNodeABCD <PointInMetricSpace, DataType> refOne,', ' IMTreeNodeABCD <PointInMetricSpace, DataType> refTwo) {', ' ', ' // create a necw list and add the two guys in', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> ();', ' myData.add (refOne.getBoundingSphere (), refOne);', ' myData.add (refTwo.getBoundingSphere (), refTwo);', ' }', ' ', ' // this constructs a new node that holds the list of data that we were passed in', ' public InternalMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> useMe) {', ' myData = useMe; ', ' }', ' ', ' // from the interface', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // find the best child; this is the one we are closest to', ' double bestDist = 9e99;', ' int bestIndex = 0;', ' for (int i = 0; i < myData.size (); i++) {', ' ', ' double newDist = myData.get (i).getKey ().getPointInInterior ().getDistance (keyToAdd);', ' if (newDist < bestDist) {', ' bestDist = newDist;', ' bestIndex = i;', ' }', ' }', ' ', ' // do the recursive insert', ' IMTreeNodeABCD <PointInMetricSpace, DataType> newRef = myData.get (bestIndex).getData ().insert (keyToAdd, dataToAdd);', ' ', ' // if we got something back, then there was a split, so add the new node into our list', ' if (newRef != null) {', ' myData.add (newRef.getBoundingSphere (), newRef);', ' }', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> newOne = myData.splitInTwo ();', ' InternalMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.intersects (myData.get (i).getKey ())) {', ' myData.get (i).getData ().findKClosest (query, myQ);', ' }', ' }', ' }', ' ', ' // from the interface', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.intersects (myData.get (i).getKey ())) {', ' returnVal.addAll (myData.get (i).getData ().find (query));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return myData.get (0).getData ().depth () + 1; ', ' }', ' ', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', 'abstract class AMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> implements IMetricDataListABCD <PointInMetricSpace,KeyType, DataType> {', '', ' // this is the data that is actually stored in the list', ' private ArrayList <DataWrapper <KeyType, DataType>> myData;', ' ', ' // this is the sphere that bounds everything in the list', ' private SphereABCD <PointInMetricSpace> myBoundingSphere;', ' ', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myBoundingSphere; ', ' }', ' ', ' public int size () {', ' if (myData != null)', ' return myData.size (); ', ' else', ' return 0;', ' }', ' ', ' public DataWrapper <KeyType, DataType> get (int pos) {', ' return myData.get (pos);', ' }', ' ', ' public void replaceKey (int pos, KeyType keyToAdd) {', ' DataWrapper <KeyType, DataType> temp = myData.remove (pos);', ' DataWrapper <KeyType, DataType> newOne = new DataWrapper <KeyType, DataType> (keyToAdd, temp.getData ());', ' myData.add (pos, newOne);', ' }', ' ', ' public void add (KeyType keyToAdd, DataType dataToAdd) {', ' ', ' // if this is the first add, then set everyone up', ' if (myData == null) {', ' PointInMetricSpace myCentroid = keyToAdd.getPointInInterior ();', ' myBoundingSphere = new SphereABCD <PointInMetricSpace> (myCentroid, keyToAdd.maxDistanceTo (myCentroid));', ' myData = new ArrayList <DataWrapper <KeyType, DataType>> ();', ' ', ' // otherwise, extend the sphere if needed', ' } else {', ' myBoundingSphere.swallow (keyToAdd);', ' }', ' ', ' // add the data', ' myData.add (new DataWrapper <KeyType, DataType> (keyToAdd, dataToAdd));', ' }', ' ', ' // we want to potentially allow many implementations of the splitting lalgorithm', ' abstract public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // this is here so the actual splitting algorithn can access the list and change the sphere', ' protected ArrayList <DataWrapper <KeyType, DataType>> getList () {', ' return myData;', ' }', ' ', ' // this is here so the splitting algorithm can modify the list and the sphere', ' protected void replaceGuts (AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> withMe) {', ' myData = withMe.myData;', ' myBoundingSphere = withMe.myBoundingSphere;', ' }', ' ', '}', '', '// this is a particular implementation of the metric data list that uses a simple quadratic clustering', '// algorithm to perform a list split. It picks two "seeds" (the most distant objects) and then repeatedly', '// adds to the two new lists by choosing the objects closest to the seeds', 'class ChrisMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> extends AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> {', '', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo () {', ' ', ' // first, we need to find the two most distant points in the list', ' ArrayList <DataWrapper <KeyType, DataType>> myData = getList ();', ' int bestI = 0, bestJ = 0;', ' double maxDist = -1.0;', ' for (int i = 0; i < myData.size (); i++) {', ' for (int j = i + 1; j < myData.size (); j++) {', ' ', ' // get the two keys', ' DataWrapper <KeyType, DataType> pointOne = myData.get (i);', ' DataWrapper <KeyType, DataType> pointTwo = myData.get (j);', ' ', ' // find the difference between them', ' double curDist = pointOne.getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', '', ' // see if it is the biggest', ' if (curDist > maxDist) {', ' maxDist = curDist;', ' bestI = i;', ' bestJ = j;', ' }', ' }', ' }', ' ', ' // now, we have the best two points; those are seeds for the clustering', ' DataWrapper <KeyType, DataType> pointOne = myData.remove (bestI);', ' DataWrapper <KeyType, DataType> pointTwo = myData.remove (bestJ - 1);', ' ', ' // these are the two new lists', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listOne = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listTwo = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' ', ' // put the two seeds in', ' listOne.add (pointOne.getKey (), pointOne.getData ());', ' listTwo.add (pointTwo.getKey (), pointTwo.getData ());', ' ', ' // and add everyone else in', ' while (myData.size () != 0) {', ' ', ' // find the one closest to the first seed', ' int bestIndex = 0;', ' double bestDist = 9e99;', ' ', ' // loop thru all of the candidate data objects', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listOne.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' ', ' // break if no more data', ' if (myData.size () == 0)', ' break;', ' ', ' // loop thru all of the candidate data objects', ' bestDist = 9e99;', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listTwo.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' }', ' ', ' // now we replace our own guts with the first list', ' replaceGuts (listOne);', ' ', ' // and return the other list', ' return listTwo;', ' }', '}', '', 'interface IMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> {', ' ', ' // add a new pair to the list', ' public void add (KeyType keyToAdd, DataType dataToAdd);', ' ', ' // replace a key at the indicated position', ' public void replaceKey (int pos, KeyType keyToAdd);', ' ', ' // get the key, data pair that resides at a particular position', ' public DataWrapper <KeyType, DataType> get (int pos);', ' ', ' // return the number of items in the list', ' public int size ();', ' ', ' // split the list in two, using some clutering algorithm', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // get a sphere that totally bounds all of the objects in the list', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class MTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public MTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class SCMTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public SCMTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', '', 'public class MTreeTester extends TestCase {', ' ', ' // compare two lists of strings to see if the contents are the same', ' private boolean compareStringSets (ArrayList <String> setOne, ArrayList <String> setTwo) {', ' ', ' // sort the sets and make sure they are the same', ' boolean returnVal = true;', ' if (setOne.size () == setTwo.size ()) {', ' Collections.sort (setOne);', ' Collections.sort (setTwo);', ' for (int i = 0; i < setOne.size (); i++) {', ' if (!setOne.get (i).equals (setTwo.get (i))) {', ' returnVal = false;', ' break; ', ' }', ' }', ' } else {', ' returnVal = false;', ' }', ' ', ' // print out the result', ' System.out.println ("**** Expected:");', ' for (int i = 0; i < setOne.size (); i++) {', ' System.out.format (setOne.get (i) + " ");', ' }', ' System.out.println ("\\n**** Got:");', ' for (int i = 0; i < setTwo.size (); i++) {', ' System.out.format (setTwo.get (i) + " ");', ' }', ' System.out.println ("");', ' ', ' return returnVal;', ' }', ' ', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST SIMPLE ONE DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testOneDimRangeQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.find (query, expectedQuerySize / 2);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.find (query, expectedQuerySize / 2);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (numPoints);', ' result1 = myTree.find (query, expectedQuerySize);', ' result2 = hisTree.find (query, expectedQuerySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // like the last one, but runs a top k', ' private void testOneDimTopKQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (167);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.findKClosest (query, querySize);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (0);', ' result1 = myTree.findKClosest (query, querySize);', ' result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST MULTI-DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimRangeQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' double dist1 = 0;', ' double dist2 = 0;', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' dist1 = Math.sqrt (numDims) * expectedQuerySize / 2.0;', ' dist2 = Math.sqrt (numDims) * expectedQuerySize;', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' // do a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, (int) expectedQuerySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = myTree.findKClosest (query2, (int) expectedQuerySize);', ' ', ' // find the distance to the furthest point in both cases', ' for (int i = 0; i < (int) expectedQuerySize; i++) {', ' double newDist = result1.get (i).getKey ().getDistance (query1);', ' if (newDist > dist1)', ' dist1 = newDist;', ' newDist = result2.get (i).getKey ().getDistance (query2);', ' if (newDist > dist2)', ' dist2 = newDist;', ' }', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.find (query1, dist1);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.find (query1, dist1);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.find (query2, dist2);', ' result2 = hisTree.find (query2, dist2);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimTopKQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, querySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.findKClosest (query1, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.findKClosest (query2, querySize);', ' result2 = hisTree.findKClosest (query2, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' ', ' /**', ' * "TIER 1" TESTS', ' * NONE OF THESE REQUIRE ANY SPLITS', ' */', ' public void testEasy1() {', ' testOneDimRangeQuery (true, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy2() {', ' testOneDimRangeQuery (false, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy3() {', ' testOneDimRangeQuery (true, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy4() {', ' testOneDimRangeQuery (false, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy5() {', ' testMultiDimRangeQuery (true, 1, 5, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy6() {', ' testMultiDimRangeQuery (false, 1, 10, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy7() {', ' testMultiDimRangeQuery (true, 1, 5, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy8() {', ' testMultiDimRangeQuery (false, 1, 15, 10000, 10000, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 2" TESTS', ' * NONE OF THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testMod1() {', ' testOneDimRangeQuery (true, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod2() {', ' testOneDimRangeQuery (false, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod3() {', ' testOneDimRangeQuery (true, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod4() {', ' testOneDimRangeQuery (false, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod5() {', ' testMultiDimRangeQuery (true, 2, 5, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod6() {', ' testMultiDimRangeQuery (false, 2, 10, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod7() {', ' testMultiDimRangeQuery (true, 2, 5, 10000, 100, 1000, 10);', ' }', ' ', ' public void testMod8() {', ' testMultiDimRangeQuery (false, 2, 15, 10000, 100, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 3" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testHard1() {', ' testOneDimRangeQuery (true, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard2() {', ' testOneDimRangeQuery (false, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard3() {', ' testOneDimRangeQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard4() {', ' testOneDimRangeQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard5() {', ' testMultiDimRangeQuery (true, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard6() {', ' testMultiDimRangeQuery (false, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard7() {', ' testMultiDimRangeQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard8() {', ' testMultiDimRangeQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', ' ', ' /**', ' * "TIER 4" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE AND THEY TEST THE TOPK FUNCTIONALITY', ' */', ' ', ' public void testTopK1() {', ' testOneDimTopKQuery (true, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK2() {', ' testOneDimTopKQuery (false, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK3() {', ' testOneDimTopKQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK4() {', ' testOneDimTopKQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK5() {', ' testMultiDimTopKQuery (true, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK6() {', ' testMultiDimTopKQuery (false, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK7() {', ' testMultiDimTopKQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK8() {', ' testMultiDimTopKQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', '}'] | [{'reason_category': 'Loop Body', 'usage_line': 392}, {'reason_category': 'If Body', 'usage_line': 392}, {'reason_category': 'Loop Body', 'usage_line': 393}, {'reason_category': 'If Body', 'usage_line': 393}, {'reason_category': 'Loop Body', 'usage_line': 394}, {'reason_category': 'If Body', 'usage_line': 394}] | Variable 'myQ' used at line 392 is defined at line 388 and has a Short-Range dependency.
Global_Variable 'myData' used at line 392 is defined at line 355 and has a Long-Range dependency.
Variable 'i' used at line 392 is defined at line 389 and has a Short-Range dependency.
Function 'getKey' used at line 392 is defined at line 439 and has a Long-Range dependency.
Function 'getPointInInterior' used at line 392 is defined at line 122 and has a Long-Range dependency.
Function 'getData' used at line 392 is defined at line 443 and has a Long-Range dependency.
Variable 'query' used at line 393 is defined at line 388 and has a Short-Range dependency.
Global_Variable 'myData' used at line 393 is defined at line 355 and has a Long-Range dependency.
Variable 'i' used at line 393 is defined at line 389 and has a Short-Range dependency.
Function 'getKey' used at line 393 is defined at line 439 and has a Long-Range dependency.
Function 'getPointInInterior' used at line 393 is defined at line 122 and has a Long-Range dependency. | {'Loop Body': 3, 'If Body': 3} | {'Variable Short-Range': 4, 'Global_Variable Long-Range': 2, 'Function Long-Range': 5} |
infilling_java | MTreeTester | 391 | 395 | ['import junit.framework.TestCase;', 'import java.util.ArrayList;', 'import java.util.Random;', 'import java.util.Collections;', '', '// this is a map from a set of keys of type PointInMetricSpace to a', '// set of data of type DataType', 'interface IMTree <Key extends IPointInMetricSpace <Key>, Data> {', ' ', ' // insert a new key/data pair into the map', ' void insert (Key keyToAdd, Data dataToAdd);', ' ', ' // find all of the key/data pairs in the map that fall within a', ' // particular distance of query point if no results are found, then', ' // an empty array is returned (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> find (Key query, double distance);', ' ', ' // find the k closest key/data pairs in the map to a particular', ' // query point ', ' //', ' // if the number of points in the map is less than k, then the', ' // returned list will have less than k pairs in it', ' //', ' // if the number of points is zero, then an empty array is returned', ' // (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> findKClosest (Key query, int k);', ' ', ' // returns the number of nodes that exist on a path from root to leaf in the tree...', ' // whtever the details of the implementation are, a tree with a single leaf node should return 1, and a tree', ' // with more than one lead node should return at least two (since it must have at least one internal node).', ' public int depth ();', ' ', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', '', 'interface IDoubleVector {', '', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '', '// this correponds to some geometric object in a metric space; the object is built out of', '// one or more points of type PointInMetricSpace', 'interface IObjectInMetricSpaceABCD <PointInMetricSpace extends IPointInMetricSpace<PointInMetricSpace>> {', ' ', ' // get the maximum distance from some point on the shape to a particular point in the metric space', ' double maxDistanceTo (PointInMetricSpace checkMe);', ' ', ' // return some arbitrary point on the interior of the geometric object', ' PointInMetricSpace getPointInInterior ();', '}', '', '', '// this interface corresponds to a point in some metric space', 'interface IPointInMetricSpace <PointInMetricSpace> {', ' ', ' // get the distance to another point', ' // ', ' // for this to work in an M-Tree, distances should be "metric" and', ' // obey the triangle inequality', ' double getDistance (PointInMetricSpace toMe);', '}', '', '// this is the basic node type in the structure', 'interface IMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> {', ' ', ' // insert a new key/data pair into the structure. The return value is a new MTreeNode if there was', ' // a split in response to the insertion, or a null if there was no split', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd);', ' ', ' // find all of the key/data pairs in the structure that fall within a particular query sphere', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query); ', ' ', ' // find the set of items closest to the given query point', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ);', ' ', ' // returns a sphere that totally encompasses everything in the node and its subtree', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', ' ', ' // returns the depth', ' public int depth ();', '}', '', '// this is a point in a particular metric space', 'class PointABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the point', ' private PointInMetricSpace me;', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return me; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return checkMe.getDistance (me); ', ' }', ' ', ' // contruct a point', ' public PointABCD (PointInMetricSpace useMe) {', ' me = useMe; ', ' }', '}', '', 'class PQueueABCD <PointInMetricSpace, DataType> {', ' ', ' // this is an object in the queue', ' private class Wrapper {', ' DataWrapper <PointInMetricSpace, DataType> myData;', ' double distance;', ' }', ' ', ' // this is the actual queue', ' ArrayList <Wrapper> myList;', ' ', ' // this is the largest distance value currently in the queue', ' double large;', ' ', ' // this is the max number of objects', ' int maxCount;', ' ', ' // create a priority queue with the speced number of slots', ' PQueueABCD (int maxCountIn) {', ' maxCount = maxCountIn;', ' myList = new ArrayList <Wrapper> ();', ' large = 9e99;', ' }', ' ', ' // get the largest distance in the queue', ' double getDist () {', ' return large;', ' }', ' ', ' // add a new object to the queue... the insertion is ignored if the distance value', ' // exceeds the largest that is in the queue and the queue is already full', ' void insert (PointInMetricSpace key, DataType data, double distance) {', ' ', ' // if we are full, remove the one with the largest distance', ' if (myList.size () == maxCount && distance < large) {', ' ', ' int badIndex = 0;', ' double maxDist = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > maxDist) {', ' maxDist = myList.get (i).distance;', ' badIndex = i;', ' }', ' }', ' ', ' myList.remove (badIndex);', ' }', ' ', ' // see if there is room', ' if (myList.size () < maxCount) {', ' ', ' // add it ', ' Wrapper newOne = new Wrapper ();', ' newOne.myData = new DataWrapper <PointInMetricSpace, DataType> (key, data);', ' newOne.distance = distance;', ' myList.add (newOne); ', ' }', ' ', ' // if we are full, reset the max distance', ' if (myList.size () == maxCount) {', ' large = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > large) {', ' large = myList.get (i).distance;', ' }', ' }', ' }', ' ', ' }', ' ', ' // extracts the contents of the queue', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> done () {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' for (int i = 0; i < myList.size (); i++) {', ' returnVal.add (myList.get (i).myData); ', ' }', ' ', ' return returnVal;', ' }', ' ', '}', '', '// this is a sphere in a particular metric space', 'class SphereABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the center of the sphere and its radius', ' private PointInMetricSpace center;', ' private double radius;', ' ', ' // build a sphere out of its center and its radius', ' public SphereABCD (PointInMetricSpace centerIn, double radiusIn) {', ' center = centerIn;', ' radius = radiusIn;', ' }', ' ', ' // increase the size of the sphere so it contains the object swallowMe', ' public void swallow (IObjectInMetricSpaceABCD <PointInMetricSpace> swallowMe) {', ' ', ' // see if we need to increase the radius to swallow this guy', ' double dist = swallowMe.maxDistanceTo (center);', ' if (dist > radius)', ' radius = dist;', ' }', ' ', ' // check to see if a sphere intersects another sphere', ' public boolean intersects (SphereABCD <PointInMetricSpace> me) {', ' return (me.center.getDistance (center) <= me.radius + radius);', ' }', ' ', ' // check to see if the sphere contains a point', ' public boolean contains (PointInMetricSpace checkMe) {', ' return (checkMe.getDistance (center) <= radius);', ' }', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return center; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return radius + checkMe.getDistance (center); ', ' }', '}', '', '', '', 'class OneDimPoint implements IPointInMetricSpace <OneDimPoint> {', ' ', ' // this is the actual double', ' Double value;', ' ', ' // construct this out of a double value', ' public OneDimPoint (double makeFromMe) {', ' value = new Double (makeFromMe);', ' }', ' ', ' // get the distance to another point', ' public double getDistance (OneDimPoint toMe) {', ' if (value > toMe.value)', ' return value - toMe.value;', ' else', ' return toMe.value - value;', ' }', ' ', '}', '', 'class MultiDimPoint implements IPointInMetricSpace <MultiDimPoint> {', ' ', ' // this is the point in a multidimensional space', ' IDoubleVector me;', ' ', ' // make this out of an IDoubleVector', ' public MultiDimPoint (IDoubleVector useMe) {', ' me = useMe;', ' }', ' ', ' // get the Euclidean distance to another point', ' public double getDistance (MultiDimPoint toMe) {', ' double distance = 0.0;', ' try {', ' for (int i = 0; i < me.getLength (); i++) {', ' double diff = me.getItem (i) - toMe.me.getItem (i);', ' diff *= diff;', ' distance += diff;', ' }', ' } catch (OutOfBoundsException e) {', ' throw new IndexOutOfBoundsException ("Can\'t compare two MultiDimPoint objects with different dimensionality!"); ', ' }', ' return Math.sqrt(distance);', ' }', ' ', '}', '// this is a leaf node', 'class LeafMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements ', ' IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myData;', ' ', ' // contructor that takes a data list and builds a node out of it', ' private LeafMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myDataIn) {', ' myData = myDataIn; ', ' }', ' ', ' // constructor that creates an empty node', ' public LeafMTreeNodeABCD () {', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> (); ', ' }', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // just add in the new data', ' myData.add (new PointABCD <PointInMetricSpace> (keyToAdd), dataToAdd);', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> newOne = myData.splitInTwo ();', ' LeafMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());'] | [' if (mySphere.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' myQ.insert (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData (), ', ' query.getDistance (myData.get (i).getKey ().getPointInInterior ()));', ' }', ' }'] | [' }', ' ', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' returnVal.add (new DataWrapper <PointInMetricSpace, DataType> (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData ()));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return 1; ', ' }', '', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', '// this silly little class is just a wrapper for a key, data pair', 'class DataWrapper <Key, Data> {', ' ', ' Key key;', ' Data data;', ' ', ' public DataWrapper (Key keyIn, Data dataIn) {', ' key = keyIn;', ' data = dataIn;', ' }', ' ', ' public Key getKey () {', ' return key;', ' }', ' ', ' public Data getData () {', ' return data;', ' }', '}', '', '', '// this is an internal node', 'class InternalMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType>', ' implements IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> myData;', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' // this constructs a new internal node that holds precisely the two nodes that are passed in', ' public InternalMTreeNodeABCD (IMTreeNodeABCD <PointInMetricSpace, DataType> refOne,', ' IMTreeNodeABCD <PointInMetricSpace, DataType> refTwo) {', ' ', ' // create a necw list and add the two guys in', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> ();', ' myData.add (refOne.getBoundingSphere (), refOne);', ' myData.add (refTwo.getBoundingSphere (), refTwo);', ' }', ' ', ' // this constructs a new node that holds the list of data that we were passed in', ' public InternalMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> useMe) {', ' myData = useMe; ', ' }', ' ', ' // from the interface', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // find the best child; this is the one we are closest to', ' double bestDist = 9e99;', ' int bestIndex = 0;', ' for (int i = 0; i < myData.size (); i++) {', ' ', ' double newDist = myData.get (i).getKey ().getPointInInterior ().getDistance (keyToAdd);', ' if (newDist < bestDist) {', ' bestDist = newDist;', ' bestIndex = i;', ' }', ' }', ' ', ' // do the recursive insert', ' IMTreeNodeABCD <PointInMetricSpace, DataType> newRef = myData.get (bestIndex).getData ().insert (keyToAdd, dataToAdd);', ' ', ' // if we got something back, then there was a split, so add the new node into our list', ' if (newRef != null) {', ' myData.add (newRef.getBoundingSphere (), newRef);', ' }', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> newOne = myData.splitInTwo ();', ' InternalMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.intersects (myData.get (i).getKey ())) {', ' myData.get (i).getData ().findKClosest (query, myQ);', ' }', ' }', ' }', ' ', ' // from the interface', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.intersects (myData.get (i).getKey ())) {', ' returnVal.addAll (myData.get (i).getData ().find (query));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return myData.get (0).getData ().depth () + 1; ', ' }', ' ', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', 'abstract class AMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> implements IMetricDataListABCD <PointInMetricSpace,KeyType, DataType> {', '', ' // this is the data that is actually stored in the list', ' private ArrayList <DataWrapper <KeyType, DataType>> myData;', ' ', ' // this is the sphere that bounds everything in the list', ' private SphereABCD <PointInMetricSpace> myBoundingSphere;', ' ', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myBoundingSphere; ', ' }', ' ', ' public int size () {', ' if (myData != null)', ' return myData.size (); ', ' else', ' return 0;', ' }', ' ', ' public DataWrapper <KeyType, DataType> get (int pos) {', ' return myData.get (pos);', ' }', ' ', ' public void replaceKey (int pos, KeyType keyToAdd) {', ' DataWrapper <KeyType, DataType> temp = myData.remove (pos);', ' DataWrapper <KeyType, DataType> newOne = new DataWrapper <KeyType, DataType> (keyToAdd, temp.getData ());', ' myData.add (pos, newOne);', ' }', ' ', ' public void add (KeyType keyToAdd, DataType dataToAdd) {', ' ', ' // if this is the first add, then set everyone up', ' if (myData == null) {', ' PointInMetricSpace myCentroid = keyToAdd.getPointInInterior ();', ' myBoundingSphere = new SphereABCD <PointInMetricSpace> (myCentroid, keyToAdd.maxDistanceTo (myCentroid));', ' myData = new ArrayList <DataWrapper <KeyType, DataType>> ();', ' ', ' // otherwise, extend the sphere if needed', ' } else {', ' myBoundingSphere.swallow (keyToAdd);', ' }', ' ', ' // add the data', ' myData.add (new DataWrapper <KeyType, DataType> (keyToAdd, dataToAdd));', ' }', ' ', ' // we want to potentially allow many implementations of the splitting lalgorithm', ' abstract public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // this is here so the actual splitting algorithn can access the list and change the sphere', ' protected ArrayList <DataWrapper <KeyType, DataType>> getList () {', ' return myData;', ' }', ' ', ' // this is here so the splitting algorithm can modify the list and the sphere', ' protected void replaceGuts (AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> withMe) {', ' myData = withMe.myData;', ' myBoundingSphere = withMe.myBoundingSphere;', ' }', ' ', '}', '', '// this is a particular implementation of the metric data list that uses a simple quadratic clustering', '// algorithm to perform a list split. It picks two "seeds" (the most distant objects) and then repeatedly', '// adds to the two new lists by choosing the objects closest to the seeds', 'class ChrisMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> extends AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> {', '', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo () {', ' ', ' // first, we need to find the two most distant points in the list', ' ArrayList <DataWrapper <KeyType, DataType>> myData = getList ();', ' int bestI = 0, bestJ = 0;', ' double maxDist = -1.0;', ' for (int i = 0; i < myData.size (); i++) {', ' for (int j = i + 1; j < myData.size (); j++) {', ' ', ' // get the two keys', ' DataWrapper <KeyType, DataType> pointOne = myData.get (i);', ' DataWrapper <KeyType, DataType> pointTwo = myData.get (j);', ' ', ' // find the difference between them', ' double curDist = pointOne.getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', '', ' // see if it is the biggest', ' if (curDist > maxDist) {', ' maxDist = curDist;', ' bestI = i;', ' bestJ = j;', ' }', ' }', ' }', ' ', ' // now, we have the best two points; those are seeds for the clustering', ' DataWrapper <KeyType, DataType> pointOne = myData.remove (bestI);', ' DataWrapper <KeyType, DataType> pointTwo = myData.remove (bestJ - 1);', ' ', ' // these are the two new lists', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listOne = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listTwo = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' ', ' // put the two seeds in', ' listOne.add (pointOne.getKey (), pointOne.getData ());', ' listTwo.add (pointTwo.getKey (), pointTwo.getData ());', ' ', ' // and add everyone else in', ' while (myData.size () != 0) {', ' ', ' // find the one closest to the first seed', ' int bestIndex = 0;', ' double bestDist = 9e99;', ' ', ' // loop thru all of the candidate data objects', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listOne.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' ', ' // break if no more data', ' if (myData.size () == 0)', ' break;', ' ', ' // loop thru all of the candidate data objects', ' bestDist = 9e99;', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listTwo.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' }', ' ', ' // now we replace our own guts with the first list', ' replaceGuts (listOne);', ' ', ' // and return the other list', ' return listTwo;', ' }', '}', '', 'interface IMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> {', ' ', ' // add a new pair to the list', ' public void add (KeyType keyToAdd, DataType dataToAdd);', ' ', ' // replace a key at the indicated position', ' public void replaceKey (int pos, KeyType keyToAdd);', ' ', ' // get the key, data pair that resides at a particular position', ' public DataWrapper <KeyType, DataType> get (int pos);', ' ', ' // return the number of items in the list', ' public int size ();', ' ', ' // split the list in two, using some clutering algorithm', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // get a sphere that totally bounds all of the objects in the list', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class MTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public MTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class SCMTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public SCMTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', '', 'public class MTreeTester extends TestCase {', ' ', ' // compare two lists of strings to see if the contents are the same', ' private boolean compareStringSets (ArrayList <String> setOne, ArrayList <String> setTwo) {', ' ', ' // sort the sets and make sure they are the same', ' boolean returnVal = true;', ' if (setOne.size () == setTwo.size ()) {', ' Collections.sort (setOne);', ' Collections.sort (setTwo);', ' for (int i = 0; i < setOne.size (); i++) {', ' if (!setOne.get (i).equals (setTwo.get (i))) {', ' returnVal = false;', ' break; ', ' }', ' }', ' } else {', ' returnVal = false;', ' }', ' ', ' // print out the result', ' System.out.println ("**** Expected:");', ' for (int i = 0; i < setOne.size (); i++) {', ' System.out.format (setOne.get (i) + " ");', ' }', ' System.out.println ("\\n**** Got:");', ' for (int i = 0; i < setTwo.size (); i++) {', ' System.out.format (setTwo.get (i) + " ");', ' }', ' System.out.println ("");', ' ', ' return returnVal;', ' }', ' ', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST SIMPLE ONE DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testOneDimRangeQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.find (query, expectedQuerySize / 2);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.find (query, expectedQuerySize / 2);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (numPoints);', ' result1 = myTree.find (query, expectedQuerySize);', ' result2 = hisTree.find (query, expectedQuerySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // like the last one, but runs a top k', ' private void testOneDimTopKQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (167);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.findKClosest (query, querySize);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (0);', ' result1 = myTree.findKClosest (query, querySize);', ' result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST MULTI-DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimRangeQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' double dist1 = 0;', ' double dist2 = 0;', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' dist1 = Math.sqrt (numDims) * expectedQuerySize / 2.0;', ' dist2 = Math.sqrt (numDims) * expectedQuerySize;', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' // do a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, (int) expectedQuerySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = myTree.findKClosest (query2, (int) expectedQuerySize);', ' ', ' // find the distance to the furthest point in both cases', ' for (int i = 0; i < (int) expectedQuerySize; i++) {', ' double newDist = result1.get (i).getKey ().getDistance (query1);', ' if (newDist > dist1)', ' dist1 = newDist;', ' newDist = result2.get (i).getKey ().getDistance (query2);', ' if (newDist > dist2)', ' dist2 = newDist;', ' }', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.find (query1, dist1);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.find (query1, dist1);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.find (query2, dist2);', ' result2 = hisTree.find (query2, dist2);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimTopKQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, querySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.findKClosest (query1, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.findKClosest (query2, querySize);', ' result2 = hisTree.findKClosest (query2, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' ', ' /**', ' * "TIER 1" TESTS', ' * NONE OF THESE REQUIRE ANY SPLITS', ' */', ' public void testEasy1() {', ' testOneDimRangeQuery (true, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy2() {', ' testOneDimRangeQuery (false, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy3() {', ' testOneDimRangeQuery (true, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy4() {', ' testOneDimRangeQuery (false, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy5() {', ' testMultiDimRangeQuery (true, 1, 5, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy6() {', ' testMultiDimRangeQuery (false, 1, 10, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy7() {', ' testMultiDimRangeQuery (true, 1, 5, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy8() {', ' testMultiDimRangeQuery (false, 1, 15, 10000, 10000, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 2" TESTS', ' * NONE OF THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testMod1() {', ' testOneDimRangeQuery (true, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod2() {', ' testOneDimRangeQuery (false, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod3() {', ' testOneDimRangeQuery (true, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod4() {', ' testOneDimRangeQuery (false, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod5() {', ' testMultiDimRangeQuery (true, 2, 5, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod6() {', ' testMultiDimRangeQuery (false, 2, 10, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod7() {', ' testMultiDimRangeQuery (true, 2, 5, 10000, 100, 1000, 10);', ' }', ' ', ' public void testMod8() {', ' testMultiDimRangeQuery (false, 2, 15, 10000, 100, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 3" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testHard1() {', ' testOneDimRangeQuery (true, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard2() {', ' testOneDimRangeQuery (false, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard3() {', ' testOneDimRangeQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard4() {', ' testOneDimRangeQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard5() {', ' testMultiDimRangeQuery (true, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard6() {', ' testMultiDimRangeQuery (false, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard7() {', ' testMultiDimRangeQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard8() {', ' testMultiDimRangeQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', ' ', ' /**', ' * "TIER 4" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE AND THEY TEST THE TOPK FUNCTIONALITY', ' */', ' ', ' public void testTopK1() {', ' testOneDimTopKQuery (true, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK2() {', ' testOneDimTopKQuery (false, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK3() {', ' testOneDimTopKQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK4() {', ' testOneDimTopKQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK5() {', ' testMultiDimTopKQuery (true, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK6() {', ' testMultiDimTopKQuery (false, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK7() {', ' testMultiDimTopKQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK8() {', ' testMultiDimTopKQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', '}'] | [{'reason_category': 'Loop Body', 'usage_line': 391}, {'reason_category': 'If Condition', 'usage_line': 391}, {'reason_category': 'Loop Body', 'usage_line': 392}, {'reason_category': 'If Body', 'usage_line': 392}, {'reason_category': 'Loop Body', 'usage_line': 393}, {'reason_category': 'If Body', 'usage_line': 393}, {'reason_category': 'Loop Body', 'usage_line': 394}, {'reason_category': 'If Body', 'usage_line': 394}, {'reason_category': 'Loop Body', 'usage_line': 395}] | Function 'SphereABCD.contains' used at line 391 is defined at line 289 and has a Long-Range dependency.
Global_Variable 'myData' used at line 391 is defined at line 355 and has a Long-Range dependency.
Variable 'i' used at line 391 is defined at line 389 and has a Short-Range dependency.
Function 'getKey' used at line 391 is defined at line 439 and has a Long-Range dependency.
Function 'getPointInInterior' used at line 391 is defined at line 122 and has a Long-Range dependency.
Variable 'myQ' used at line 392 is defined at line 388 and has a Short-Range dependency.
Global_Variable 'myData' used at line 392 is defined at line 355 and has a Long-Range dependency.
Variable 'i' used at line 392 is defined at line 389 and has a Short-Range dependency.
Function 'getKey' used at line 392 is defined at line 439 and has a Long-Range dependency.
Function 'getPointInInterior' used at line 392 is defined at line 122 and has a Long-Range dependency.
Function 'getData' used at line 392 is defined at line 443 and has a Long-Range dependency.
Variable 'query' used at line 393 is defined at line 388 and has a Short-Range dependency.
Global_Variable 'myData' used at line 393 is defined at line 355 and has a Long-Range dependency.
Variable 'i' used at line 393 is defined at line 389 and has a Short-Range dependency.
Function 'getKey' used at line 393 is defined at line 439 and has a Long-Range dependency.
Function 'getPointInInterior' used at line 393 is defined at line 122 and has a Long-Range dependency. | {'Loop Body': 5, 'If Condition': 1, 'If Body': 3} | {'Function Long-Range': 8, 'Global_Variable Long-Range': 3, 'Variable Short-Range': 5} |
infilling_java | MTreeTester | 405 | 406 | ['import junit.framework.TestCase;', 'import java.util.ArrayList;', 'import java.util.Random;', 'import java.util.Collections;', '', '// this is a map from a set of keys of type PointInMetricSpace to a', '// set of data of type DataType', 'interface IMTree <Key extends IPointInMetricSpace <Key>, Data> {', ' ', ' // insert a new key/data pair into the map', ' void insert (Key keyToAdd, Data dataToAdd);', ' ', ' // find all of the key/data pairs in the map that fall within a', ' // particular distance of query point if no results are found, then', ' // an empty array is returned (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> find (Key query, double distance);', ' ', ' // find the k closest key/data pairs in the map to a particular', ' // query point ', ' //', ' // if the number of points in the map is less than k, then the', ' // returned list will have less than k pairs in it', ' //', ' // if the number of points is zero, then an empty array is returned', ' // (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> findKClosest (Key query, int k);', ' ', ' // returns the number of nodes that exist on a path from root to leaf in the tree...', ' // whtever the details of the implementation are, a tree with a single leaf node should return 1, and a tree', ' // with more than one lead node should return at least two (since it must have at least one internal node).', ' public int depth ();', ' ', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', '', 'interface IDoubleVector {', '', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '', '// this correponds to some geometric object in a metric space; the object is built out of', '// one or more points of type PointInMetricSpace', 'interface IObjectInMetricSpaceABCD <PointInMetricSpace extends IPointInMetricSpace<PointInMetricSpace>> {', ' ', ' // get the maximum distance from some point on the shape to a particular point in the metric space', ' double maxDistanceTo (PointInMetricSpace checkMe);', ' ', ' // return some arbitrary point on the interior of the geometric object', ' PointInMetricSpace getPointInInterior ();', '}', '', '', '// this interface corresponds to a point in some metric space', 'interface IPointInMetricSpace <PointInMetricSpace> {', ' ', ' // get the distance to another point', ' // ', ' // for this to work in an M-Tree, distances should be "metric" and', ' // obey the triangle inequality', ' double getDistance (PointInMetricSpace toMe);', '}', '', '// this is the basic node type in the structure', 'interface IMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> {', ' ', ' // insert a new key/data pair into the structure. The return value is a new MTreeNode if there was', ' // a split in response to the insertion, or a null if there was no split', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd);', ' ', ' // find all of the key/data pairs in the structure that fall within a particular query sphere', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query); ', ' ', ' // find the set of items closest to the given query point', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ);', ' ', ' // returns a sphere that totally encompasses everything in the node and its subtree', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', ' ', ' // returns the depth', ' public int depth ();', '}', '', '// this is a point in a particular metric space', 'class PointABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the point', ' private PointInMetricSpace me;', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return me; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return checkMe.getDistance (me); ', ' }', ' ', ' // contruct a point', ' public PointABCD (PointInMetricSpace useMe) {', ' me = useMe; ', ' }', '}', '', 'class PQueueABCD <PointInMetricSpace, DataType> {', ' ', ' // this is an object in the queue', ' private class Wrapper {', ' DataWrapper <PointInMetricSpace, DataType> myData;', ' double distance;', ' }', ' ', ' // this is the actual queue', ' ArrayList <Wrapper> myList;', ' ', ' // this is the largest distance value currently in the queue', ' double large;', ' ', ' // this is the max number of objects', ' int maxCount;', ' ', ' // create a priority queue with the speced number of slots', ' PQueueABCD (int maxCountIn) {', ' maxCount = maxCountIn;', ' myList = new ArrayList <Wrapper> ();', ' large = 9e99;', ' }', ' ', ' // get the largest distance in the queue', ' double getDist () {', ' return large;', ' }', ' ', ' // add a new object to the queue... the insertion is ignored if the distance value', ' // exceeds the largest that is in the queue and the queue is already full', ' void insert (PointInMetricSpace key, DataType data, double distance) {', ' ', ' // if we are full, remove the one with the largest distance', ' if (myList.size () == maxCount && distance < large) {', ' ', ' int badIndex = 0;', ' double maxDist = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > maxDist) {', ' maxDist = myList.get (i).distance;', ' badIndex = i;', ' }', ' }', ' ', ' myList.remove (badIndex);', ' }', ' ', ' // see if there is room', ' if (myList.size () < maxCount) {', ' ', ' // add it ', ' Wrapper newOne = new Wrapper ();', ' newOne.myData = new DataWrapper <PointInMetricSpace, DataType> (key, data);', ' newOne.distance = distance;', ' myList.add (newOne); ', ' }', ' ', ' // if we are full, reset the max distance', ' if (myList.size () == maxCount) {', ' large = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > large) {', ' large = myList.get (i).distance;', ' }', ' }', ' }', ' ', ' }', ' ', ' // extracts the contents of the queue', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> done () {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' for (int i = 0; i < myList.size (); i++) {', ' returnVal.add (myList.get (i).myData); ', ' }', ' ', ' return returnVal;', ' }', ' ', '}', '', '// this is a sphere in a particular metric space', 'class SphereABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the center of the sphere and its radius', ' private PointInMetricSpace center;', ' private double radius;', ' ', ' // build a sphere out of its center and its radius', ' public SphereABCD (PointInMetricSpace centerIn, double radiusIn) {', ' center = centerIn;', ' radius = radiusIn;', ' }', ' ', ' // increase the size of the sphere so it contains the object swallowMe', ' public void swallow (IObjectInMetricSpaceABCD <PointInMetricSpace> swallowMe) {', ' ', ' // see if we need to increase the radius to swallow this guy', ' double dist = swallowMe.maxDistanceTo (center);', ' if (dist > radius)', ' radius = dist;', ' }', ' ', ' // check to see if a sphere intersects another sphere', ' public boolean intersects (SphereABCD <PointInMetricSpace> me) {', ' return (me.center.getDistance (center) <= me.radius + radius);', ' }', ' ', ' // check to see if the sphere contains a point', ' public boolean contains (PointInMetricSpace checkMe) {', ' return (checkMe.getDistance (center) <= radius);', ' }', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return center; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return radius + checkMe.getDistance (center); ', ' }', '}', '', '', '', 'class OneDimPoint implements IPointInMetricSpace <OneDimPoint> {', ' ', ' // this is the actual double', ' Double value;', ' ', ' // construct this out of a double value', ' public OneDimPoint (double makeFromMe) {', ' value = new Double (makeFromMe);', ' }', ' ', ' // get the distance to another point', ' public double getDistance (OneDimPoint toMe) {', ' if (value > toMe.value)', ' return value - toMe.value;', ' else', ' return toMe.value - value;', ' }', ' ', '}', '', 'class MultiDimPoint implements IPointInMetricSpace <MultiDimPoint> {', ' ', ' // this is the point in a multidimensional space', ' IDoubleVector me;', ' ', ' // make this out of an IDoubleVector', ' public MultiDimPoint (IDoubleVector useMe) {', ' me = useMe;', ' }', ' ', ' // get the Euclidean distance to another point', ' public double getDistance (MultiDimPoint toMe) {', ' double distance = 0.0;', ' try {', ' for (int i = 0; i < me.getLength (); i++) {', ' double diff = me.getItem (i) - toMe.me.getItem (i);', ' diff *= diff;', ' distance += diff;', ' }', ' } catch (OutOfBoundsException e) {', ' throw new IndexOutOfBoundsException ("Can\'t compare two MultiDimPoint objects with different dimensionality!"); ', ' }', ' return Math.sqrt(distance);', ' }', ' ', '}', '// this is a leaf node', 'class LeafMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements ', ' IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myData;', ' ', ' // contructor that takes a data list and builds a node out of it', ' private LeafMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myDataIn) {', ' myData = myDataIn; ', ' }', ' ', ' // constructor that creates an empty node', ' public LeafMTreeNodeABCD () {', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> (); ', ' }', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // just add in the new data', ' myData.add (new PointABCD <PointInMetricSpace> (keyToAdd), dataToAdd);', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> newOne = myData.splitInTwo ();', ' LeafMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' myQ.insert (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData (), ', ' query.getDistance (myData.get (i).getKey ().getPointInInterior ()));', ' }', ' }', ' }', ' ', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.contains (myData.get (i).getKey ().getPointInInterior ())) {'] | [' returnVal.add (new DataWrapper <PointInMetricSpace, DataType> (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData ()));', ' }'] | [' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return 1; ', ' }', '', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', '// this silly little class is just a wrapper for a key, data pair', 'class DataWrapper <Key, Data> {', ' ', ' Key key;', ' Data data;', ' ', ' public DataWrapper (Key keyIn, Data dataIn) {', ' key = keyIn;', ' data = dataIn;', ' }', ' ', ' public Key getKey () {', ' return key;', ' }', ' ', ' public Data getData () {', ' return data;', ' }', '}', '', '', '// this is an internal node', 'class InternalMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType>', ' implements IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> myData;', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' // this constructs a new internal node that holds precisely the two nodes that are passed in', ' public InternalMTreeNodeABCD (IMTreeNodeABCD <PointInMetricSpace, DataType> refOne,', ' IMTreeNodeABCD <PointInMetricSpace, DataType> refTwo) {', ' ', ' // create a necw list and add the two guys in', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> ();', ' myData.add (refOne.getBoundingSphere (), refOne);', ' myData.add (refTwo.getBoundingSphere (), refTwo);', ' }', ' ', ' // this constructs a new node that holds the list of data that we were passed in', ' public InternalMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> useMe) {', ' myData = useMe; ', ' }', ' ', ' // from the interface', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // find the best child; this is the one we are closest to', ' double bestDist = 9e99;', ' int bestIndex = 0;', ' for (int i = 0; i < myData.size (); i++) {', ' ', ' double newDist = myData.get (i).getKey ().getPointInInterior ().getDistance (keyToAdd);', ' if (newDist < bestDist) {', ' bestDist = newDist;', ' bestIndex = i;', ' }', ' }', ' ', ' // do the recursive insert', ' IMTreeNodeABCD <PointInMetricSpace, DataType> newRef = myData.get (bestIndex).getData ().insert (keyToAdd, dataToAdd);', ' ', ' // if we got something back, then there was a split, so add the new node into our list', ' if (newRef != null) {', ' myData.add (newRef.getBoundingSphere (), newRef);', ' }', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> newOne = myData.splitInTwo ();', ' InternalMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.intersects (myData.get (i).getKey ())) {', ' myData.get (i).getData ().findKClosest (query, myQ);', ' }', ' }', ' }', ' ', ' // from the interface', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.intersects (myData.get (i).getKey ())) {', ' returnVal.addAll (myData.get (i).getData ().find (query));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return myData.get (0).getData ().depth () + 1; ', ' }', ' ', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', 'abstract class AMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> implements IMetricDataListABCD <PointInMetricSpace,KeyType, DataType> {', '', ' // this is the data that is actually stored in the list', ' private ArrayList <DataWrapper <KeyType, DataType>> myData;', ' ', ' // this is the sphere that bounds everything in the list', ' private SphereABCD <PointInMetricSpace> myBoundingSphere;', ' ', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myBoundingSphere; ', ' }', ' ', ' public int size () {', ' if (myData != null)', ' return myData.size (); ', ' else', ' return 0;', ' }', ' ', ' public DataWrapper <KeyType, DataType> get (int pos) {', ' return myData.get (pos);', ' }', ' ', ' public void replaceKey (int pos, KeyType keyToAdd) {', ' DataWrapper <KeyType, DataType> temp = myData.remove (pos);', ' DataWrapper <KeyType, DataType> newOne = new DataWrapper <KeyType, DataType> (keyToAdd, temp.getData ());', ' myData.add (pos, newOne);', ' }', ' ', ' public void add (KeyType keyToAdd, DataType dataToAdd) {', ' ', ' // if this is the first add, then set everyone up', ' if (myData == null) {', ' PointInMetricSpace myCentroid = keyToAdd.getPointInInterior ();', ' myBoundingSphere = new SphereABCD <PointInMetricSpace> (myCentroid, keyToAdd.maxDistanceTo (myCentroid));', ' myData = new ArrayList <DataWrapper <KeyType, DataType>> ();', ' ', ' // otherwise, extend the sphere if needed', ' } else {', ' myBoundingSphere.swallow (keyToAdd);', ' }', ' ', ' // add the data', ' myData.add (new DataWrapper <KeyType, DataType> (keyToAdd, dataToAdd));', ' }', ' ', ' // we want to potentially allow many implementations of the splitting lalgorithm', ' abstract public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // this is here so the actual splitting algorithn can access the list and change the sphere', ' protected ArrayList <DataWrapper <KeyType, DataType>> getList () {', ' return myData;', ' }', ' ', ' // this is here so the splitting algorithm can modify the list and the sphere', ' protected void replaceGuts (AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> withMe) {', ' myData = withMe.myData;', ' myBoundingSphere = withMe.myBoundingSphere;', ' }', ' ', '}', '', '// this is a particular implementation of the metric data list that uses a simple quadratic clustering', '// algorithm to perform a list split. It picks two "seeds" (the most distant objects) and then repeatedly', '// adds to the two new lists by choosing the objects closest to the seeds', 'class ChrisMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> extends AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> {', '', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo () {', ' ', ' // first, we need to find the two most distant points in the list', ' ArrayList <DataWrapper <KeyType, DataType>> myData = getList ();', ' int bestI = 0, bestJ = 0;', ' double maxDist = -1.0;', ' for (int i = 0; i < myData.size (); i++) {', ' for (int j = i + 1; j < myData.size (); j++) {', ' ', ' // get the two keys', ' DataWrapper <KeyType, DataType> pointOne = myData.get (i);', ' DataWrapper <KeyType, DataType> pointTwo = myData.get (j);', ' ', ' // find the difference between them', ' double curDist = pointOne.getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', '', ' // see if it is the biggest', ' if (curDist > maxDist) {', ' maxDist = curDist;', ' bestI = i;', ' bestJ = j;', ' }', ' }', ' }', ' ', ' // now, we have the best two points; those are seeds for the clustering', ' DataWrapper <KeyType, DataType> pointOne = myData.remove (bestI);', ' DataWrapper <KeyType, DataType> pointTwo = myData.remove (bestJ - 1);', ' ', ' // these are the two new lists', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listOne = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listTwo = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' ', ' // put the two seeds in', ' listOne.add (pointOne.getKey (), pointOne.getData ());', ' listTwo.add (pointTwo.getKey (), pointTwo.getData ());', ' ', ' // and add everyone else in', ' while (myData.size () != 0) {', ' ', ' // find the one closest to the first seed', ' int bestIndex = 0;', ' double bestDist = 9e99;', ' ', ' // loop thru all of the candidate data objects', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listOne.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' ', ' // break if no more data', ' if (myData.size () == 0)', ' break;', ' ', ' // loop thru all of the candidate data objects', ' bestDist = 9e99;', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listTwo.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' }', ' ', ' // now we replace our own guts with the first list', ' replaceGuts (listOne);', ' ', ' // and return the other list', ' return listTwo;', ' }', '}', '', 'interface IMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> {', ' ', ' // add a new pair to the list', ' public void add (KeyType keyToAdd, DataType dataToAdd);', ' ', ' // replace a key at the indicated position', ' public void replaceKey (int pos, KeyType keyToAdd);', ' ', ' // get the key, data pair that resides at a particular position', ' public DataWrapper <KeyType, DataType> get (int pos);', ' ', ' // return the number of items in the list', ' public int size ();', ' ', ' // split the list in two, using some clutering algorithm', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // get a sphere that totally bounds all of the objects in the list', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class MTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public MTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class SCMTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public SCMTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', '', 'public class MTreeTester extends TestCase {', ' ', ' // compare two lists of strings to see if the contents are the same', ' private boolean compareStringSets (ArrayList <String> setOne, ArrayList <String> setTwo) {', ' ', ' // sort the sets and make sure they are the same', ' boolean returnVal = true;', ' if (setOne.size () == setTwo.size ()) {', ' Collections.sort (setOne);', ' Collections.sort (setTwo);', ' for (int i = 0; i < setOne.size (); i++) {', ' if (!setOne.get (i).equals (setTwo.get (i))) {', ' returnVal = false;', ' break; ', ' }', ' }', ' } else {', ' returnVal = false;', ' }', ' ', ' // print out the result', ' System.out.println ("**** Expected:");', ' for (int i = 0; i < setOne.size (); i++) {', ' System.out.format (setOne.get (i) + " ");', ' }', ' System.out.println ("\\n**** Got:");', ' for (int i = 0; i < setTwo.size (); i++) {', ' System.out.format (setTwo.get (i) + " ");', ' }', ' System.out.println ("");', ' ', ' return returnVal;', ' }', ' ', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST SIMPLE ONE DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testOneDimRangeQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.find (query, expectedQuerySize / 2);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.find (query, expectedQuerySize / 2);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (numPoints);', ' result1 = myTree.find (query, expectedQuerySize);', ' result2 = hisTree.find (query, expectedQuerySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // like the last one, but runs a top k', ' private void testOneDimTopKQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (167);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.findKClosest (query, querySize);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (0);', ' result1 = myTree.findKClosest (query, querySize);', ' result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST MULTI-DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimRangeQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' double dist1 = 0;', ' double dist2 = 0;', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' dist1 = Math.sqrt (numDims) * expectedQuerySize / 2.0;', ' dist2 = Math.sqrt (numDims) * expectedQuerySize;', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' // do a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, (int) expectedQuerySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = myTree.findKClosest (query2, (int) expectedQuerySize);', ' ', ' // find the distance to the furthest point in both cases', ' for (int i = 0; i < (int) expectedQuerySize; i++) {', ' double newDist = result1.get (i).getKey ().getDistance (query1);', ' if (newDist > dist1)', ' dist1 = newDist;', ' newDist = result2.get (i).getKey ().getDistance (query2);', ' if (newDist > dist2)', ' dist2 = newDist;', ' }', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.find (query1, dist1);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.find (query1, dist1);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.find (query2, dist2);', ' result2 = hisTree.find (query2, dist2);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimTopKQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, querySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.findKClosest (query1, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.findKClosest (query2, querySize);', ' result2 = hisTree.findKClosest (query2, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' ', ' /**', ' * "TIER 1" TESTS', ' * NONE OF THESE REQUIRE ANY SPLITS', ' */', ' public void testEasy1() {', ' testOneDimRangeQuery (true, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy2() {', ' testOneDimRangeQuery (false, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy3() {', ' testOneDimRangeQuery (true, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy4() {', ' testOneDimRangeQuery (false, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy5() {', ' testMultiDimRangeQuery (true, 1, 5, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy6() {', ' testMultiDimRangeQuery (false, 1, 10, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy7() {', ' testMultiDimRangeQuery (true, 1, 5, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy8() {', ' testMultiDimRangeQuery (false, 1, 15, 10000, 10000, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 2" TESTS', ' * NONE OF THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testMod1() {', ' testOneDimRangeQuery (true, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod2() {', ' testOneDimRangeQuery (false, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod3() {', ' testOneDimRangeQuery (true, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod4() {', ' testOneDimRangeQuery (false, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod5() {', ' testMultiDimRangeQuery (true, 2, 5, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod6() {', ' testMultiDimRangeQuery (false, 2, 10, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod7() {', ' testMultiDimRangeQuery (true, 2, 5, 10000, 100, 1000, 10);', ' }', ' ', ' public void testMod8() {', ' testMultiDimRangeQuery (false, 2, 15, 10000, 100, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 3" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testHard1() {', ' testOneDimRangeQuery (true, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard2() {', ' testOneDimRangeQuery (false, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard3() {', ' testOneDimRangeQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard4() {', ' testOneDimRangeQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard5() {', ' testMultiDimRangeQuery (true, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard6() {', ' testMultiDimRangeQuery (false, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard7() {', ' testMultiDimRangeQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard8() {', ' testMultiDimRangeQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', ' ', ' /**', ' * "TIER 4" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE AND THEY TEST THE TOPK FUNCTIONALITY', ' */', ' ', ' public void testTopK1() {', ' testOneDimTopKQuery (true, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK2() {', ' testOneDimTopKQuery (false, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK3() {', ' testOneDimTopKQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK4() {', ' testOneDimTopKQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK5() {', ' testMultiDimTopKQuery (true, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK6() {', ' testMultiDimTopKQuery (false, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK7() {', ' testMultiDimTopKQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK8() {', ' testMultiDimTopKQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', '}'] | [{'reason_category': 'Loop Body', 'usage_line': 405}, {'reason_category': 'If Body', 'usage_line': 405}, {'reason_category': 'Loop Body', 'usage_line': 406}, {'reason_category': 'If Body', 'usage_line': 406}] | Variable 'returnVal' used at line 405 is defined at line 400 and has a Short-Range dependency.
Class 'DataWrapper' used at line 405 is defined at line 429 and has a Medium-Range dependency.
Global_Variable 'myData' used at line 405 is defined at line 355 and has a Long-Range dependency.
Variable 'i' used at line 405 is defined at line 403 and has a Short-Range dependency.
Function 'getKey' used at line 405 is defined at line 439 and has a Long-Range dependency.
Function 'getPointInInterior' used at line 405 is defined at line 122 and has a Long-Range dependency.
Function 'getData' used at line 405 is defined at line 443 and has a Long-Range dependency. | {'Loop Body': 2, 'If Body': 2} | {'Variable Short-Range': 2, 'Class Medium-Range': 1, 'Global_Variable Long-Range': 1, 'Function Long-Range': 3} |
infilling_java | MTreeTester | 404 | 407 | ['import junit.framework.TestCase;', 'import java.util.ArrayList;', 'import java.util.Random;', 'import java.util.Collections;', '', '// this is a map from a set of keys of type PointInMetricSpace to a', '// set of data of type DataType', 'interface IMTree <Key extends IPointInMetricSpace <Key>, Data> {', ' ', ' // insert a new key/data pair into the map', ' void insert (Key keyToAdd, Data dataToAdd);', ' ', ' // find all of the key/data pairs in the map that fall within a', ' // particular distance of query point if no results are found, then', ' // an empty array is returned (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> find (Key query, double distance);', ' ', ' // find the k closest key/data pairs in the map to a particular', ' // query point ', ' //', ' // if the number of points in the map is less than k, then the', ' // returned list will have less than k pairs in it', ' //', ' // if the number of points is zero, then an empty array is returned', ' // (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> findKClosest (Key query, int k);', ' ', ' // returns the number of nodes that exist on a path from root to leaf in the tree...', ' // whtever the details of the implementation are, a tree with a single leaf node should return 1, and a tree', ' // with more than one lead node should return at least two (since it must have at least one internal node).', ' public int depth ();', ' ', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', '', 'interface IDoubleVector {', '', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '', '// this correponds to some geometric object in a metric space; the object is built out of', '// one or more points of type PointInMetricSpace', 'interface IObjectInMetricSpaceABCD <PointInMetricSpace extends IPointInMetricSpace<PointInMetricSpace>> {', ' ', ' // get the maximum distance from some point on the shape to a particular point in the metric space', ' double maxDistanceTo (PointInMetricSpace checkMe);', ' ', ' // return some arbitrary point on the interior of the geometric object', ' PointInMetricSpace getPointInInterior ();', '}', '', '', '// this interface corresponds to a point in some metric space', 'interface IPointInMetricSpace <PointInMetricSpace> {', ' ', ' // get the distance to another point', ' // ', ' // for this to work in an M-Tree, distances should be "metric" and', ' // obey the triangle inequality', ' double getDistance (PointInMetricSpace toMe);', '}', '', '// this is the basic node type in the structure', 'interface IMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> {', ' ', ' // insert a new key/data pair into the structure. The return value is a new MTreeNode if there was', ' // a split in response to the insertion, or a null if there was no split', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd);', ' ', ' // find all of the key/data pairs in the structure that fall within a particular query sphere', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query); ', ' ', ' // find the set of items closest to the given query point', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ);', ' ', ' // returns a sphere that totally encompasses everything in the node and its subtree', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', ' ', ' // returns the depth', ' public int depth ();', '}', '', '// this is a point in a particular metric space', 'class PointABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the point', ' private PointInMetricSpace me;', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return me; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return checkMe.getDistance (me); ', ' }', ' ', ' // contruct a point', ' public PointABCD (PointInMetricSpace useMe) {', ' me = useMe; ', ' }', '}', '', 'class PQueueABCD <PointInMetricSpace, DataType> {', ' ', ' // this is an object in the queue', ' private class Wrapper {', ' DataWrapper <PointInMetricSpace, DataType> myData;', ' double distance;', ' }', ' ', ' // this is the actual queue', ' ArrayList <Wrapper> myList;', ' ', ' // this is the largest distance value currently in the queue', ' double large;', ' ', ' // this is the max number of objects', ' int maxCount;', ' ', ' // create a priority queue with the speced number of slots', ' PQueueABCD (int maxCountIn) {', ' maxCount = maxCountIn;', ' myList = new ArrayList <Wrapper> ();', ' large = 9e99;', ' }', ' ', ' // get the largest distance in the queue', ' double getDist () {', ' return large;', ' }', ' ', ' // add a new object to the queue... the insertion is ignored if the distance value', ' // exceeds the largest that is in the queue and the queue is already full', ' void insert (PointInMetricSpace key, DataType data, double distance) {', ' ', ' // if we are full, remove the one with the largest distance', ' if (myList.size () == maxCount && distance < large) {', ' ', ' int badIndex = 0;', ' double maxDist = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > maxDist) {', ' maxDist = myList.get (i).distance;', ' badIndex = i;', ' }', ' }', ' ', ' myList.remove (badIndex);', ' }', ' ', ' // see if there is room', ' if (myList.size () < maxCount) {', ' ', ' // add it ', ' Wrapper newOne = new Wrapper ();', ' newOne.myData = new DataWrapper <PointInMetricSpace, DataType> (key, data);', ' newOne.distance = distance;', ' myList.add (newOne); ', ' }', ' ', ' // if we are full, reset the max distance', ' if (myList.size () == maxCount) {', ' large = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > large) {', ' large = myList.get (i).distance;', ' }', ' }', ' }', ' ', ' }', ' ', ' // extracts the contents of the queue', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> done () {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' for (int i = 0; i < myList.size (); i++) {', ' returnVal.add (myList.get (i).myData); ', ' }', ' ', ' return returnVal;', ' }', ' ', '}', '', '// this is a sphere in a particular metric space', 'class SphereABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the center of the sphere and its radius', ' private PointInMetricSpace center;', ' private double radius;', ' ', ' // build a sphere out of its center and its radius', ' public SphereABCD (PointInMetricSpace centerIn, double radiusIn) {', ' center = centerIn;', ' radius = radiusIn;', ' }', ' ', ' // increase the size of the sphere so it contains the object swallowMe', ' public void swallow (IObjectInMetricSpaceABCD <PointInMetricSpace> swallowMe) {', ' ', ' // see if we need to increase the radius to swallow this guy', ' double dist = swallowMe.maxDistanceTo (center);', ' if (dist > radius)', ' radius = dist;', ' }', ' ', ' // check to see if a sphere intersects another sphere', ' public boolean intersects (SphereABCD <PointInMetricSpace> me) {', ' return (me.center.getDistance (center) <= me.radius + radius);', ' }', ' ', ' // check to see if the sphere contains a point', ' public boolean contains (PointInMetricSpace checkMe) {', ' return (checkMe.getDistance (center) <= radius);', ' }', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return center; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return radius + checkMe.getDistance (center); ', ' }', '}', '', '', '', 'class OneDimPoint implements IPointInMetricSpace <OneDimPoint> {', ' ', ' // this is the actual double', ' Double value;', ' ', ' // construct this out of a double value', ' public OneDimPoint (double makeFromMe) {', ' value = new Double (makeFromMe);', ' }', ' ', ' // get the distance to another point', ' public double getDistance (OneDimPoint toMe) {', ' if (value > toMe.value)', ' return value - toMe.value;', ' else', ' return toMe.value - value;', ' }', ' ', '}', '', 'class MultiDimPoint implements IPointInMetricSpace <MultiDimPoint> {', ' ', ' // this is the point in a multidimensional space', ' IDoubleVector me;', ' ', ' // make this out of an IDoubleVector', ' public MultiDimPoint (IDoubleVector useMe) {', ' me = useMe;', ' }', ' ', ' // get the Euclidean distance to another point', ' public double getDistance (MultiDimPoint toMe) {', ' double distance = 0.0;', ' try {', ' for (int i = 0; i < me.getLength (); i++) {', ' double diff = me.getItem (i) - toMe.me.getItem (i);', ' diff *= diff;', ' distance += diff;', ' }', ' } catch (OutOfBoundsException e) {', ' throw new IndexOutOfBoundsException ("Can\'t compare two MultiDimPoint objects with different dimensionality!"); ', ' }', ' return Math.sqrt(distance);', ' }', ' ', '}', '// this is a leaf node', 'class LeafMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements ', ' IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myData;', ' ', ' // contructor that takes a data list and builds a node out of it', ' private LeafMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myDataIn) {', ' myData = myDataIn; ', ' }', ' ', ' // constructor that creates an empty node', ' public LeafMTreeNodeABCD () {', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> (); ', ' }', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // just add in the new data', ' myData.add (new PointABCD <PointInMetricSpace> (keyToAdd), dataToAdd);', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> newOne = myData.splitInTwo ();', ' LeafMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' myQ.insert (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData (), ', ' query.getDistance (myData.get (i).getKey ().getPointInInterior ()));', ' }', ' }', ' }', ' ', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {'] | [' if (query.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' returnVal.add (new DataWrapper <PointInMetricSpace, DataType> (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData ()));', ' }', ' }'] | [' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return 1; ', ' }', '', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', '// this silly little class is just a wrapper for a key, data pair', 'class DataWrapper <Key, Data> {', ' ', ' Key key;', ' Data data;', ' ', ' public DataWrapper (Key keyIn, Data dataIn) {', ' key = keyIn;', ' data = dataIn;', ' }', ' ', ' public Key getKey () {', ' return key;', ' }', ' ', ' public Data getData () {', ' return data;', ' }', '}', '', '', '// this is an internal node', 'class InternalMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType>', ' implements IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> myData;', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' // this constructs a new internal node that holds precisely the two nodes that are passed in', ' public InternalMTreeNodeABCD (IMTreeNodeABCD <PointInMetricSpace, DataType> refOne,', ' IMTreeNodeABCD <PointInMetricSpace, DataType> refTwo) {', ' ', ' // create a necw list and add the two guys in', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> ();', ' myData.add (refOne.getBoundingSphere (), refOne);', ' myData.add (refTwo.getBoundingSphere (), refTwo);', ' }', ' ', ' // this constructs a new node that holds the list of data that we were passed in', ' public InternalMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> useMe) {', ' myData = useMe; ', ' }', ' ', ' // from the interface', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // find the best child; this is the one we are closest to', ' double bestDist = 9e99;', ' int bestIndex = 0;', ' for (int i = 0; i < myData.size (); i++) {', ' ', ' double newDist = myData.get (i).getKey ().getPointInInterior ().getDistance (keyToAdd);', ' if (newDist < bestDist) {', ' bestDist = newDist;', ' bestIndex = i;', ' }', ' }', ' ', ' // do the recursive insert', ' IMTreeNodeABCD <PointInMetricSpace, DataType> newRef = myData.get (bestIndex).getData ().insert (keyToAdd, dataToAdd);', ' ', ' // if we got something back, then there was a split, so add the new node into our list', ' if (newRef != null) {', ' myData.add (newRef.getBoundingSphere (), newRef);', ' }', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> newOne = myData.splitInTwo ();', ' InternalMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.intersects (myData.get (i).getKey ())) {', ' myData.get (i).getData ().findKClosest (query, myQ);', ' }', ' }', ' }', ' ', ' // from the interface', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.intersects (myData.get (i).getKey ())) {', ' returnVal.addAll (myData.get (i).getData ().find (query));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return myData.get (0).getData ().depth () + 1; ', ' }', ' ', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', 'abstract class AMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> implements IMetricDataListABCD <PointInMetricSpace,KeyType, DataType> {', '', ' // this is the data that is actually stored in the list', ' private ArrayList <DataWrapper <KeyType, DataType>> myData;', ' ', ' // this is the sphere that bounds everything in the list', ' private SphereABCD <PointInMetricSpace> myBoundingSphere;', ' ', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myBoundingSphere; ', ' }', ' ', ' public int size () {', ' if (myData != null)', ' return myData.size (); ', ' else', ' return 0;', ' }', ' ', ' public DataWrapper <KeyType, DataType> get (int pos) {', ' return myData.get (pos);', ' }', ' ', ' public void replaceKey (int pos, KeyType keyToAdd) {', ' DataWrapper <KeyType, DataType> temp = myData.remove (pos);', ' DataWrapper <KeyType, DataType> newOne = new DataWrapper <KeyType, DataType> (keyToAdd, temp.getData ());', ' myData.add (pos, newOne);', ' }', ' ', ' public void add (KeyType keyToAdd, DataType dataToAdd) {', ' ', ' // if this is the first add, then set everyone up', ' if (myData == null) {', ' PointInMetricSpace myCentroid = keyToAdd.getPointInInterior ();', ' myBoundingSphere = new SphereABCD <PointInMetricSpace> (myCentroid, keyToAdd.maxDistanceTo (myCentroid));', ' myData = new ArrayList <DataWrapper <KeyType, DataType>> ();', ' ', ' // otherwise, extend the sphere if needed', ' } else {', ' myBoundingSphere.swallow (keyToAdd);', ' }', ' ', ' // add the data', ' myData.add (new DataWrapper <KeyType, DataType> (keyToAdd, dataToAdd));', ' }', ' ', ' // we want to potentially allow many implementations of the splitting lalgorithm', ' abstract public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // this is here so the actual splitting algorithn can access the list and change the sphere', ' protected ArrayList <DataWrapper <KeyType, DataType>> getList () {', ' return myData;', ' }', ' ', ' // this is here so the splitting algorithm can modify the list and the sphere', ' protected void replaceGuts (AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> withMe) {', ' myData = withMe.myData;', ' myBoundingSphere = withMe.myBoundingSphere;', ' }', ' ', '}', '', '// this is a particular implementation of the metric data list that uses a simple quadratic clustering', '// algorithm to perform a list split. It picks two "seeds" (the most distant objects) and then repeatedly', '// adds to the two new lists by choosing the objects closest to the seeds', 'class ChrisMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> extends AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> {', '', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo () {', ' ', ' // first, we need to find the two most distant points in the list', ' ArrayList <DataWrapper <KeyType, DataType>> myData = getList ();', ' int bestI = 0, bestJ = 0;', ' double maxDist = -1.0;', ' for (int i = 0; i < myData.size (); i++) {', ' for (int j = i + 1; j < myData.size (); j++) {', ' ', ' // get the two keys', ' DataWrapper <KeyType, DataType> pointOne = myData.get (i);', ' DataWrapper <KeyType, DataType> pointTwo = myData.get (j);', ' ', ' // find the difference between them', ' double curDist = pointOne.getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', '', ' // see if it is the biggest', ' if (curDist > maxDist) {', ' maxDist = curDist;', ' bestI = i;', ' bestJ = j;', ' }', ' }', ' }', ' ', ' // now, we have the best two points; those are seeds for the clustering', ' DataWrapper <KeyType, DataType> pointOne = myData.remove (bestI);', ' DataWrapper <KeyType, DataType> pointTwo = myData.remove (bestJ - 1);', ' ', ' // these are the two new lists', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listOne = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listTwo = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' ', ' // put the two seeds in', ' listOne.add (pointOne.getKey (), pointOne.getData ());', ' listTwo.add (pointTwo.getKey (), pointTwo.getData ());', ' ', ' // and add everyone else in', ' while (myData.size () != 0) {', ' ', ' // find the one closest to the first seed', ' int bestIndex = 0;', ' double bestDist = 9e99;', ' ', ' // loop thru all of the candidate data objects', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listOne.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' ', ' // break if no more data', ' if (myData.size () == 0)', ' break;', ' ', ' // loop thru all of the candidate data objects', ' bestDist = 9e99;', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listTwo.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' }', ' ', ' // now we replace our own guts with the first list', ' replaceGuts (listOne);', ' ', ' // and return the other list', ' return listTwo;', ' }', '}', '', 'interface IMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> {', ' ', ' // add a new pair to the list', ' public void add (KeyType keyToAdd, DataType dataToAdd);', ' ', ' // replace a key at the indicated position', ' public void replaceKey (int pos, KeyType keyToAdd);', ' ', ' // get the key, data pair that resides at a particular position', ' public DataWrapper <KeyType, DataType> get (int pos);', ' ', ' // return the number of items in the list', ' public int size ();', ' ', ' // split the list in two, using some clutering algorithm', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // get a sphere that totally bounds all of the objects in the list', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class MTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public MTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class SCMTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public SCMTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', '', 'public class MTreeTester extends TestCase {', ' ', ' // compare two lists of strings to see if the contents are the same', ' private boolean compareStringSets (ArrayList <String> setOne, ArrayList <String> setTwo) {', ' ', ' // sort the sets and make sure they are the same', ' boolean returnVal = true;', ' if (setOne.size () == setTwo.size ()) {', ' Collections.sort (setOne);', ' Collections.sort (setTwo);', ' for (int i = 0; i < setOne.size (); i++) {', ' if (!setOne.get (i).equals (setTwo.get (i))) {', ' returnVal = false;', ' break; ', ' }', ' }', ' } else {', ' returnVal = false;', ' }', ' ', ' // print out the result', ' System.out.println ("**** Expected:");', ' for (int i = 0; i < setOne.size (); i++) {', ' System.out.format (setOne.get (i) + " ");', ' }', ' System.out.println ("\\n**** Got:");', ' for (int i = 0; i < setTwo.size (); i++) {', ' System.out.format (setTwo.get (i) + " ");', ' }', ' System.out.println ("");', ' ', ' return returnVal;', ' }', ' ', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST SIMPLE ONE DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testOneDimRangeQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.find (query, expectedQuerySize / 2);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.find (query, expectedQuerySize / 2);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (numPoints);', ' result1 = myTree.find (query, expectedQuerySize);', ' result2 = hisTree.find (query, expectedQuerySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // like the last one, but runs a top k', ' private void testOneDimTopKQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (167);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.findKClosest (query, querySize);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (0);', ' result1 = myTree.findKClosest (query, querySize);', ' result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST MULTI-DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimRangeQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' double dist1 = 0;', ' double dist2 = 0;', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' dist1 = Math.sqrt (numDims) * expectedQuerySize / 2.0;', ' dist2 = Math.sqrt (numDims) * expectedQuerySize;', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' // do a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, (int) expectedQuerySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = myTree.findKClosest (query2, (int) expectedQuerySize);', ' ', ' // find the distance to the furthest point in both cases', ' for (int i = 0; i < (int) expectedQuerySize; i++) {', ' double newDist = result1.get (i).getKey ().getDistance (query1);', ' if (newDist > dist1)', ' dist1 = newDist;', ' newDist = result2.get (i).getKey ().getDistance (query2);', ' if (newDist > dist2)', ' dist2 = newDist;', ' }', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.find (query1, dist1);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.find (query1, dist1);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.find (query2, dist2);', ' result2 = hisTree.find (query2, dist2);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimTopKQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, querySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.findKClosest (query1, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.findKClosest (query2, querySize);', ' result2 = hisTree.findKClosest (query2, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' ', ' /**', ' * "TIER 1" TESTS', ' * NONE OF THESE REQUIRE ANY SPLITS', ' */', ' public void testEasy1() {', ' testOneDimRangeQuery (true, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy2() {', ' testOneDimRangeQuery (false, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy3() {', ' testOneDimRangeQuery (true, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy4() {', ' testOneDimRangeQuery (false, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy5() {', ' testMultiDimRangeQuery (true, 1, 5, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy6() {', ' testMultiDimRangeQuery (false, 1, 10, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy7() {', ' testMultiDimRangeQuery (true, 1, 5, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy8() {', ' testMultiDimRangeQuery (false, 1, 15, 10000, 10000, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 2" TESTS', ' * NONE OF THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testMod1() {', ' testOneDimRangeQuery (true, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod2() {', ' testOneDimRangeQuery (false, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod3() {', ' testOneDimRangeQuery (true, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod4() {', ' testOneDimRangeQuery (false, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod5() {', ' testMultiDimRangeQuery (true, 2, 5, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod6() {', ' testMultiDimRangeQuery (false, 2, 10, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod7() {', ' testMultiDimRangeQuery (true, 2, 5, 10000, 100, 1000, 10);', ' }', ' ', ' public void testMod8() {', ' testMultiDimRangeQuery (false, 2, 15, 10000, 100, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 3" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testHard1() {', ' testOneDimRangeQuery (true, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard2() {', ' testOneDimRangeQuery (false, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard3() {', ' testOneDimRangeQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard4() {', ' testOneDimRangeQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard5() {', ' testMultiDimRangeQuery (true, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard6() {', ' testMultiDimRangeQuery (false, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard7() {', ' testMultiDimRangeQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard8() {', ' testMultiDimRangeQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', ' ', ' /**', ' * "TIER 4" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE AND THEY TEST THE TOPK FUNCTIONALITY', ' */', ' ', ' public void testTopK1() {', ' testOneDimTopKQuery (true, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK2() {', ' testOneDimTopKQuery (false, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK3() {', ' testOneDimTopKQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK4() {', ' testOneDimTopKQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK5() {', ' testMultiDimTopKQuery (true, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK6() {', ' testMultiDimTopKQuery (false, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK7() {', ' testMultiDimTopKQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK8() {', ' testMultiDimTopKQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', '}'] | [{'reason_category': 'Loop Body', 'usage_line': 404}, {'reason_category': 'If Condition', 'usage_line': 404}, {'reason_category': 'Loop Body', 'usage_line': 405}, {'reason_category': 'If Body', 'usage_line': 405}, {'reason_category': 'Loop Body', 'usage_line': 406}, {'reason_category': 'If Body', 'usage_line': 406}, {'reason_category': 'Loop Body', 'usage_line': 407}] | Variable 'query' used at line 404 is defined at line 398 and has a Short-Range dependency.
Global_Variable 'myData' used at line 404 is defined at line 355 and has a Long-Range dependency.
Variable 'i' used at line 404 is defined at line 403 and has a Short-Range dependency.
Function 'getKey' used at line 404 is defined at line 439 and has a Long-Range dependency.
Function 'getPointInInterior' used at line 404 is defined at line 122 and has a Long-Range dependency.
Variable 'returnVal' used at line 405 is defined at line 400 and has a Short-Range dependency.
Class 'DataWrapper' used at line 405 is defined at line 429 and has a Medium-Range dependency.
Global_Variable 'myData' used at line 405 is defined at line 355 and has a Long-Range dependency.
Variable 'i' used at line 405 is defined at line 403 and has a Short-Range dependency.
Function 'getKey' used at line 405 is defined at line 439 and has a Long-Range dependency.
Function 'getPointInInterior' used at line 405 is defined at line 122 and has a Long-Range dependency.
Function 'getData' used at line 405 is defined at line 443 and has a Long-Range dependency. | {'Loop Body': 4, 'If Condition': 1, 'If Body': 2} | {'Variable Short-Range': 4, 'Global_Variable Long-Range': 2, 'Function Long-Range': 5, 'Class Medium-Range': 1} |
infilling_java | MTreeTester | 435 | 437 | ['import junit.framework.TestCase;', 'import java.util.ArrayList;', 'import java.util.Random;', 'import java.util.Collections;', '', '// this is a map from a set of keys of type PointInMetricSpace to a', '// set of data of type DataType', 'interface IMTree <Key extends IPointInMetricSpace <Key>, Data> {', ' ', ' // insert a new key/data pair into the map', ' void insert (Key keyToAdd, Data dataToAdd);', ' ', ' // find all of the key/data pairs in the map that fall within a', ' // particular distance of query point if no results are found, then', ' // an empty array is returned (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> find (Key query, double distance);', ' ', ' // find the k closest key/data pairs in the map to a particular', ' // query point ', ' //', ' // if the number of points in the map is less than k, then the', ' // returned list will have less than k pairs in it', ' //', ' // if the number of points is zero, then an empty array is returned', ' // (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> findKClosest (Key query, int k);', ' ', ' // returns the number of nodes that exist on a path from root to leaf in the tree...', ' // whtever the details of the implementation are, a tree with a single leaf node should return 1, and a tree', ' // with more than one lead node should return at least two (since it must have at least one internal node).', ' public int depth ();', ' ', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', '', 'interface IDoubleVector {', '', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '', '// this correponds to some geometric object in a metric space; the object is built out of', '// one or more points of type PointInMetricSpace', 'interface IObjectInMetricSpaceABCD <PointInMetricSpace extends IPointInMetricSpace<PointInMetricSpace>> {', ' ', ' // get the maximum distance from some point on the shape to a particular point in the metric space', ' double maxDistanceTo (PointInMetricSpace checkMe);', ' ', ' // return some arbitrary point on the interior of the geometric object', ' PointInMetricSpace getPointInInterior ();', '}', '', '', '// this interface corresponds to a point in some metric space', 'interface IPointInMetricSpace <PointInMetricSpace> {', ' ', ' // get the distance to another point', ' // ', ' // for this to work in an M-Tree, distances should be "metric" and', ' // obey the triangle inequality', ' double getDistance (PointInMetricSpace toMe);', '}', '', '// this is the basic node type in the structure', 'interface IMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> {', ' ', ' // insert a new key/data pair into the structure. The return value is a new MTreeNode if there was', ' // a split in response to the insertion, or a null if there was no split', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd);', ' ', ' // find all of the key/data pairs in the structure that fall within a particular query sphere', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query); ', ' ', ' // find the set of items closest to the given query point', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ);', ' ', ' // returns a sphere that totally encompasses everything in the node and its subtree', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', ' ', ' // returns the depth', ' public int depth ();', '}', '', '// this is a point in a particular metric space', 'class PointABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the point', ' private PointInMetricSpace me;', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return me; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return checkMe.getDistance (me); ', ' }', ' ', ' // contruct a point', ' public PointABCD (PointInMetricSpace useMe) {', ' me = useMe; ', ' }', '}', '', 'class PQueueABCD <PointInMetricSpace, DataType> {', ' ', ' // this is an object in the queue', ' private class Wrapper {', ' DataWrapper <PointInMetricSpace, DataType> myData;', ' double distance;', ' }', ' ', ' // this is the actual queue', ' ArrayList <Wrapper> myList;', ' ', ' // this is the largest distance value currently in the queue', ' double large;', ' ', ' // this is the max number of objects', ' int maxCount;', ' ', ' // create a priority queue with the speced number of slots', ' PQueueABCD (int maxCountIn) {', ' maxCount = maxCountIn;', ' myList = new ArrayList <Wrapper> ();', ' large = 9e99;', ' }', ' ', ' // get the largest distance in the queue', ' double getDist () {', ' return large;', ' }', ' ', ' // add a new object to the queue... the insertion is ignored if the distance value', ' // exceeds the largest that is in the queue and the queue is already full', ' void insert (PointInMetricSpace key, DataType data, double distance) {', ' ', ' // if we are full, remove the one with the largest distance', ' if (myList.size () == maxCount && distance < large) {', ' ', ' int badIndex = 0;', ' double maxDist = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > maxDist) {', ' maxDist = myList.get (i).distance;', ' badIndex = i;', ' }', ' }', ' ', ' myList.remove (badIndex);', ' }', ' ', ' // see if there is room', ' if (myList.size () < maxCount) {', ' ', ' // add it ', ' Wrapper newOne = new Wrapper ();', ' newOne.myData = new DataWrapper <PointInMetricSpace, DataType> (key, data);', ' newOne.distance = distance;', ' myList.add (newOne); ', ' }', ' ', ' // if we are full, reset the max distance', ' if (myList.size () == maxCount) {', ' large = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > large) {', ' large = myList.get (i).distance;', ' }', ' }', ' }', ' ', ' }', ' ', ' // extracts the contents of the queue', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> done () {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' for (int i = 0; i < myList.size (); i++) {', ' returnVal.add (myList.get (i).myData); ', ' }', ' ', ' return returnVal;', ' }', ' ', '}', '', '// this is a sphere in a particular metric space', 'class SphereABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the center of the sphere and its radius', ' private PointInMetricSpace center;', ' private double radius;', ' ', ' // build a sphere out of its center and its radius', ' public SphereABCD (PointInMetricSpace centerIn, double radiusIn) {', ' center = centerIn;', ' radius = radiusIn;', ' }', ' ', ' // increase the size of the sphere so it contains the object swallowMe', ' public void swallow (IObjectInMetricSpaceABCD <PointInMetricSpace> swallowMe) {', ' ', ' // see if we need to increase the radius to swallow this guy', ' double dist = swallowMe.maxDistanceTo (center);', ' if (dist > radius)', ' radius = dist;', ' }', ' ', ' // check to see if a sphere intersects another sphere', ' public boolean intersects (SphereABCD <PointInMetricSpace> me) {', ' return (me.center.getDistance (center) <= me.radius + radius);', ' }', ' ', ' // check to see if the sphere contains a point', ' public boolean contains (PointInMetricSpace checkMe) {', ' return (checkMe.getDistance (center) <= radius);', ' }', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return center; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return radius + checkMe.getDistance (center); ', ' }', '}', '', '', '', 'class OneDimPoint implements IPointInMetricSpace <OneDimPoint> {', ' ', ' // this is the actual double', ' Double value;', ' ', ' // construct this out of a double value', ' public OneDimPoint (double makeFromMe) {', ' value = new Double (makeFromMe);', ' }', ' ', ' // get the distance to another point', ' public double getDistance (OneDimPoint toMe) {', ' if (value > toMe.value)', ' return value - toMe.value;', ' else', ' return toMe.value - value;', ' }', ' ', '}', '', 'class MultiDimPoint implements IPointInMetricSpace <MultiDimPoint> {', ' ', ' // this is the point in a multidimensional space', ' IDoubleVector me;', ' ', ' // make this out of an IDoubleVector', ' public MultiDimPoint (IDoubleVector useMe) {', ' me = useMe;', ' }', ' ', ' // get the Euclidean distance to another point', ' public double getDistance (MultiDimPoint toMe) {', ' double distance = 0.0;', ' try {', ' for (int i = 0; i < me.getLength (); i++) {', ' double diff = me.getItem (i) - toMe.me.getItem (i);', ' diff *= diff;', ' distance += diff;', ' }', ' } catch (OutOfBoundsException e) {', ' throw new IndexOutOfBoundsException ("Can\'t compare two MultiDimPoint objects with different dimensionality!"); ', ' }', ' return Math.sqrt(distance);', ' }', ' ', '}', '// this is a leaf node', 'class LeafMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements ', ' IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myData;', ' ', ' // contructor that takes a data list and builds a node out of it', ' private LeafMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myDataIn) {', ' myData = myDataIn; ', ' }', ' ', ' // constructor that creates an empty node', ' public LeafMTreeNodeABCD () {', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> (); ', ' }', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // just add in the new data', ' myData.add (new PointABCD <PointInMetricSpace> (keyToAdd), dataToAdd);', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> newOne = myData.splitInTwo ();', ' LeafMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' myQ.insert (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData (), ', ' query.getDistance (myData.get (i).getKey ().getPointInInterior ()));', ' }', ' }', ' }', ' ', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' returnVal.add (new DataWrapper <PointInMetricSpace, DataType> (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData ()));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return 1; ', ' }', '', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', '// this silly little class is just a wrapper for a key, data pair', 'class DataWrapper <Key, Data> {', ' ', ' Key key;', ' Data data;', ' ', ' public DataWrapper (Key keyIn, Data dataIn) {'] | [' key = keyIn;', ' data = dataIn;', ' }'] | [' ', ' public Key getKey () {', ' return key;', ' }', ' ', ' public Data getData () {', ' return data;', ' }', '}', '', '', '// this is an internal node', 'class InternalMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType>', ' implements IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> myData;', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' // this constructs a new internal node that holds precisely the two nodes that are passed in', ' public InternalMTreeNodeABCD (IMTreeNodeABCD <PointInMetricSpace, DataType> refOne,', ' IMTreeNodeABCD <PointInMetricSpace, DataType> refTwo) {', ' ', ' // create a necw list and add the two guys in', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> ();', ' myData.add (refOne.getBoundingSphere (), refOne);', ' myData.add (refTwo.getBoundingSphere (), refTwo);', ' }', ' ', ' // this constructs a new node that holds the list of data that we were passed in', ' public InternalMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> useMe) {', ' myData = useMe; ', ' }', ' ', ' // from the interface', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // find the best child; this is the one we are closest to', ' double bestDist = 9e99;', ' int bestIndex = 0;', ' for (int i = 0; i < myData.size (); i++) {', ' ', ' double newDist = myData.get (i).getKey ().getPointInInterior ().getDistance (keyToAdd);', ' if (newDist < bestDist) {', ' bestDist = newDist;', ' bestIndex = i;', ' }', ' }', ' ', ' // do the recursive insert', ' IMTreeNodeABCD <PointInMetricSpace, DataType> newRef = myData.get (bestIndex).getData ().insert (keyToAdd, dataToAdd);', ' ', ' // if we got something back, then there was a split, so add the new node into our list', ' if (newRef != null) {', ' myData.add (newRef.getBoundingSphere (), newRef);', ' }', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> newOne = myData.splitInTwo ();', ' InternalMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.intersects (myData.get (i).getKey ())) {', ' myData.get (i).getData ().findKClosest (query, myQ);', ' }', ' }', ' }', ' ', ' // from the interface', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.intersects (myData.get (i).getKey ())) {', ' returnVal.addAll (myData.get (i).getData ().find (query));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return myData.get (0).getData ().depth () + 1; ', ' }', ' ', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', 'abstract class AMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> implements IMetricDataListABCD <PointInMetricSpace,KeyType, DataType> {', '', ' // this is the data that is actually stored in the list', ' private ArrayList <DataWrapper <KeyType, DataType>> myData;', ' ', ' // this is the sphere that bounds everything in the list', ' private SphereABCD <PointInMetricSpace> myBoundingSphere;', ' ', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myBoundingSphere; ', ' }', ' ', ' public int size () {', ' if (myData != null)', ' return myData.size (); ', ' else', ' return 0;', ' }', ' ', ' public DataWrapper <KeyType, DataType> get (int pos) {', ' return myData.get (pos);', ' }', ' ', ' public void replaceKey (int pos, KeyType keyToAdd) {', ' DataWrapper <KeyType, DataType> temp = myData.remove (pos);', ' DataWrapper <KeyType, DataType> newOne = new DataWrapper <KeyType, DataType> (keyToAdd, temp.getData ());', ' myData.add (pos, newOne);', ' }', ' ', ' public void add (KeyType keyToAdd, DataType dataToAdd) {', ' ', ' // if this is the first add, then set everyone up', ' if (myData == null) {', ' PointInMetricSpace myCentroid = keyToAdd.getPointInInterior ();', ' myBoundingSphere = new SphereABCD <PointInMetricSpace> (myCentroid, keyToAdd.maxDistanceTo (myCentroid));', ' myData = new ArrayList <DataWrapper <KeyType, DataType>> ();', ' ', ' // otherwise, extend the sphere if needed', ' } else {', ' myBoundingSphere.swallow (keyToAdd);', ' }', ' ', ' // add the data', ' myData.add (new DataWrapper <KeyType, DataType> (keyToAdd, dataToAdd));', ' }', ' ', ' // we want to potentially allow many implementations of the splitting lalgorithm', ' abstract public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // this is here so the actual splitting algorithn can access the list and change the sphere', ' protected ArrayList <DataWrapper <KeyType, DataType>> getList () {', ' return myData;', ' }', ' ', ' // this is here so the splitting algorithm can modify the list and the sphere', ' protected void replaceGuts (AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> withMe) {', ' myData = withMe.myData;', ' myBoundingSphere = withMe.myBoundingSphere;', ' }', ' ', '}', '', '// this is a particular implementation of the metric data list that uses a simple quadratic clustering', '// algorithm to perform a list split. It picks two "seeds" (the most distant objects) and then repeatedly', '// adds to the two new lists by choosing the objects closest to the seeds', 'class ChrisMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> extends AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> {', '', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo () {', ' ', ' // first, we need to find the two most distant points in the list', ' ArrayList <DataWrapper <KeyType, DataType>> myData = getList ();', ' int bestI = 0, bestJ = 0;', ' double maxDist = -1.0;', ' for (int i = 0; i < myData.size (); i++) {', ' for (int j = i + 1; j < myData.size (); j++) {', ' ', ' // get the two keys', ' DataWrapper <KeyType, DataType> pointOne = myData.get (i);', ' DataWrapper <KeyType, DataType> pointTwo = myData.get (j);', ' ', ' // find the difference between them', ' double curDist = pointOne.getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', '', ' // see if it is the biggest', ' if (curDist > maxDist) {', ' maxDist = curDist;', ' bestI = i;', ' bestJ = j;', ' }', ' }', ' }', ' ', ' // now, we have the best two points; those are seeds for the clustering', ' DataWrapper <KeyType, DataType> pointOne = myData.remove (bestI);', ' DataWrapper <KeyType, DataType> pointTwo = myData.remove (bestJ - 1);', ' ', ' // these are the two new lists', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listOne = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listTwo = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' ', ' // put the two seeds in', ' listOne.add (pointOne.getKey (), pointOne.getData ());', ' listTwo.add (pointTwo.getKey (), pointTwo.getData ());', ' ', ' // and add everyone else in', ' while (myData.size () != 0) {', ' ', ' // find the one closest to the first seed', ' int bestIndex = 0;', ' double bestDist = 9e99;', ' ', ' // loop thru all of the candidate data objects', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listOne.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' ', ' // break if no more data', ' if (myData.size () == 0)', ' break;', ' ', ' // loop thru all of the candidate data objects', ' bestDist = 9e99;', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listTwo.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' }', ' ', ' // now we replace our own guts with the first list', ' replaceGuts (listOne);', ' ', ' // and return the other list', ' return listTwo;', ' }', '}', '', 'interface IMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> {', ' ', ' // add a new pair to the list', ' public void add (KeyType keyToAdd, DataType dataToAdd);', ' ', ' // replace a key at the indicated position', ' public void replaceKey (int pos, KeyType keyToAdd);', ' ', ' // get the key, data pair that resides at a particular position', ' public DataWrapper <KeyType, DataType> get (int pos);', ' ', ' // return the number of items in the list', ' public int size ();', ' ', ' // split the list in two, using some clutering algorithm', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // get a sphere that totally bounds all of the objects in the list', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class MTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public MTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class SCMTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public SCMTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', '', 'public class MTreeTester extends TestCase {', ' ', ' // compare two lists of strings to see if the contents are the same', ' private boolean compareStringSets (ArrayList <String> setOne, ArrayList <String> setTwo) {', ' ', ' // sort the sets and make sure they are the same', ' boolean returnVal = true;', ' if (setOne.size () == setTwo.size ()) {', ' Collections.sort (setOne);', ' Collections.sort (setTwo);', ' for (int i = 0; i < setOne.size (); i++) {', ' if (!setOne.get (i).equals (setTwo.get (i))) {', ' returnVal = false;', ' break; ', ' }', ' }', ' } else {', ' returnVal = false;', ' }', ' ', ' // print out the result', ' System.out.println ("**** Expected:");', ' for (int i = 0; i < setOne.size (); i++) {', ' System.out.format (setOne.get (i) + " ");', ' }', ' System.out.println ("\\n**** Got:");', ' for (int i = 0; i < setTwo.size (); i++) {', ' System.out.format (setTwo.get (i) + " ");', ' }', ' System.out.println ("");', ' ', ' return returnVal;', ' }', ' ', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST SIMPLE ONE DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testOneDimRangeQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.find (query, expectedQuerySize / 2);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.find (query, expectedQuerySize / 2);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (numPoints);', ' result1 = myTree.find (query, expectedQuerySize);', ' result2 = hisTree.find (query, expectedQuerySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // like the last one, but runs a top k', ' private void testOneDimTopKQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (167);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.findKClosest (query, querySize);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (0);', ' result1 = myTree.findKClosest (query, querySize);', ' result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST MULTI-DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimRangeQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' double dist1 = 0;', ' double dist2 = 0;', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' dist1 = Math.sqrt (numDims) * expectedQuerySize / 2.0;', ' dist2 = Math.sqrt (numDims) * expectedQuerySize;', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' // do a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, (int) expectedQuerySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = myTree.findKClosest (query2, (int) expectedQuerySize);', ' ', ' // find the distance to the furthest point in both cases', ' for (int i = 0; i < (int) expectedQuerySize; i++) {', ' double newDist = result1.get (i).getKey ().getDistance (query1);', ' if (newDist > dist1)', ' dist1 = newDist;', ' newDist = result2.get (i).getKey ().getDistance (query2);', ' if (newDist > dist2)', ' dist2 = newDist;', ' }', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.find (query1, dist1);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.find (query1, dist1);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.find (query2, dist2);', ' result2 = hisTree.find (query2, dist2);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimTopKQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, querySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.findKClosest (query1, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.findKClosest (query2, querySize);', ' result2 = hisTree.findKClosest (query2, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' ', ' /**', ' * "TIER 1" TESTS', ' * NONE OF THESE REQUIRE ANY SPLITS', ' */', ' public void testEasy1() {', ' testOneDimRangeQuery (true, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy2() {', ' testOneDimRangeQuery (false, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy3() {', ' testOneDimRangeQuery (true, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy4() {', ' testOneDimRangeQuery (false, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy5() {', ' testMultiDimRangeQuery (true, 1, 5, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy6() {', ' testMultiDimRangeQuery (false, 1, 10, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy7() {', ' testMultiDimRangeQuery (true, 1, 5, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy8() {', ' testMultiDimRangeQuery (false, 1, 15, 10000, 10000, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 2" TESTS', ' * NONE OF THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testMod1() {', ' testOneDimRangeQuery (true, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod2() {', ' testOneDimRangeQuery (false, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod3() {', ' testOneDimRangeQuery (true, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod4() {', ' testOneDimRangeQuery (false, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod5() {', ' testMultiDimRangeQuery (true, 2, 5, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod6() {', ' testMultiDimRangeQuery (false, 2, 10, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod7() {', ' testMultiDimRangeQuery (true, 2, 5, 10000, 100, 1000, 10);', ' }', ' ', ' public void testMod8() {', ' testMultiDimRangeQuery (false, 2, 15, 10000, 100, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 3" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testHard1() {', ' testOneDimRangeQuery (true, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard2() {', ' testOneDimRangeQuery (false, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard3() {', ' testOneDimRangeQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard4() {', ' testOneDimRangeQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard5() {', ' testMultiDimRangeQuery (true, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard6() {', ' testMultiDimRangeQuery (false, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard7() {', ' testMultiDimRangeQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard8() {', ' testMultiDimRangeQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', ' ', ' /**', ' * "TIER 4" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE AND THEY TEST THE TOPK FUNCTIONALITY', ' */', ' ', ' public void testTopK1() {', ' testOneDimTopKQuery (true, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK2() {', ' testOneDimTopKQuery (false, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK3() {', ' testOneDimTopKQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK4() {', ' testOneDimTopKQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK5() {', ' testMultiDimTopKQuery (true, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK6() {', ' testMultiDimTopKQuery (false, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK7() {', ' testMultiDimTopKQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK8() {', ' testMultiDimTopKQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', '}'] | [] | Variable 'keyIn' used at line 435 is defined at line 434 and has a Short-Range dependency.
Global_Variable 'key' used at line 435 is defined at line 431 and has a Short-Range dependency.
Variable 'dataIn' used at line 436 is defined at line 434 and has a Short-Range dependency.
Global_Variable 'data' used at line 436 is defined at line 432 and has a Short-Range dependency. | {} | {'Variable Short-Range': 2, 'Global_Variable Short-Range': 2} |
infilling_java | MTreeTester | 440 | 441 | ['import junit.framework.TestCase;', 'import java.util.ArrayList;', 'import java.util.Random;', 'import java.util.Collections;', '', '// this is a map from a set of keys of type PointInMetricSpace to a', '// set of data of type DataType', 'interface IMTree <Key extends IPointInMetricSpace <Key>, Data> {', ' ', ' // insert a new key/data pair into the map', ' void insert (Key keyToAdd, Data dataToAdd);', ' ', ' // find all of the key/data pairs in the map that fall within a', ' // particular distance of query point if no results are found, then', ' // an empty array is returned (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> find (Key query, double distance);', ' ', ' // find the k closest key/data pairs in the map to a particular', ' // query point ', ' //', ' // if the number of points in the map is less than k, then the', ' // returned list will have less than k pairs in it', ' //', ' // if the number of points is zero, then an empty array is returned', ' // (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> findKClosest (Key query, int k);', ' ', ' // returns the number of nodes that exist on a path from root to leaf in the tree...', ' // whtever the details of the implementation are, a tree with a single leaf node should return 1, and a tree', ' // with more than one lead node should return at least two (since it must have at least one internal node).', ' public int depth ();', ' ', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', '', 'interface IDoubleVector {', '', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '', '// this correponds to some geometric object in a metric space; the object is built out of', '// one or more points of type PointInMetricSpace', 'interface IObjectInMetricSpaceABCD <PointInMetricSpace extends IPointInMetricSpace<PointInMetricSpace>> {', ' ', ' // get the maximum distance from some point on the shape to a particular point in the metric space', ' double maxDistanceTo (PointInMetricSpace checkMe);', ' ', ' // return some arbitrary point on the interior of the geometric object', ' PointInMetricSpace getPointInInterior ();', '}', '', '', '// this interface corresponds to a point in some metric space', 'interface IPointInMetricSpace <PointInMetricSpace> {', ' ', ' // get the distance to another point', ' // ', ' // for this to work in an M-Tree, distances should be "metric" and', ' // obey the triangle inequality', ' double getDistance (PointInMetricSpace toMe);', '}', '', '// this is the basic node type in the structure', 'interface IMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> {', ' ', ' // insert a new key/data pair into the structure. The return value is a new MTreeNode if there was', ' // a split in response to the insertion, or a null if there was no split', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd);', ' ', ' // find all of the key/data pairs in the structure that fall within a particular query sphere', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query); ', ' ', ' // find the set of items closest to the given query point', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ);', ' ', ' // returns a sphere that totally encompasses everything in the node and its subtree', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', ' ', ' // returns the depth', ' public int depth ();', '}', '', '// this is a point in a particular metric space', 'class PointABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the point', ' private PointInMetricSpace me;', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return me; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return checkMe.getDistance (me); ', ' }', ' ', ' // contruct a point', ' public PointABCD (PointInMetricSpace useMe) {', ' me = useMe; ', ' }', '}', '', 'class PQueueABCD <PointInMetricSpace, DataType> {', ' ', ' // this is an object in the queue', ' private class Wrapper {', ' DataWrapper <PointInMetricSpace, DataType> myData;', ' double distance;', ' }', ' ', ' // this is the actual queue', ' ArrayList <Wrapper> myList;', ' ', ' // this is the largest distance value currently in the queue', ' double large;', ' ', ' // this is the max number of objects', ' int maxCount;', ' ', ' // create a priority queue with the speced number of slots', ' PQueueABCD (int maxCountIn) {', ' maxCount = maxCountIn;', ' myList = new ArrayList <Wrapper> ();', ' large = 9e99;', ' }', ' ', ' // get the largest distance in the queue', ' double getDist () {', ' return large;', ' }', ' ', ' // add a new object to the queue... the insertion is ignored if the distance value', ' // exceeds the largest that is in the queue and the queue is already full', ' void insert (PointInMetricSpace key, DataType data, double distance) {', ' ', ' // if we are full, remove the one with the largest distance', ' if (myList.size () == maxCount && distance < large) {', ' ', ' int badIndex = 0;', ' double maxDist = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > maxDist) {', ' maxDist = myList.get (i).distance;', ' badIndex = i;', ' }', ' }', ' ', ' myList.remove (badIndex);', ' }', ' ', ' // see if there is room', ' if (myList.size () < maxCount) {', ' ', ' // add it ', ' Wrapper newOne = new Wrapper ();', ' newOne.myData = new DataWrapper <PointInMetricSpace, DataType> (key, data);', ' newOne.distance = distance;', ' myList.add (newOne); ', ' }', ' ', ' // if we are full, reset the max distance', ' if (myList.size () == maxCount) {', ' large = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > large) {', ' large = myList.get (i).distance;', ' }', ' }', ' }', ' ', ' }', ' ', ' // extracts the contents of the queue', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> done () {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' for (int i = 0; i < myList.size (); i++) {', ' returnVal.add (myList.get (i).myData); ', ' }', ' ', ' return returnVal;', ' }', ' ', '}', '', '// this is a sphere in a particular metric space', 'class SphereABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the center of the sphere and its radius', ' private PointInMetricSpace center;', ' private double radius;', ' ', ' // build a sphere out of its center and its radius', ' public SphereABCD (PointInMetricSpace centerIn, double radiusIn) {', ' center = centerIn;', ' radius = radiusIn;', ' }', ' ', ' // increase the size of the sphere so it contains the object swallowMe', ' public void swallow (IObjectInMetricSpaceABCD <PointInMetricSpace> swallowMe) {', ' ', ' // see if we need to increase the radius to swallow this guy', ' double dist = swallowMe.maxDistanceTo (center);', ' if (dist > radius)', ' radius = dist;', ' }', ' ', ' // check to see if a sphere intersects another sphere', ' public boolean intersects (SphereABCD <PointInMetricSpace> me) {', ' return (me.center.getDistance (center) <= me.radius + radius);', ' }', ' ', ' // check to see if the sphere contains a point', ' public boolean contains (PointInMetricSpace checkMe) {', ' return (checkMe.getDistance (center) <= radius);', ' }', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return center; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return radius + checkMe.getDistance (center); ', ' }', '}', '', '', '', 'class OneDimPoint implements IPointInMetricSpace <OneDimPoint> {', ' ', ' // this is the actual double', ' Double value;', ' ', ' // construct this out of a double value', ' public OneDimPoint (double makeFromMe) {', ' value = new Double (makeFromMe);', ' }', ' ', ' // get the distance to another point', ' public double getDistance (OneDimPoint toMe) {', ' if (value > toMe.value)', ' return value - toMe.value;', ' else', ' return toMe.value - value;', ' }', ' ', '}', '', 'class MultiDimPoint implements IPointInMetricSpace <MultiDimPoint> {', ' ', ' // this is the point in a multidimensional space', ' IDoubleVector me;', ' ', ' // make this out of an IDoubleVector', ' public MultiDimPoint (IDoubleVector useMe) {', ' me = useMe;', ' }', ' ', ' // get the Euclidean distance to another point', ' public double getDistance (MultiDimPoint toMe) {', ' double distance = 0.0;', ' try {', ' for (int i = 0; i < me.getLength (); i++) {', ' double diff = me.getItem (i) - toMe.me.getItem (i);', ' diff *= diff;', ' distance += diff;', ' }', ' } catch (OutOfBoundsException e) {', ' throw new IndexOutOfBoundsException ("Can\'t compare two MultiDimPoint objects with different dimensionality!"); ', ' }', ' return Math.sqrt(distance);', ' }', ' ', '}', '// this is a leaf node', 'class LeafMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements ', ' IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myData;', ' ', ' // contructor that takes a data list and builds a node out of it', ' private LeafMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myDataIn) {', ' myData = myDataIn; ', ' }', ' ', ' // constructor that creates an empty node', ' public LeafMTreeNodeABCD () {', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> (); ', ' }', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // just add in the new data', ' myData.add (new PointABCD <PointInMetricSpace> (keyToAdd), dataToAdd);', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> newOne = myData.splitInTwo ();', ' LeafMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' myQ.insert (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData (), ', ' query.getDistance (myData.get (i).getKey ().getPointInInterior ()));', ' }', ' }', ' }', ' ', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' returnVal.add (new DataWrapper <PointInMetricSpace, DataType> (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData ()));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return 1; ', ' }', '', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', '// this silly little class is just a wrapper for a key, data pair', 'class DataWrapper <Key, Data> {', ' ', ' Key key;', ' Data data;', ' ', ' public DataWrapper (Key keyIn, Data dataIn) {', ' key = keyIn;', ' data = dataIn;', ' }', ' ', ' public Key getKey () {'] | [' return key;', ' }'] | [' ', ' public Data getData () {', ' return data;', ' }', '}', '', '', '// this is an internal node', 'class InternalMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType>', ' implements IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> myData;', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' // this constructs a new internal node that holds precisely the two nodes that are passed in', ' public InternalMTreeNodeABCD (IMTreeNodeABCD <PointInMetricSpace, DataType> refOne,', ' IMTreeNodeABCD <PointInMetricSpace, DataType> refTwo) {', ' ', ' // create a necw list and add the two guys in', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> ();', ' myData.add (refOne.getBoundingSphere (), refOne);', ' myData.add (refTwo.getBoundingSphere (), refTwo);', ' }', ' ', ' // this constructs a new node that holds the list of data that we were passed in', ' public InternalMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> useMe) {', ' myData = useMe; ', ' }', ' ', ' // from the interface', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // find the best child; this is the one we are closest to', ' double bestDist = 9e99;', ' int bestIndex = 0;', ' for (int i = 0; i < myData.size (); i++) {', ' ', ' double newDist = myData.get (i).getKey ().getPointInInterior ().getDistance (keyToAdd);', ' if (newDist < bestDist) {', ' bestDist = newDist;', ' bestIndex = i;', ' }', ' }', ' ', ' // do the recursive insert', ' IMTreeNodeABCD <PointInMetricSpace, DataType> newRef = myData.get (bestIndex).getData ().insert (keyToAdd, dataToAdd);', ' ', ' // if we got something back, then there was a split, so add the new node into our list', ' if (newRef != null) {', ' myData.add (newRef.getBoundingSphere (), newRef);', ' }', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> newOne = myData.splitInTwo ();', ' InternalMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.intersects (myData.get (i).getKey ())) {', ' myData.get (i).getData ().findKClosest (query, myQ);', ' }', ' }', ' }', ' ', ' // from the interface', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.intersects (myData.get (i).getKey ())) {', ' returnVal.addAll (myData.get (i).getData ().find (query));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return myData.get (0).getData ().depth () + 1; ', ' }', ' ', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', 'abstract class AMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> implements IMetricDataListABCD <PointInMetricSpace,KeyType, DataType> {', '', ' // this is the data that is actually stored in the list', ' private ArrayList <DataWrapper <KeyType, DataType>> myData;', ' ', ' // this is the sphere that bounds everything in the list', ' private SphereABCD <PointInMetricSpace> myBoundingSphere;', ' ', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myBoundingSphere; ', ' }', ' ', ' public int size () {', ' if (myData != null)', ' return myData.size (); ', ' else', ' return 0;', ' }', ' ', ' public DataWrapper <KeyType, DataType> get (int pos) {', ' return myData.get (pos);', ' }', ' ', ' public void replaceKey (int pos, KeyType keyToAdd) {', ' DataWrapper <KeyType, DataType> temp = myData.remove (pos);', ' DataWrapper <KeyType, DataType> newOne = new DataWrapper <KeyType, DataType> (keyToAdd, temp.getData ());', ' myData.add (pos, newOne);', ' }', ' ', ' public void add (KeyType keyToAdd, DataType dataToAdd) {', ' ', ' // if this is the first add, then set everyone up', ' if (myData == null) {', ' PointInMetricSpace myCentroid = keyToAdd.getPointInInterior ();', ' myBoundingSphere = new SphereABCD <PointInMetricSpace> (myCentroid, keyToAdd.maxDistanceTo (myCentroid));', ' myData = new ArrayList <DataWrapper <KeyType, DataType>> ();', ' ', ' // otherwise, extend the sphere if needed', ' } else {', ' myBoundingSphere.swallow (keyToAdd);', ' }', ' ', ' // add the data', ' myData.add (new DataWrapper <KeyType, DataType> (keyToAdd, dataToAdd));', ' }', ' ', ' // we want to potentially allow many implementations of the splitting lalgorithm', ' abstract public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // this is here so the actual splitting algorithn can access the list and change the sphere', ' protected ArrayList <DataWrapper <KeyType, DataType>> getList () {', ' return myData;', ' }', ' ', ' // this is here so the splitting algorithm can modify the list and the sphere', ' protected void replaceGuts (AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> withMe) {', ' myData = withMe.myData;', ' myBoundingSphere = withMe.myBoundingSphere;', ' }', ' ', '}', '', '// this is a particular implementation of the metric data list that uses a simple quadratic clustering', '// algorithm to perform a list split. It picks two "seeds" (the most distant objects) and then repeatedly', '// adds to the two new lists by choosing the objects closest to the seeds', 'class ChrisMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> extends AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> {', '', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo () {', ' ', ' // first, we need to find the two most distant points in the list', ' ArrayList <DataWrapper <KeyType, DataType>> myData = getList ();', ' int bestI = 0, bestJ = 0;', ' double maxDist = -1.0;', ' for (int i = 0; i < myData.size (); i++) {', ' for (int j = i + 1; j < myData.size (); j++) {', ' ', ' // get the two keys', ' DataWrapper <KeyType, DataType> pointOne = myData.get (i);', ' DataWrapper <KeyType, DataType> pointTwo = myData.get (j);', ' ', ' // find the difference between them', ' double curDist = pointOne.getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', '', ' // see if it is the biggest', ' if (curDist > maxDist) {', ' maxDist = curDist;', ' bestI = i;', ' bestJ = j;', ' }', ' }', ' }', ' ', ' // now, we have the best two points; those are seeds for the clustering', ' DataWrapper <KeyType, DataType> pointOne = myData.remove (bestI);', ' DataWrapper <KeyType, DataType> pointTwo = myData.remove (bestJ - 1);', ' ', ' // these are the two new lists', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listOne = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listTwo = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' ', ' // put the two seeds in', ' listOne.add (pointOne.getKey (), pointOne.getData ());', ' listTwo.add (pointTwo.getKey (), pointTwo.getData ());', ' ', ' // and add everyone else in', ' while (myData.size () != 0) {', ' ', ' // find the one closest to the first seed', ' int bestIndex = 0;', ' double bestDist = 9e99;', ' ', ' // loop thru all of the candidate data objects', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listOne.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' ', ' // break if no more data', ' if (myData.size () == 0)', ' break;', ' ', ' // loop thru all of the candidate data objects', ' bestDist = 9e99;', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listTwo.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' }', ' ', ' // now we replace our own guts with the first list', ' replaceGuts (listOne);', ' ', ' // and return the other list', ' return listTwo;', ' }', '}', '', 'interface IMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> {', ' ', ' // add a new pair to the list', ' public void add (KeyType keyToAdd, DataType dataToAdd);', ' ', ' // replace a key at the indicated position', ' public void replaceKey (int pos, KeyType keyToAdd);', ' ', ' // get the key, data pair that resides at a particular position', ' public DataWrapper <KeyType, DataType> get (int pos);', ' ', ' // return the number of items in the list', ' public int size ();', ' ', ' // split the list in two, using some clutering algorithm', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // get a sphere that totally bounds all of the objects in the list', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class MTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public MTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class SCMTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public SCMTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', '', 'public class MTreeTester extends TestCase {', ' ', ' // compare two lists of strings to see if the contents are the same', ' private boolean compareStringSets (ArrayList <String> setOne, ArrayList <String> setTwo) {', ' ', ' // sort the sets and make sure they are the same', ' boolean returnVal = true;', ' if (setOne.size () == setTwo.size ()) {', ' Collections.sort (setOne);', ' Collections.sort (setTwo);', ' for (int i = 0; i < setOne.size (); i++) {', ' if (!setOne.get (i).equals (setTwo.get (i))) {', ' returnVal = false;', ' break; ', ' }', ' }', ' } else {', ' returnVal = false;', ' }', ' ', ' // print out the result', ' System.out.println ("**** Expected:");', ' for (int i = 0; i < setOne.size (); i++) {', ' System.out.format (setOne.get (i) + " ");', ' }', ' System.out.println ("\\n**** Got:");', ' for (int i = 0; i < setTwo.size (); i++) {', ' System.out.format (setTwo.get (i) + " ");', ' }', ' System.out.println ("");', ' ', ' return returnVal;', ' }', ' ', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST SIMPLE ONE DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testOneDimRangeQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.find (query, expectedQuerySize / 2);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.find (query, expectedQuerySize / 2);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (numPoints);', ' result1 = myTree.find (query, expectedQuerySize);', ' result2 = hisTree.find (query, expectedQuerySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // like the last one, but runs a top k', ' private void testOneDimTopKQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (167);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.findKClosest (query, querySize);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (0);', ' result1 = myTree.findKClosest (query, querySize);', ' result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST MULTI-DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimRangeQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' double dist1 = 0;', ' double dist2 = 0;', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' dist1 = Math.sqrt (numDims) * expectedQuerySize / 2.0;', ' dist2 = Math.sqrt (numDims) * expectedQuerySize;', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' // do a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, (int) expectedQuerySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = myTree.findKClosest (query2, (int) expectedQuerySize);', ' ', ' // find the distance to the furthest point in both cases', ' for (int i = 0; i < (int) expectedQuerySize; i++) {', ' double newDist = result1.get (i).getKey ().getDistance (query1);', ' if (newDist > dist1)', ' dist1 = newDist;', ' newDist = result2.get (i).getKey ().getDistance (query2);', ' if (newDist > dist2)', ' dist2 = newDist;', ' }', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.find (query1, dist1);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.find (query1, dist1);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.find (query2, dist2);', ' result2 = hisTree.find (query2, dist2);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimTopKQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, querySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.findKClosest (query1, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.findKClosest (query2, querySize);', ' result2 = hisTree.findKClosest (query2, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' ', ' /**', ' * "TIER 1" TESTS', ' * NONE OF THESE REQUIRE ANY SPLITS', ' */', ' public void testEasy1() {', ' testOneDimRangeQuery (true, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy2() {', ' testOneDimRangeQuery (false, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy3() {', ' testOneDimRangeQuery (true, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy4() {', ' testOneDimRangeQuery (false, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy5() {', ' testMultiDimRangeQuery (true, 1, 5, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy6() {', ' testMultiDimRangeQuery (false, 1, 10, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy7() {', ' testMultiDimRangeQuery (true, 1, 5, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy8() {', ' testMultiDimRangeQuery (false, 1, 15, 10000, 10000, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 2" TESTS', ' * NONE OF THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testMod1() {', ' testOneDimRangeQuery (true, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod2() {', ' testOneDimRangeQuery (false, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod3() {', ' testOneDimRangeQuery (true, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod4() {', ' testOneDimRangeQuery (false, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod5() {', ' testMultiDimRangeQuery (true, 2, 5, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod6() {', ' testMultiDimRangeQuery (false, 2, 10, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod7() {', ' testMultiDimRangeQuery (true, 2, 5, 10000, 100, 1000, 10);', ' }', ' ', ' public void testMod8() {', ' testMultiDimRangeQuery (false, 2, 15, 10000, 100, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 3" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testHard1() {', ' testOneDimRangeQuery (true, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard2() {', ' testOneDimRangeQuery (false, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard3() {', ' testOneDimRangeQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard4() {', ' testOneDimRangeQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard5() {', ' testMultiDimRangeQuery (true, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard6() {', ' testMultiDimRangeQuery (false, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard7() {', ' testMultiDimRangeQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard8() {', ' testMultiDimRangeQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', ' ', ' /**', ' * "TIER 4" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE AND THEY TEST THE TOPK FUNCTIONALITY', ' */', ' ', ' public void testTopK1() {', ' testOneDimTopKQuery (true, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK2() {', ' testOneDimTopKQuery (false, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK3() {', ' testOneDimTopKQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK4() {', ' testOneDimTopKQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK5() {', ' testMultiDimTopKQuery (true, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK6() {', ' testMultiDimTopKQuery (false, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK7() {', ' testMultiDimTopKQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK8() {', ' testMultiDimTopKQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', '}'] | [] | Global_Variable 'key' used at line 440 is defined at line 431 and has a Short-Range dependency. | {} | {'Global_Variable Short-Range': 1} |
infilling_java | MTreeTester | 444 | 446 | ['import junit.framework.TestCase;', 'import java.util.ArrayList;', 'import java.util.Random;', 'import java.util.Collections;', '', '// this is a map from a set of keys of type PointInMetricSpace to a', '// set of data of type DataType', 'interface IMTree <Key extends IPointInMetricSpace <Key>, Data> {', ' ', ' // insert a new key/data pair into the map', ' void insert (Key keyToAdd, Data dataToAdd);', ' ', ' // find all of the key/data pairs in the map that fall within a', ' // particular distance of query point if no results are found, then', ' // an empty array is returned (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> find (Key query, double distance);', ' ', ' // find the k closest key/data pairs in the map to a particular', ' // query point ', ' //', ' // if the number of points in the map is less than k, then the', ' // returned list will have less than k pairs in it', ' //', ' // if the number of points is zero, then an empty array is returned', ' // (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> findKClosest (Key query, int k);', ' ', ' // returns the number of nodes that exist on a path from root to leaf in the tree...', ' // whtever the details of the implementation are, a tree with a single leaf node should return 1, and a tree', ' // with more than one lead node should return at least two (since it must have at least one internal node).', ' public int depth ();', ' ', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', '', 'interface IDoubleVector {', '', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '', '// this correponds to some geometric object in a metric space; the object is built out of', '// one or more points of type PointInMetricSpace', 'interface IObjectInMetricSpaceABCD <PointInMetricSpace extends IPointInMetricSpace<PointInMetricSpace>> {', ' ', ' // get the maximum distance from some point on the shape to a particular point in the metric space', ' double maxDistanceTo (PointInMetricSpace checkMe);', ' ', ' // return some arbitrary point on the interior of the geometric object', ' PointInMetricSpace getPointInInterior ();', '}', '', '', '// this interface corresponds to a point in some metric space', 'interface IPointInMetricSpace <PointInMetricSpace> {', ' ', ' // get the distance to another point', ' // ', ' // for this to work in an M-Tree, distances should be "metric" and', ' // obey the triangle inequality', ' double getDistance (PointInMetricSpace toMe);', '}', '', '// this is the basic node type in the structure', 'interface IMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> {', ' ', ' // insert a new key/data pair into the structure. The return value is a new MTreeNode if there was', ' // a split in response to the insertion, or a null if there was no split', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd);', ' ', ' // find all of the key/data pairs in the structure that fall within a particular query sphere', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query); ', ' ', ' // find the set of items closest to the given query point', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ);', ' ', ' // returns a sphere that totally encompasses everything in the node and its subtree', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', ' ', ' // returns the depth', ' public int depth ();', '}', '', '// this is a point in a particular metric space', 'class PointABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the point', ' private PointInMetricSpace me;', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return me; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return checkMe.getDistance (me); ', ' }', ' ', ' // contruct a point', ' public PointABCD (PointInMetricSpace useMe) {', ' me = useMe; ', ' }', '}', '', 'class PQueueABCD <PointInMetricSpace, DataType> {', ' ', ' // this is an object in the queue', ' private class Wrapper {', ' DataWrapper <PointInMetricSpace, DataType> myData;', ' double distance;', ' }', ' ', ' // this is the actual queue', ' ArrayList <Wrapper> myList;', ' ', ' // this is the largest distance value currently in the queue', ' double large;', ' ', ' // this is the max number of objects', ' int maxCount;', ' ', ' // create a priority queue with the speced number of slots', ' PQueueABCD (int maxCountIn) {', ' maxCount = maxCountIn;', ' myList = new ArrayList <Wrapper> ();', ' large = 9e99;', ' }', ' ', ' // get the largest distance in the queue', ' double getDist () {', ' return large;', ' }', ' ', ' // add a new object to the queue... the insertion is ignored if the distance value', ' // exceeds the largest that is in the queue and the queue is already full', ' void insert (PointInMetricSpace key, DataType data, double distance) {', ' ', ' // if we are full, remove the one with the largest distance', ' if (myList.size () == maxCount && distance < large) {', ' ', ' int badIndex = 0;', ' double maxDist = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > maxDist) {', ' maxDist = myList.get (i).distance;', ' badIndex = i;', ' }', ' }', ' ', ' myList.remove (badIndex);', ' }', ' ', ' // see if there is room', ' if (myList.size () < maxCount) {', ' ', ' // add it ', ' Wrapper newOne = new Wrapper ();', ' newOne.myData = new DataWrapper <PointInMetricSpace, DataType> (key, data);', ' newOne.distance = distance;', ' myList.add (newOne); ', ' }', ' ', ' // if we are full, reset the max distance', ' if (myList.size () == maxCount) {', ' large = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > large) {', ' large = myList.get (i).distance;', ' }', ' }', ' }', ' ', ' }', ' ', ' // extracts the contents of the queue', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> done () {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' for (int i = 0; i < myList.size (); i++) {', ' returnVal.add (myList.get (i).myData); ', ' }', ' ', ' return returnVal;', ' }', ' ', '}', '', '// this is a sphere in a particular metric space', 'class SphereABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the center of the sphere and its radius', ' private PointInMetricSpace center;', ' private double radius;', ' ', ' // build a sphere out of its center and its radius', ' public SphereABCD (PointInMetricSpace centerIn, double radiusIn) {', ' center = centerIn;', ' radius = radiusIn;', ' }', ' ', ' // increase the size of the sphere so it contains the object swallowMe', ' public void swallow (IObjectInMetricSpaceABCD <PointInMetricSpace> swallowMe) {', ' ', ' // see if we need to increase the radius to swallow this guy', ' double dist = swallowMe.maxDistanceTo (center);', ' if (dist > radius)', ' radius = dist;', ' }', ' ', ' // check to see if a sphere intersects another sphere', ' public boolean intersects (SphereABCD <PointInMetricSpace> me) {', ' return (me.center.getDistance (center) <= me.radius + radius);', ' }', ' ', ' // check to see if the sphere contains a point', ' public boolean contains (PointInMetricSpace checkMe) {', ' return (checkMe.getDistance (center) <= radius);', ' }', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return center; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return radius + checkMe.getDistance (center); ', ' }', '}', '', '', '', 'class OneDimPoint implements IPointInMetricSpace <OneDimPoint> {', ' ', ' // this is the actual double', ' Double value;', ' ', ' // construct this out of a double value', ' public OneDimPoint (double makeFromMe) {', ' value = new Double (makeFromMe);', ' }', ' ', ' // get the distance to another point', ' public double getDistance (OneDimPoint toMe) {', ' if (value > toMe.value)', ' return value - toMe.value;', ' else', ' return toMe.value - value;', ' }', ' ', '}', '', 'class MultiDimPoint implements IPointInMetricSpace <MultiDimPoint> {', ' ', ' // this is the point in a multidimensional space', ' IDoubleVector me;', ' ', ' // make this out of an IDoubleVector', ' public MultiDimPoint (IDoubleVector useMe) {', ' me = useMe;', ' }', ' ', ' // get the Euclidean distance to another point', ' public double getDistance (MultiDimPoint toMe) {', ' double distance = 0.0;', ' try {', ' for (int i = 0; i < me.getLength (); i++) {', ' double diff = me.getItem (i) - toMe.me.getItem (i);', ' diff *= diff;', ' distance += diff;', ' }', ' } catch (OutOfBoundsException e) {', ' throw new IndexOutOfBoundsException ("Can\'t compare two MultiDimPoint objects with different dimensionality!"); ', ' }', ' return Math.sqrt(distance);', ' }', ' ', '}', '// this is a leaf node', 'class LeafMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements ', ' IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myData;', ' ', ' // contructor that takes a data list and builds a node out of it', ' private LeafMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myDataIn) {', ' myData = myDataIn; ', ' }', ' ', ' // constructor that creates an empty node', ' public LeafMTreeNodeABCD () {', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> (); ', ' }', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // just add in the new data', ' myData.add (new PointABCD <PointInMetricSpace> (keyToAdd), dataToAdd);', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> newOne = myData.splitInTwo ();', ' LeafMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' myQ.insert (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData (), ', ' query.getDistance (myData.get (i).getKey ().getPointInInterior ()));', ' }', ' }', ' }', ' ', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' returnVal.add (new DataWrapper <PointInMetricSpace, DataType> (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData ()));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return 1; ', ' }', '', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', '// this silly little class is just a wrapper for a key, data pair', 'class DataWrapper <Key, Data> {', ' ', ' Key key;', ' Data data;', ' ', ' public DataWrapper (Key keyIn, Data dataIn) {', ' key = keyIn;', ' data = dataIn;', ' }', ' ', ' public Key getKey () {', ' return key;', ' }', ' ', ' public Data getData () {'] | [' return data;', ' }', '}'] | ['', '', '// this is an internal node', 'class InternalMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType>', ' implements IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> myData;', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' // this constructs a new internal node that holds precisely the two nodes that are passed in', ' public InternalMTreeNodeABCD (IMTreeNodeABCD <PointInMetricSpace, DataType> refOne,', ' IMTreeNodeABCD <PointInMetricSpace, DataType> refTwo) {', ' ', ' // create a necw list and add the two guys in', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> ();', ' myData.add (refOne.getBoundingSphere (), refOne);', ' myData.add (refTwo.getBoundingSphere (), refTwo);', ' }', ' ', ' // this constructs a new node that holds the list of data that we were passed in', ' public InternalMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> useMe) {', ' myData = useMe; ', ' }', ' ', ' // from the interface', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // find the best child; this is the one we are closest to', ' double bestDist = 9e99;', ' int bestIndex = 0;', ' for (int i = 0; i < myData.size (); i++) {', ' ', ' double newDist = myData.get (i).getKey ().getPointInInterior ().getDistance (keyToAdd);', ' if (newDist < bestDist) {', ' bestDist = newDist;', ' bestIndex = i;', ' }', ' }', ' ', ' // do the recursive insert', ' IMTreeNodeABCD <PointInMetricSpace, DataType> newRef = myData.get (bestIndex).getData ().insert (keyToAdd, dataToAdd);', ' ', ' // if we got something back, then there was a split, so add the new node into our list', ' if (newRef != null) {', ' myData.add (newRef.getBoundingSphere (), newRef);', ' }', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> newOne = myData.splitInTwo ();', ' InternalMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.intersects (myData.get (i).getKey ())) {', ' myData.get (i).getData ().findKClosest (query, myQ);', ' }', ' }', ' }', ' ', ' // from the interface', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.intersects (myData.get (i).getKey ())) {', ' returnVal.addAll (myData.get (i).getData ().find (query));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return myData.get (0).getData ().depth () + 1; ', ' }', ' ', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', 'abstract class AMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> implements IMetricDataListABCD <PointInMetricSpace,KeyType, DataType> {', '', ' // this is the data that is actually stored in the list', ' private ArrayList <DataWrapper <KeyType, DataType>> myData;', ' ', ' // this is the sphere that bounds everything in the list', ' private SphereABCD <PointInMetricSpace> myBoundingSphere;', ' ', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myBoundingSphere; ', ' }', ' ', ' public int size () {', ' if (myData != null)', ' return myData.size (); ', ' else', ' return 0;', ' }', ' ', ' public DataWrapper <KeyType, DataType> get (int pos) {', ' return myData.get (pos);', ' }', ' ', ' public void replaceKey (int pos, KeyType keyToAdd) {', ' DataWrapper <KeyType, DataType> temp = myData.remove (pos);', ' DataWrapper <KeyType, DataType> newOne = new DataWrapper <KeyType, DataType> (keyToAdd, temp.getData ());', ' myData.add (pos, newOne);', ' }', ' ', ' public void add (KeyType keyToAdd, DataType dataToAdd) {', ' ', ' // if this is the first add, then set everyone up', ' if (myData == null) {', ' PointInMetricSpace myCentroid = keyToAdd.getPointInInterior ();', ' myBoundingSphere = new SphereABCD <PointInMetricSpace> (myCentroid, keyToAdd.maxDistanceTo (myCentroid));', ' myData = new ArrayList <DataWrapper <KeyType, DataType>> ();', ' ', ' // otherwise, extend the sphere if needed', ' } else {', ' myBoundingSphere.swallow (keyToAdd);', ' }', ' ', ' // add the data', ' myData.add (new DataWrapper <KeyType, DataType> (keyToAdd, dataToAdd));', ' }', ' ', ' // we want to potentially allow many implementations of the splitting lalgorithm', ' abstract public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // this is here so the actual splitting algorithn can access the list and change the sphere', ' protected ArrayList <DataWrapper <KeyType, DataType>> getList () {', ' return myData;', ' }', ' ', ' // this is here so the splitting algorithm can modify the list and the sphere', ' protected void replaceGuts (AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> withMe) {', ' myData = withMe.myData;', ' myBoundingSphere = withMe.myBoundingSphere;', ' }', ' ', '}', '', '// this is a particular implementation of the metric data list that uses a simple quadratic clustering', '// algorithm to perform a list split. It picks two "seeds" (the most distant objects) and then repeatedly', '// adds to the two new lists by choosing the objects closest to the seeds', 'class ChrisMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> extends AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> {', '', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo () {', ' ', ' // first, we need to find the two most distant points in the list', ' ArrayList <DataWrapper <KeyType, DataType>> myData = getList ();', ' int bestI = 0, bestJ = 0;', ' double maxDist = -1.0;', ' for (int i = 0; i < myData.size (); i++) {', ' for (int j = i + 1; j < myData.size (); j++) {', ' ', ' // get the two keys', ' DataWrapper <KeyType, DataType> pointOne = myData.get (i);', ' DataWrapper <KeyType, DataType> pointTwo = myData.get (j);', ' ', ' // find the difference between them', ' double curDist = pointOne.getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', '', ' // see if it is the biggest', ' if (curDist > maxDist) {', ' maxDist = curDist;', ' bestI = i;', ' bestJ = j;', ' }', ' }', ' }', ' ', ' // now, we have the best two points; those are seeds for the clustering', ' DataWrapper <KeyType, DataType> pointOne = myData.remove (bestI);', ' DataWrapper <KeyType, DataType> pointTwo = myData.remove (bestJ - 1);', ' ', ' // these are the two new lists', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listOne = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listTwo = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' ', ' // put the two seeds in', ' listOne.add (pointOne.getKey (), pointOne.getData ());', ' listTwo.add (pointTwo.getKey (), pointTwo.getData ());', ' ', ' // and add everyone else in', ' while (myData.size () != 0) {', ' ', ' // find the one closest to the first seed', ' int bestIndex = 0;', ' double bestDist = 9e99;', ' ', ' // loop thru all of the candidate data objects', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listOne.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' ', ' // break if no more data', ' if (myData.size () == 0)', ' break;', ' ', ' // loop thru all of the candidate data objects', ' bestDist = 9e99;', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listTwo.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' }', ' ', ' // now we replace our own guts with the first list', ' replaceGuts (listOne);', ' ', ' // and return the other list', ' return listTwo;', ' }', '}', '', 'interface IMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> {', ' ', ' // add a new pair to the list', ' public void add (KeyType keyToAdd, DataType dataToAdd);', ' ', ' // replace a key at the indicated position', ' public void replaceKey (int pos, KeyType keyToAdd);', ' ', ' // get the key, data pair that resides at a particular position', ' public DataWrapper <KeyType, DataType> get (int pos);', ' ', ' // return the number of items in the list', ' public int size ();', ' ', ' // split the list in two, using some clutering algorithm', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // get a sphere that totally bounds all of the objects in the list', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class MTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public MTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class SCMTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public SCMTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', '', 'public class MTreeTester extends TestCase {', ' ', ' // compare two lists of strings to see if the contents are the same', ' private boolean compareStringSets (ArrayList <String> setOne, ArrayList <String> setTwo) {', ' ', ' // sort the sets and make sure they are the same', ' boolean returnVal = true;', ' if (setOne.size () == setTwo.size ()) {', ' Collections.sort (setOne);', ' Collections.sort (setTwo);', ' for (int i = 0; i < setOne.size (); i++) {', ' if (!setOne.get (i).equals (setTwo.get (i))) {', ' returnVal = false;', ' break; ', ' }', ' }', ' } else {', ' returnVal = false;', ' }', ' ', ' // print out the result', ' System.out.println ("**** Expected:");', ' for (int i = 0; i < setOne.size (); i++) {', ' System.out.format (setOne.get (i) + " ");', ' }', ' System.out.println ("\\n**** Got:");', ' for (int i = 0; i < setTwo.size (); i++) {', ' System.out.format (setTwo.get (i) + " ");', ' }', ' System.out.println ("");', ' ', ' return returnVal;', ' }', ' ', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST SIMPLE ONE DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testOneDimRangeQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.find (query, expectedQuerySize / 2);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.find (query, expectedQuerySize / 2);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (numPoints);', ' result1 = myTree.find (query, expectedQuerySize);', ' result2 = hisTree.find (query, expectedQuerySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // like the last one, but runs a top k', ' private void testOneDimTopKQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (167);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.findKClosest (query, querySize);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (0);', ' result1 = myTree.findKClosest (query, querySize);', ' result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST MULTI-DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimRangeQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' double dist1 = 0;', ' double dist2 = 0;', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' dist1 = Math.sqrt (numDims) * expectedQuerySize / 2.0;', ' dist2 = Math.sqrt (numDims) * expectedQuerySize;', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' // do a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, (int) expectedQuerySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = myTree.findKClosest (query2, (int) expectedQuerySize);', ' ', ' // find the distance to the furthest point in both cases', ' for (int i = 0; i < (int) expectedQuerySize; i++) {', ' double newDist = result1.get (i).getKey ().getDistance (query1);', ' if (newDist > dist1)', ' dist1 = newDist;', ' newDist = result2.get (i).getKey ().getDistance (query2);', ' if (newDist > dist2)', ' dist2 = newDist;', ' }', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.find (query1, dist1);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.find (query1, dist1);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.find (query2, dist2);', ' result2 = hisTree.find (query2, dist2);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimTopKQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, querySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.findKClosest (query1, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.findKClosest (query2, querySize);', ' result2 = hisTree.findKClosest (query2, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' ', ' /**', ' * "TIER 1" TESTS', ' * NONE OF THESE REQUIRE ANY SPLITS', ' */', ' public void testEasy1() {', ' testOneDimRangeQuery (true, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy2() {', ' testOneDimRangeQuery (false, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy3() {', ' testOneDimRangeQuery (true, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy4() {', ' testOneDimRangeQuery (false, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy5() {', ' testMultiDimRangeQuery (true, 1, 5, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy6() {', ' testMultiDimRangeQuery (false, 1, 10, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy7() {', ' testMultiDimRangeQuery (true, 1, 5, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy8() {', ' testMultiDimRangeQuery (false, 1, 15, 10000, 10000, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 2" TESTS', ' * NONE OF THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testMod1() {', ' testOneDimRangeQuery (true, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod2() {', ' testOneDimRangeQuery (false, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod3() {', ' testOneDimRangeQuery (true, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod4() {', ' testOneDimRangeQuery (false, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod5() {', ' testMultiDimRangeQuery (true, 2, 5, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod6() {', ' testMultiDimRangeQuery (false, 2, 10, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod7() {', ' testMultiDimRangeQuery (true, 2, 5, 10000, 100, 1000, 10);', ' }', ' ', ' public void testMod8() {', ' testMultiDimRangeQuery (false, 2, 15, 10000, 100, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 3" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testHard1() {', ' testOneDimRangeQuery (true, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard2() {', ' testOneDimRangeQuery (false, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard3() {', ' testOneDimRangeQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard4() {', ' testOneDimRangeQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard5() {', ' testMultiDimRangeQuery (true, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard6() {', ' testMultiDimRangeQuery (false, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard7() {', ' testMultiDimRangeQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard8() {', ' testMultiDimRangeQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', ' ', ' /**', ' * "TIER 4" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE AND THEY TEST THE TOPK FUNCTIONALITY', ' */', ' ', ' public void testTopK1() {', ' testOneDimTopKQuery (true, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK2() {', ' testOneDimTopKQuery (false, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK3() {', ' testOneDimTopKQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK4() {', ' testOneDimTopKQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK5() {', ' testMultiDimTopKQuery (true, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK6() {', ' testMultiDimTopKQuery (false, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK7() {', ' testMultiDimTopKQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK8() {', ' testMultiDimTopKQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', '}'] | [] | Global_Variable 'data' used at line 444 is defined at line 432 and has a Medium-Range dependency. | {} | {'Global_Variable Medium-Range': 1} |
infilling_java | MTreeTester | 486 | 488 | ['import junit.framework.TestCase;', 'import java.util.ArrayList;', 'import java.util.Random;', 'import java.util.Collections;', '', '// this is a map from a set of keys of type PointInMetricSpace to a', '// set of data of type DataType', 'interface IMTree <Key extends IPointInMetricSpace <Key>, Data> {', ' ', ' // insert a new key/data pair into the map', ' void insert (Key keyToAdd, Data dataToAdd);', ' ', ' // find all of the key/data pairs in the map that fall within a', ' // particular distance of query point if no results are found, then', ' // an empty array is returned (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> find (Key query, double distance);', ' ', ' // find the k closest key/data pairs in the map to a particular', ' // query point ', ' //', ' // if the number of points in the map is less than k, then the', ' // returned list will have less than k pairs in it', ' //', ' // if the number of points is zero, then an empty array is returned', ' // (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> findKClosest (Key query, int k);', ' ', ' // returns the number of nodes that exist on a path from root to leaf in the tree...', ' // whtever the details of the implementation are, a tree with a single leaf node should return 1, and a tree', ' // with more than one lead node should return at least two (since it must have at least one internal node).', ' public int depth ();', ' ', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', '', 'interface IDoubleVector {', '', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '', '// this correponds to some geometric object in a metric space; the object is built out of', '// one or more points of type PointInMetricSpace', 'interface IObjectInMetricSpaceABCD <PointInMetricSpace extends IPointInMetricSpace<PointInMetricSpace>> {', ' ', ' // get the maximum distance from some point on the shape to a particular point in the metric space', ' double maxDistanceTo (PointInMetricSpace checkMe);', ' ', ' // return some arbitrary point on the interior of the geometric object', ' PointInMetricSpace getPointInInterior ();', '}', '', '', '// this interface corresponds to a point in some metric space', 'interface IPointInMetricSpace <PointInMetricSpace> {', ' ', ' // get the distance to another point', ' // ', ' // for this to work in an M-Tree, distances should be "metric" and', ' // obey the triangle inequality', ' double getDistance (PointInMetricSpace toMe);', '}', '', '// this is the basic node type in the structure', 'interface IMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> {', ' ', ' // insert a new key/data pair into the structure. The return value is a new MTreeNode if there was', ' // a split in response to the insertion, or a null if there was no split', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd);', ' ', ' // find all of the key/data pairs in the structure that fall within a particular query sphere', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query); ', ' ', ' // find the set of items closest to the given query point', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ);', ' ', ' // returns a sphere that totally encompasses everything in the node and its subtree', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', ' ', ' // returns the depth', ' public int depth ();', '}', '', '// this is a point in a particular metric space', 'class PointABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the point', ' private PointInMetricSpace me;', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return me; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return checkMe.getDistance (me); ', ' }', ' ', ' // contruct a point', ' public PointABCD (PointInMetricSpace useMe) {', ' me = useMe; ', ' }', '}', '', 'class PQueueABCD <PointInMetricSpace, DataType> {', ' ', ' // this is an object in the queue', ' private class Wrapper {', ' DataWrapper <PointInMetricSpace, DataType> myData;', ' double distance;', ' }', ' ', ' // this is the actual queue', ' ArrayList <Wrapper> myList;', ' ', ' // this is the largest distance value currently in the queue', ' double large;', ' ', ' // this is the max number of objects', ' int maxCount;', ' ', ' // create a priority queue with the speced number of slots', ' PQueueABCD (int maxCountIn) {', ' maxCount = maxCountIn;', ' myList = new ArrayList <Wrapper> ();', ' large = 9e99;', ' }', ' ', ' // get the largest distance in the queue', ' double getDist () {', ' return large;', ' }', ' ', ' // add a new object to the queue... the insertion is ignored if the distance value', ' // exceeds the largest that is in the queue and the queue is already full', ' void insert (PointInMetricSpace key, DataType data, double distance) {', ' ', ' // if we are full, remove the one with the largest distance', ' if (myList.size () == maxCount && distance < large) {', ' ', ' int badIndex = 0;', ' double maxDist = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > maxDist) {', ' maxDist = myList.get (i).distance;', ' badIndex = i;', ' }', ' }', ' ', ' myList.remove (badIndex);', ' }', ' ', ' // see if there is room', ' if (myList.size () < maxCount) {', ' ', ' // add it ', ' Wrapper newOne = new Wrapper ();', ' newOne.myData = new DataWrapper <PointInMetricSpace, DataType> (key, data);', ' newOne.distance = distance;', ' myList.add (newOne); ', ' }', ' ', ' // if we are full, reset the max distance', ' if (myList.size () == maxCount) {', ' large = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > large) {', ' large = myList.get (i).distance;', ' }', ' }', ' }', ' ', ' }', ' ', ' // extracts the contents of the queue', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> done () {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' for (int i = 0; i < myList.size (); i++) {', ' returnVal.add (myList.get (i).myData); ', ' }', ' ', ' return returnVal;', ' }', ' ', '}', '', '// this is a sphere in a particular metric space', 'class SphereABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the center of the sphere and its radius', ' private PointInMetricSpace center;', ' private double radius;', ' ', ' // build a sphere out of its center and its radius', ' public SphereABCD (PointInMetricSpace centerIn, double radiusIn) {', ' center = centerIn;', ' radius = radiusIn;', ' }', ' ', ' // increase the size of the sphere so it contains the object swallowMe', ' public void swallow (IObjectInMetricSpaceABCD <PointInMetricSpace> swallowMe) {', ' ', ' // see if we need to increase the radius to swallow this guy', ' double dist = swallowMe.maxDistanceTo (center);', ' if (dist > radius)', ' radius = dist;', ' }', ' ', ' // check to see if a sphere intersects another sphere', ' public boolean intersects (SphereABCD <PointInMetricSpace> me) {', ' return (me.center.getDistance (center) <= me.radius + radius);', ' }', ' ', ' // check to see if the sphere contains a point', ' public boolean contains (PointInMetricSpace checkMe) {', ' return (checkMe.getDistance (center) <= radius);', ' }', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return center; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return radius + checkMe.getDistance (center); ', ' }', '}', '', '', '', 'class OneDimPoint implements IPointInMetricSpace <OneDimPoint> {', ' ', ' // this is the actual double', ' Double value;', ' ', ' // construct this out of a double value', ' public OneDimPoint (double makeFromMe) {', ' value = new Double (makeFromMe);', ' }', ' ', ' // get the distance to another point', ' public double getDistance (OneDimPoint toMe) {', ' if (value > toMe.value)', ' return value - toMe.value;', ' else', ' return toMe.value - value;', ' }', ' ', '}', '', 'class MultiDimPoint implements IPointInMetricSpace <MultiDimPoint> {', ' ', ' // this is the point in a multidimensional space', ' IDoubleVector me;', ' ', ' // make this out of an IDoubleVector', ' public MultiDimPoint (IDoubleVector useMe) {', ' me = useMe;', ' }', ' ', ' // get the Euclidean distance to another point', ' public double getDistance (MultiDimPoint toMe) {', ' double distance = 0.0;', ' try {', ' for (int i = 0; i < me.getLength (); i++) {', ' double diff = me.getItem (i) - toMe.me.getItem (i);', ' diff *= diff;', ' distance += diff;', ' }', ' } catch (OutOfBoundsException e) {', ' throw new IndexOutOfBoundsException ("Can\'t compare two MultiDimPoint objects with different dimensionality!"); ', ' }', ' return Math.sqrt(distance);', ' }', ' ', '}', '// this is a leaf node', 'class LeafMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements ', ' IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myData;', ' ', ' // contructor that takes a data list and builds a node out of it', ' private LeafMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myDataIn) {', ' myData = myDataIn; ', ' }', ' ', ' // constructor that creates an empty node', ' public LeafMTreeNodeABCD () {', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> (); ', ' }', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // just add in the new data', ' myData.add (new PointABCD <PointInMetricSpace> (keyToAdd), dataToAdd);', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> newOne = myData.splitInTwo ();', ' LeafMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' myQ.insert (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData (), ', ' query.getDistance (myData.get (i).getKey ().getPointInInterior ()));', ' }', ' }', ' }', ' ', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' returnVal.add (new DataWrapper <PointInMetricSpace, DataType> (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData ()));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return 1; ', ' }', '', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', '// this silly little class is just a wrapper for a key, data pair', 'class DataWrapper <Key, Data> {', ' ', ' Key key;', ' Data data;', ' ', ' public DataWrapper (Key keyIn, Data dataIn) {', ' key = keyIn;', ' data = dataIn;', ' }', ' ', ' public Key getKey () {', ' return key;', ' }', ' ', ' public Data getData () {', ' return data;', ' }', '}', '', '', '// this is an internal node', 'class InternalMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType>', ' implements IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> myData;', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' // this constructs a new internal node that holds precisely the two nodes that are passed in', ' public InternalMTreeNodeABCD (IMTreeNodeABCD <PointInMetricSpace, DataType> refOne,', ' IMTreeNodeABCD <PointInMetricSpace, DataType> refTwo) {', ' ', ' // create a necw list and add the two guys in', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> ();', ' myData.add (refOne.getBoundingSphere (), refOne);', ' myData.add (refTwo.getBoundingSphere (), refTwo);', ' }', ' ', ' // this constructs a new node that holds the list of data that we were passed in', ' public InternalMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> useMe) {', ' myData = useMe; ', ' }', ' ', ' // from the interface', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // find the best child; this is the one we are closest to', ' double bestDist = 9e99;', ' int bestIndex = 0;', ' for (int i = 0; i < myData.size (); i++) {', ' ', ' double newDist = myData.get (i).getKey ().getPointInInterior ().getDistance (keyToAdd);', ' if (newDist < bestDist) {'] | [' bestDist = newDist;', ' bestIndex = i;', ' }'] | [' }', ' ', ' // do the recursive insert', ' IMTreeNodeABCD <PointInMetricSpace, DataType> newRef = myData.get (bestIndex).getData ().insert (keyToAdd, dataToAdd);', ' ', ' // if we got something back, then there was a split, so add the new node into our list', ' if (newRef != null) {', ' myData.add (newRef.getBoundingSphere (), newRef);', ' }', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> newOne = myData.splitInTwo ();', ' InternalMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.intersects (myData.get (i).getKey ())) {', ' myData.get (i).getData ().findKClosest (query, myQ);', ' }', ' }', ' }', ' ', ' // from the interface', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.intersects (myData.get (i).getKey ())) {', ' returnVal.addAll (myData.get (i).getData ().find (query));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return myData.get (0).getData ().depth () + 1; ', ' }', ' ', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', 'abstract class AMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> implements IMetricDataListABCD <PointInMetricSpace,KeyType, DataType> {', '', ' // this is the data that is actually stored in the list', ' private ArrayList <DataWrapper <KeyType, DataType>> myData;', ' ', ' // this is the sphere that bounds everything in the list', ' private SphereABCD <PointInMetricSpace> myBoundingSphere;', ' ', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myBoundingSphere; ', ' }', ' ', ' public int size () {', ' if (myData != null)', ' return myData.size (); ', ' else', ' return 0;', ' }', ' ', ' public DataWrapper <KeyType, DataType> get (int pos) {', ' return myData.get (pos);', ' }', ' ', ' public void replaceKey (int pos, KeyType keyToAdd) {', ' DataWrapper <KeyType, DataType> temp = myData.remove (pos);', ' DataWrapper <KeyType, DataType> newOne = new DataWrapper <KeyType, DataType> (keyToAdd, temp.getData ());', ' myData.add (pos, newOne);', ' }', ' ', ' public void add (KeyType keyToAdd, DataType dataToAdd) {', ' ', ' // if this is the first add, then set everyone up', ' if (myData == null) {', ' PointInMetricSpace myCentroid = keyToAdd.getPointInInterior ();', ' myBoundingSphere = new SphereABCD <PointInMetricSpace> (myCentroid, keyToAdd.maxDistanceTo (myCentroid));', ' myData = new ArrayList <DataWrapper <KeyType, DataType>> ();', ' ', ' // otherwise, extend the sphere if needed', ' } else {', ' myBoundingSphere.swallow (keyToAdd);', ' }', ' ', ' // add the data', ' myData.add (new DataWrapper <KeyType, DataType> (keyToAdd, dataToAdd));', ' }', ' ', ' // we want to potentially allow many implementations of the splitting lalgorithm', ' abstract public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // this is here so the actual splitting algorithn can access the list and change the sphere', ' protected ArrayList <DataWrapper <KeyType, DataType>> getList () {', ' return myData;', ' }', ' ', ' // this is here so the splitting algorithm can modify the list and the sphere', ' protected void replaceGuts (AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> withMe) {', ' myData = withMe.myData;', ' myBoundingSphere = withMe.myBoundingSphere;', ' }', ' ', '}', '', '// this is a particular implementation of the metric data list that uses a simple quadratic clustering', '// algorithm to perform a list split. It picks two "seeds" (the most distant objects) and then repeatedly', '// adds to the two new lists by choosing the objects closest to the seeds', 'class ChrisMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> extends AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> {', '', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo () {', ' ', ' // first, we need to find the two most distant points in the list', ' ArrayList <DataWrapper <KeyType, DataType>> myData = getList ();', ' int bestI = 0, bestJ = 0;', ' double maxDist = -1.0;', ' for (int i = 0; i < myData.size (); i++) {', ' for (int j = i + 1; j < myData.size (); j++) {', ' ', ' // get the two keys', ' DataWrapper <KeyType, DataType> pointOne = myData.get (i);', ' DataWrapper <KeyType, DataType> pointTwo = myData.get (j);', ' ', ' // find the difference between them', ' double curDist = pointOne.getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', '', ' // see if it is the biggest', ' if (curDist > maxDist) {', ' maxDist = curDist;', ' bestI = i;', ' bestJ = j;', ' }', ' }', ' }', ' ', ' // now, we have the best two points; those are seeds for the clustering', ' DataWrapper <KeyType, DataType> pointOne = myData.remove (bestI);', ' DataWrapper <KeyType, DataType> pointTwo = myData.remove (bestJ - 1);', ' ', ' // these are the two new lists', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listOne = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listTwo = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' ', ' // put the two seeds in', ' listOne.add (pointOne.getKey (), pointOne.getData ());', ' listTwo.add (pointTwo.getKey (), pointTwo.getData ());', ' ', ' // and add everyone else in', ' while (myData.size () != 0) {', ' ', ' // find the one closest to the first seed', ' int bestIndex = 0;', ' double bestDist = 9e99;', ' ', ' // loop thru all of the candidate data objects', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listOne.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' ', ' // break if no more data', ' if (myData.size () == 0)', ' break;', ' ', ' // loop thru all of the candidate data objects', ' bestDist = 9e99;', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listTwo.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' }', ' ', ' // now we replace our own guts with the first list', ' replaceGuts (listOne);', ' ', ' // and return the other list', ' return listTwo;', ' }', '}', '', 'interface IMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> {', ' ', ' // add a new pair to the list', ' public void add (KeyType keyToAdd, DataType dataToAdd);', ' ', ' // replace a key at the indicated position', ' public void replaceKey (int pos, KeyType keyToAdd);', ' ', ' // get the key, data pair that resides at a particular position', ' public DataWrapper <KeyType, DataType> get (int pos);', ' ', ' // return the number of items in the list', ' public int size ();', ' ', ' // split the list in two, using some clutering algorithm', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // get a sphere that totally bounds all of the objects in the list', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class MTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public MTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class SCMTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public SCMTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', '', 'public class MTreeTester extends TestCase {', ' ', ' // compare two lists of strings to see if the contents are the same', ' private boolean compareStringSets (ArrayList <String> setOne, ArrayList <String> setTwo) {', ' ', ' // sort the sets and make sure they are the same', ' boolean returnVal = true;', ' if (setOne.size () == setTwo.size ()) {', ' Collections.sort (setOne);', ' Collections.sort (setTwo);', ' for (int i = 0; i < setOne.size (); i++) {', ' if (!setOne.get (i).equals (setTwo.get (i))) {', ' returnVal = false;', ' break; ', ' }', ' }', ' } else {', ' returnVal = false;', ' }', ' ', ' // print out the result', ' System.out.println ("**** Expected:");', ' for (int i = 0; i < setOne.size (); i++) {', ' System.out.format (setOne.get (i) + " ");', ' }', ' System.out.println ("\\n**** Got:");', ' for (int i = 0; i < setTwo.size (); i++) {', ' System.out.format (setTwo.get (i) + " ");', ' }', ' System.out.println ("");', ' ', ' return returnVal;', ' }', ' ', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST SIMPLE ONE DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testOneDimRangeQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.find (query, expectedQuerySize / 2);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.find (query, expectedQuerySize / 2);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (numPoints);', ' result1 = myTree.find (query, expectedQuerySize);', ' result2 = hisTree.find (query, expectedQuerySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // like the last one, but runs a top k', ' private void testOneDimTopKQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (167);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.findKClosest (query, querySize);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (0);', ' result1 = myTree.findKClosest (query, querySize);', ' result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST MULTI-DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimRangeQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' double dist1 = 0;', ' double dist2 = 0;', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' dist1 = Math.sqrt (numDims) * expectedQuerySize / 2.0;', ' dist2 = Math.sqrt (numDims) * expectedQuerySize;', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' // do a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, (int) expectedQuerySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = myTree.findKClosest (query2, (int) expectedQuerySize);', ' ', ' // find the distance to the furthest point in both cases', ' for (int i = 0; i < (int) expectedQuerySize; i++) {', ' double newDist = result1.get (i).getKey ().getDistance (query1);', ' if (newDist > dist1)', ' dist1 = newDist;', ' newDist = result2.get (i).getKey ().getDistance (query2);', ' if (newDist > dist2)', ' dist2 = newDist;', ' }', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.find (query1, dist1);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.find (query1, dist1);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.find (query2, dist2);', ' result2 = hisTree.find (query2, dist2);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimTopKQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, querySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.findKClosest (query1, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.findKClosest (query2, querySize);', ' result2 = hisTree.findKClosest (query2, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' ', ' /**', ' * "TIER 1" TESTS', ' * NONE OF THESE REQUIRE ANY SPLITS', ' */', ' public void testEasy1() {', ' testOneDimRangeQuery (true, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy2() {', ' testOneDimRangeQuery (false, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy3() {', ' testOneDimRangeQuery (true, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy4() {', ' testOneDimRangeQuery (false, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy5() {', ' testMultiDimRangeQuery (true, 1, 5, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy6() {', ' testMultiDimRangeQuery (false, 1, 10, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy7() {', ' testMultiDimRangeQuery (true, 1, 5, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy8() {', ' testMultiDimRangeQuery (false, 1, 15, 10000, 10000, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 2" TESTS', ' * NONE OF THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testMod1() {', ' testOneDimRangeQuery (true, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod2() {', ' testOneDimRangeQuery (false, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod3() {', ' testOneDimRangeQuery (true, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod4() {', ' testOneDimRangeQuery (false, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod5() {', ' testMultiDimRangeQuery (true, 2, 5, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod6() {', ' testMultiDimRangeQuery (false, 2, 10, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod7() {', ' testMultiDimRangeQuery (true, 2, 5, 10000, 100, 1000, 10);', ' }', ' ', ' public void testMod8() {', ' testMultiDimRangeQuery (false, 2, 15, 10000, 100, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 3" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testHard1() {', ' testOneDimRangeQuery (true, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard2() {', ' testOneDimRangeQuery (false, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard3() {', ' testOneDimRangeQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard4() {', ' testOneDimRangeQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard5() {', ' testMultiDimRangeQuery (true, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard6() {', ' testMultiDimRangeQuery (false, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard7() {', ' testMultiDimRangeQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard8() {', ' testMultiDimRangeQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', ' ', ' /**', ' * "TIER 4" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE AND THEY TEST THE TOPK FUNCTIONALITY', ' */', ' ', ' public void testTopK1() {', ' testOneDimTopKQuery (true, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK2() {', ' testOneDimTopKQuery (false, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK3() {', ' testOneDimTopKQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK4() {', ' testOneDimTopKQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK5() {', ' testMultiDimTopKQuery (true, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK6() {', ' testMultiDimTopKQuery (false, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK7() {', ' testMultiDimTopKQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK8() {', ' testMultiDimTopKQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', '}'] | [{'reason_category': 'Loop Body', 'usage_line': 486}, {'reason_category': 'If Body', 'usage_line': 486}, {'reason_category': 'Loop Body', 'usage_line': 487}, {'reason_category': 'If Body', 'usage_line': 487}, {'reason_category': 'Loop Body', 'usage_line': 488}, {'reason_category': 'If Body', 'usage_line': 488}] | Variable 'newDist' used at line 486 is defined at line 484 and has a Short-Range dependency.
Variable 'bestDist' used at line 486 is defined at line 480 and has a Short-Range dependency.
Variable 'i' used at line 487 is defined at line 482 and has a Short-Range dependency.
Variable 'bestIndex' used at line 487 is defined at line 481 and has a Short-Range dependency. | {'Loop Body': 3, 'If Body': 3} | {'Variable Short-Range': 4} |
infilling_java | MTreeTester | 485 | 489 | ['import junit.framework.TestCase;', 'import java.util.ArrayList;', 'import java.util.Random;', 'import java.util.Collections;', '', '// this is a map from a set of keys of type PointInMetricSpace to a', '// set of data of type DataType', 'interface IMTree <Key extends IPointInMetricSpace <Key>, Data> {', ' ', ' // insert a new key/data pair into the map', ' void insert (Key keyToAdd, Data dataToAdd);', ' ', ' // find all of the key/data pairs in the map that fall within a', ' // particular distance of query point if no results are found, then', ' // an empty array is returned (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> find (Key query, double distance);', ' ', ' // find the k closest key/data pairs in the map to a particular', ' // query point ', ' //', ' // if the number of points in the map is less than k, then the', ' // returned list will have less than k pairs in it', ' //', ' // if the number of points is zero, then an empty array is returned', ' // (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> findKClosest (Key query, int k);', ' ', ' // returns the number of nodes that exist on a path from root to leaf in the tree...', ' // whtever the details of the implementation are, a tree with a single leaf node should return 1, and a tree', ' // with more than one lead node should return at least two (since it must have at least one internal node).', ' public int depth ();', ' ', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', '', 'interface IDoubleVector {', '', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '', '// this correponds to some geometric object in a metric space; the object is built out of', '// one or more points of type PointInMetricSpace', 'interface IObjectInMetricSpaceABCD <PointInMetricSpace extends IPointInMetricSpace<PointInMetricSpace>> {', ' ', ' // get the maximum distance from some point on the shape to a particular point in the metric space', ' double maxDistanceTo (PointInMetricSpace checkMe);', ' ', ' // return some arbitrary point on the interior of the geometric object', ' PointInMetricSpace getPointInInterior ();', '}', '', '', '// this interface corresponds to a point in some metric space', 'interface IPointInMetricSpace <PointInMetricSpace> {', ' ', ' // get the distance to another point', ' // ', ' // for this to work in an M-Tree, distances should be "metric" and', ' // obey the triangle inequality', ' double getDistance (PointInMetricSpace toMe);', '}', '', '// this is the basic node type in the structure', 'interface IMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> {', ' ', ' // insert a new key/data pair into the structure. The return value is a new MTreeNode if there was', ' // a split in response to the insertion, or a null if there was no split', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd);', ' ', ' // find all of the key/data pairs in the structure that fall within a particular query sphere', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query); ', ' ', ' // find the set of items closest to the given query point', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ);', ' ', ' // returns a sphere that totally encompasses everything in the node and its subtree', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', ' ', ' // returns the depth', ' public int depth ();', '}', '', '// this is a point in a particular metric space', 'class PointABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the point', ' private PointInMetricSpace me;', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return me; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return checkMe.getDistance (me); ', ' }', ' ', ' // contruct a point', ' public PointABCD (PointInMetricSpace useMe) {', ' me = useMe; ', ' }', '}', '', 'class PQueueABCD <PointInMetricSpace, DataType> {', ' ', ' // this is an object in the queue', ' private class Wrapper {', ' DataWrapper <PointInMetricSpace, DataType> myData;', ' double distance;', ' }', ' ', ' // this is the actual queue', ' ArrayList <Wrapper> myList;', ' ', ' // this is the largest distance value currently in the queue', ' double large;', ' ', ' // this is the max number of objects', ' int maxCount;', ' ', ' // create a priority queue with the speced number of slots', ' PQueueABCD (int maxCountIn) {', ' maxCount = maxCountIn;', ' myList = new ArrayList <Wrapper> ();', ' large = 9e99;', ' }', ' ', ' // get the largest distance in the queue', ' double getDist () {', ' return large;', ' }', ' ', ' // add a new object to the queue... the insertion is ignored if the distance value', ' // exceeds the largest that is in the queue and the queue is already full', ' void insert (PointInMetricSpace key, DataType data, double distance) {', ' ', ' // if we are full, remove the one with the largest distance', ' if (myList.size () == maxCount && distance < large) {', ' ', ' int badIndex = 0;', ' double maxDist = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > maxDist) {', ' maxDist = myList.get (i).distance;', ' badIndex = i;', ' }', ' }', ' ', ' myList.remove (badIndex);', ' }', ' ', ' // see if there is room', ' if (myList.size () < maxCount) {', ' ', ' // add it ', ' Wrapper newOne = new Wrapper ();', ' newOne.myData = new DataWrapper <PointInMetricSpace, DataType> (key, data);', ' newOne.distance = distance;', ' myList.add (newOne); ', ' }', ' ', ' // if we are full, reset the max distance', ' if (myList.size () == maxCount) {', ' large = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > large) {', ' large = myList.get (i).distance;', ' }', ' }', ' }', ' ', ' }', ' ', ' // extracts the contents of the queue', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> done () {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' for (int i = 0; i < myList.size (); i++) {', ' returnVal.add (myList.get (i).myData); ', ' }', ' ', ' return returnVal;', ' }', ' ', '}', '', '// this is a sphere in a particular metric space', 'class SphereABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the center of the sphere and its radius', ' private PointInMetricSpace center;', ' private double radius;', ' ', ' // build a sphere out of its center and its radius', ' public SphereABCD (PointInMetricSpace centerIn, double radiusIn) {', ' center = centerIn;', ' radius = radiusIn;', ' }', ' ', ' // increase the size of the sphere so it contains the object swallowMe', ' public void swallow (IObjectInMetricSpaceABCD <PointInMetricSpace> swallowMe) {', ' ', ' // see if we need to increase the radius to swallow this guy', ' double dist = swallowMe.maxDistanceTo (center);', ' if (dist > radius)', ' radius = dist;', ' }', ' ', ' // check to see if a sphere intersects another sphere', ' public boolean intersects (SphereABCD <PointInMetricSpace> me) {', ' return (me.center.getDistance (center) <= me.radius + radius);', ' }', ' ', ' // check to see if the sphere contains a point', ' public boolean contains (PointInMetricSpace checkMe) {', ' return (checkMe.getDistance (center) <= radius);', ' }', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return center; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return radius + checkMe.getDistance (center); ', ' }', '}', '', '', '', 'class OneDimPoint implements IPointInMetricSpace <OneDimPoint> {', ' ', ' // this is the actual double', ' Double value;', ' ', ' // construct this out of a double value', ' public OneDimPoint (double makeFromMe) {', ' value = new Double (makeFromMe);', ' }', ' ', ' // get the distance to another point', ' public double getDistance (OneDimPoint toMe) {', ' if (value > toMe.value)', ' return value - toMe.value;', ' else', ' return toMe.value - value;', ' }', ' ', '}', '', 'class MultiDimPoint implements IPointInMetricSpace <MultiDimPoint> {', ' ', ' // this is the point in a multidimensional space', ' IDoubleVector me;', ' ', ' // make this out of an IDoubleVector', ' public MultiDimPoint (IDoubleVector useMe) {', ' me = useMe;', ' }', ' ', ' // get the Euclidean distance to another point', ' public double getDistance (MultiDimPoint toMe) {', ' double distance = 0.0;', ' try {', ' for (int i = 0; i < me.getLength (); i++) {', ' double diff = me.getItem (i) - toMe.me.getItem (i);', ' diff *= diff;', ' distance += diff;', ' }', ' } catch (OutOfBoundsException e) {', ' throw new IndexOutOfBoundsException ("Can\'t compare two MultiDimPoint objects with different dimensionality!"); ', ' }', ' return Math.sqrt(distance);', ' }', ' ', '}', '// this is a leaf node', 'class LeafMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements ', ' IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myData;', ' ', ' // contructor that takes a data list and builds a node out of it', ' private LeafMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myDataIn) {', ' myData = myDataIn; ', ' }', ' ', ' // constructor that creates an empty node', ' public LeafMTreeNodeABCD () {', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> (); ', ' }', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // just add in the new data', ' myData.add (new PointABCD <PointInMetricSpace> (keyToAdd), dataToAdd);', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> newOne = myData.splitInTwo ();', ' LeafMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' myQ.insert (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData (), ', ' query.getDistance (myData.get (i).getKey ().getPointInInterior ()));', ' }', ' }', ' }', ' ', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' returnVal.add (new DataWrapper <PointInMetricSpace, DataType> (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData ()));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return 1; ', ' }', '', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', '// this silly little class is just a wrapper for a key, data pair', 'class DataWrapper <Key, Data> {', ' ', ' Key key;', ' Data data;', ' ', ' public DataWrapper (Key keyIn, Data dataIn) {', ' key = keyIn;', ' data = dataIn;', ' }', ' ', ' public Key getKey () {', ' return key;', ' }', ' ', ' public Data getData () {', ' return data;', ' }', '}', '', '', '// this is an internal node', 'class InternalMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType>', ' implements IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> myData;', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' // this constructs a new internal node that holds precisely the two nodes that are passed in', ' public InternalMTreeNodeABCD (IMTreeNodeABCD <PointInMetricSpace, DataType> refOne,', ' IMTreeNodeABCD <PointInMetricSpace, DataType> refTwo) {', ' ', ' // create a necw list and add the two guys in', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> ();', ' myData.add (refOne.getBoundingSphere (), refOne);', ' myData.add (refTwo.getBoundingSphere (), refTwo);', ' }', ' ', ' // this constructs a new node that holds the list of data that we were passed in', ' public InternalMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> useMe) {', ' myData = useMe; ', ' }', ' ', ' // from the interface', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // find the best child; this is the one we are closest to', ' double bestDist = 9e99;', ' int bestIndex = 0;', ' for (int i = 0; i < myData.size (); i++) {', ' ', ' double newDist = myData.get (i).getKey ().getPointInInterior ().getDistance (keyToAdd);'] | [' if (newDist < bestDist) {', ' bestDist = newDist;', ' bestIndex = i;', ' }', ' }'] | [' ', ' // do the recursive insert', ' IMTreeNodeABCD <PointInMetricSpace, DataType> newRef = myData.get (bestIndex).getData ().insert (keyToAdd, dataToAdd);', ' ', ' // if we got something back, then there was a split, so add the new node into our list', ' if (newRef != null) {', ' myData.add (newRef.getBoundingSphere (), newRef);', ' }', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> newOne = myData.splitInTwo ();', ' InternalMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.intersects (myData.get (i).getKey ())) {', ' myData.get (i).getData ().findKClosest (query, myQ);', ' }', ' }', ' }', ' ', ' // from the interface', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.intersects (myData.get (i).getKey ())) {', ' returnVal.addAll (myData.get (i).getData ().find (query));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return myData.get (0).getData ().depth () + 1; ', ' }', ' ', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', 'abstract class AMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> implements IMetricDataListABCD <PointInMetricSpace,KeyType, DataType> {', '', ' // this is the data that is actually stored in the list', ' private ArrayList <DataWrapper <KeyType, DataType>> myData;', ' ', ' // this is the sphere that bounds everything in the list', ' private SphereABCD <PointInMetricSpace> myBoundingSphere;', ' ', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myBoundingSphere; ', ' }', ' ', ' public int size () {', ' if (myData != null)', ' return myData.size (); ', ' else', ' return 0;', ' }', ' ', ' public DataWrapper <KeyType, DataType> get (int pos) {', ' return myData.get (pos);', ' }', ' ', ' public void replaceKey (int pos, KeyType keyToAdd) {', ' DataWrapper <KeyType, DataType> temp = myData.remove (pos);', ' DataWrapper <KeyType, DataType> newOne = new DataWrapper <KeyType, DataType> (keyToAdd, temp.getData ());', ' myData.add (pos, newOne);', ' }', ' ', ' public void add (KeyType keyToAdd, DataType dataToAdd) {', ' ', ' // if this is the first add, then set everyone up', ' if (myData == null) {', ' PointInMetricSpace myCentroid = keyToAdd.getPointInInterior ();', ' myBoundingSphere = new SphereABCD <PointInMetricSpace> (myCentroid, keyToAdd.maxDistanceTo (myCentroid));', ' myData = new ArrayList <DataWrapper <KeyType, DataType>> ();', ' ', ' // otherwise, extend the sphere if needed', ' } else {', ' myBoundingSphere.swallow (keyToAdd);', ' }', ' ', ' // add the data', ' myData.add (new DataWrapper <KeyType, DataType> (keyToAdd, dataToAdd));', ' }', ' ', ' // we want to potentially allow many implementations of the splitting lalgorithm', ' abstract public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // this is here so the actual splitting algorithn can access the list and change the sphere', ' protected ArrayList <DataWrapper <KeyType, DataType>> getList () {', ' return myData;', ' }', ' ', ' // this is here so the splitting algorithm can modify the list and the sphere', ' protected void replaceGuts (AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> withMe) {', ' myData = withMe.myData;', ' myBoundingSphere = withMe.myBoundingSphere;', ' }', ' ', '}', '', '// this is a particular implementation of the metric data list that uses a simple quadratic clustering', '// algorithm to perform a list split. It picks two "seeds" (the most distant objects) and then repeatedly', '// adds to the two new lists by choosing the objects closest to the seeds', 'class ChrisMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> extends AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> {', '', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo () {', ' ', ' // first, we need to find the two most distant points in the list', ' ArrayList <DataWrapper <KeyType, DataType>> myData = getList ();', ' int bestI = 0, bestJ = 0;', ' double maxDist = -1.0;', ' for (int i = 0; i < myData.size (); i++) {', ' for (int j = i + 1; j < myData.size (); j++) {', ' ', ' // get the two keys', ' DataWrapper <KeyType, DataType> pointOne = myData.get (i);', ' DataWrapper <KeyType, DataType> pointTwo = myData.get (j);', ' ', ' // find the difference between them', ' double curDist = pointOne.getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', '', ' // see if it is the biggest', ' if (curDist > maxDist) {', ' maxDist = curDist;', ' bestI = i;', ' bestJ = j;', ' }', ' }', ' }', ' ', ' // now, we have the best two points; those are seeds for the clustering', ' DataWrapper <KeyType, DataType> pointOne = myData.remove (bestI);', ' DataWrapper <KeyType, DataType> pointTwo = myData.remove (bestJ - 1);', ' ', ' // these are the two new lists', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listOne = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listTwo = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' ', ' // put the two seeds in', ' listOne.add (pointOne.getKey (), pointOne.getData ());', ' listTwo.add (pointTwo.getKey (), pointTwo.getData ());', ' ', ' // and add everyone else in', ' while (myData.size () != 0) {', ' ', ' // find the one closest to the first seed', ' int bestIndex = 0;', ' double bestDist = 9e99;', ' ', ' // loop thru all of the candidate data objects', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listOne.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' ', ' // break if no more data', ' if (myData.size () == 0)', ' break;', ' ', ' // loop thru all of the candidate data objects', ' bestDist = 9e99;', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listTwo.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' }', ' ', ' // now we replace our own guts with the first list', ' replaceGuts (listOne);', ' ', ' // and return the other list', ' return listTwo;', ' }', '}', '', 'interface IMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> {', ' ', ' // add a new pair to the list', ' public void add (KeyType keyToAdd, DataType dataToAdd);', ' ', ' // replace a key at the indicated position', ' public void replaceKey (int pos, KeyType keyToAdd);', ' ', ' // get the key, data pair that resides at a particular position', ' public DataWrapper <KeyType, DataType> get (int pos);', ' ', ' // return the number of items in the list', ' public int size ();', ' ', ' // split the list in two, using some clutering algorithm', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // get a sphere that totally bounds all of the objects in the list', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class MTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public MTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class SCMTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public SCMTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', '', 'public class MTreeTester extends TestCase {', ' ', ' // compare two lists of strings to see if the contents are the same', ' private boolean compareStringSets (ArrayList <String> setOne, ArrayList <String> setTwo) {', ' ', ' // sort the sets and make sure they are the same', ' boolean returnVal = true;', ' if (setOne.size () == setTwo.size ()) {', ' Collections.sort (setOne);', ' Collections.sort (setTwo);', ' for (int i = 0; i < setOne.size (); i++) {', ' if (!setOne.get (i).equals (setTwo.get (i))) {', ' returnVal = false;', ' break; ', ' }', ' }', ' } else {', ' returnVal = false;', ' }', ' ', ' // print out the result', ' System.out.println ("**** Expected:");', ' for (int i = 0; i < setOne.size (); i++) {', ' System.out.format (setOne.get (i) + " ");', ' }', ' System.out.println ("\\n**** Got:");', ' for (int i = 0; i < setTwo.size (); i++) {', ' System.out.format (setTwo.get (i) + " ");', ' }', ' System.out.println ("");', ' ', ' return returnVal;', ' }', ' ', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST SIMPLE ONE DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testOneDimRangeQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.find (query, expectedQuerySize / 2);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.find (query, expectedQuerySize / 2);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (numPoints);', ' result1 = myTree.find (query, expectedQuerySize);', ' result2 = hisTree.find (query, expectedQuerySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // like the last one, but runs a top k', ' private void testOneDimTopKQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (167);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.findKClosest (query, querySize);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (0);', ' result1 = myTree.findKClosest (query, querySize);', ' result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST MULTI-DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimRangeQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' double dist1 = 0;', ' double dist2 = 0;', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' dist1 = Math.sqrt (numDims) * expectedQuerySize / 2.0;', ' dist2 = Math.sqrt (numDims) * expectedQuerySize;', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' // do a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, (int) expectedQuerySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = myTree.findKClosest (query2, (int) expectedQuerySize);', ' ', ' // find the distance to the furthest point in both cases', ' for (int i = 0; i < (int) expectedQuerySize; i++) {', ' double newDist = result1.get (i).getKey ().getDistance (query1);', ' if (newDist > dist1)', ' dist1 = newDist;', ' newDist = result2.get (i).getKey ().getDistance (query2);', ' if (newDist > dist2)', ' dist2 = newDist;', ' }', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.find (query1, dist1);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.find (query1, dist1);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.find (query2, dist2);', ' result2 = hisTree.find (query2, dist2);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimTopKQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, querySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.findKClosest (query1, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.findKClosest (query2, querySize);', ' result2 = hisTree.findKClosest (query2, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' ', ' /**', ' * "TIER 1" TESTS', ' * NONE OF THESE REQUIRE ANY SPLITS', ' */', ' public void testEasy1() {', ' testOneDimRangeQuery (true, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy2() {', ' testOneDimRangeQuery (false, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy3() {', ' testOneDimRangeQuery (true, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy4() {', ' testOneDimRangeQuery (false, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy5() {', ' testMultiDimRangeQuery (true, 1, 5, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy6() {', ' testMultiDimRangeQuery (false, 1, 10, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy7() {', ' testMultiDimRangeQuery (true, 1, 5, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy8() {', ' testMultiDimRangeQuery (false, 1, 15, 10000, 10000, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 2" TESTS', ' * NONE OF THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testMod1() {', ' testOneDimRangeQuery (true, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod2() {', ' testOneDimRangeQuery (false, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod3() {', ' testOneDimRangeQuery (true, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod4() {', ' testOneDimRangeQuery (false, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod5() {', ' testMultiDimRangeQuery (true, 2, 5, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod6() {', ' testMultiDimRangeQuery (false, 2, 10, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod7() {', ' testMultiDimRangeQuery (true, 2, 5, 10000, 100, 1000, 10);', ' }', ' ', ' public void testMod8() {', ' testMultiDimRangeQuery (false, 2, 15, 10000, 100, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 3" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testHard1() {', ' testOneDimRangeQuery (true, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard2() {', ' testOneDimRangeQuery (false, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard3() {', ' testOneDimRangeQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard4() {', ' testOneDimRangeQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard5() {', ' testMultiDimRangeQuery (true, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard6() {', ' testMultiDimRangeQuery (false, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard7() {', ' testMultiDimRangeQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard8() {', ' testMultiDimRangeQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', ' ', ' /**', ' * "TIER 4" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE AND THEY TEST THE TOPK FUNCTIONALITY', ' */', ' ', ' public void testTopK1() {', ' testOneDimTopKQuery (true, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK2() {', ' testOneDimTopKQuery (false, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK3() {', ' testOneDimTopKQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK4() {', ' testOneDimTopKQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK5() {', ' testMultiDimTopKQuery (true, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK6() {', ' testMultiDimTopKQuery (false, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK7() {', ' testMultiDimTopKQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK8() {', ' testMultiDimTopKQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', '}'] | [{'reason_category': 'If Condition', 'usage_line': 485}, {'reason_category': 'Loop Body', 'usage_line': 485}, {'reason_category': 'Loop Body', 'usage_line': 486}, {'reason_category': 'If Body', 'usage_line': 486}, {'reason_category': 'Loop Body', 'usage_line': 487}, {'reason_category': 'If Body', 'usage_line': 487}, {'reason_category': 'Loop Body', 'usage_line': 488}, {'reason_category': 'If Body', 'usage_line': 488}, {'reason_category': 'Loop Body', 'usage_line': 489}] | Variable 'newDist' used at line 485 is defined at line 484 and has a Short-Range dependency.
Variable 'bestDist' used at line 485 is defined at line 480 and has a Short-Range dependency.
Variable 'newDist' used at line 486 is defined at line 484 and has a Short-Range dependency.
Variable 'bestDist' used at line 486 is defined at line 480 and has a Short-Range dependency.
Variable 'i' used at line 487 is defined at line 482 and has a Short-Range dependency.
Variable 'bestIndex' used at line 487 is defined at line 481 and has a Short-Range dependency. | {'If Condition': 1, 'Loop Body': 5, 'If Body': 3} | {'Variable Short-Range': 6} |
infilling_java | MTreeTester | 496 | 497 | ['import junit.framework.TestCase;', 'import java.util.ArrayList;', 'import java.util.Random;', 'import java.util.Collections;', '', '// this is a map from a set of keys of type PointInMetricSpace to a', '// set of data of type DataType', 'interface IMTree <Key extends IPointInMetricSpace <Key>, Data> {', ' ', ' // insert a new key/data pair into the map', ' void insert (Key keyToAdd, Data dataToAdd);', ' ', ' // find all of the key/data pairs in the map that fall within a', ' // particular distance of query point if no results are found, then', ' // an empty array is returned (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> find (Key query, double distance);', ' ', ' // find the k closest key/data pairs in the map to a particular', ' // query point ', ' //', ' // if the number of points in the map is less than k, then the', ' // returned list will have less than k pairs in it', ' //', ' // if the number of points is zero, then an empty array is returned', ' // (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> findKClosest (Key query, int k);', ' ', ' // returns the number of nodes that exist on a path from root to leaf in the tree...', ' // whtever the details of the implementation are, a tree with a single leaf node should return 1, and a tree', ' // with more than one lead node should return at least two (since it must have at least one internal node).', ' public int depth ();', ' ', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', '', 'interface IDoubleVector {', '', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '', '// this correponds to some geometric object in a metric space; the object is built out of', '// one or more points of type PointInMetricSpace', 'interface IObjectInMetricSpaceABCD <PointInMetricSpace extends IPointInMetricSpace<PointInMetricSpace>> {', ' ', ' // get the maximum distance from some point on the shape to a particular point in the metric space', ' double maxDistanceTo (PointInMetricSpace checkMe);', ' ', ' // return some arbitrary point on the interior of the geometric object', ' PointInMetricSpace getPointInInterior ();', '}', '', '', '// this interface corresponds to a point in some metric space', 'interface IPointInMetricSpace <PointInMetricSpace> {', ' ', ' // get the distance to another point', ' // ', ' // for this to work in an M-Tree, distances should be "metric" and', ' // obey the triangle inequality', ' double getDistance (PointInMetricSpace toMe);', '}', '', '// this is the basic node type in the structure', 'interface IMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> {', ' ', ' // insert a new key/data pair into the structure. The return value is a new MTreeNode if there was', ' // a split in response to the insertion, or a null if there was no split', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd);', ' ', ' // find all of the key/data pairs in the structure that fall within a particular query sphere', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query); ', ' ', ' // find the set of items closest to the given query point', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ);', ' ', ' // returns a sphere that totally encompasses everything in the node and its subtree', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', ' ', ' // returns the depth', ' public int depth ();', '}', '', '// this is a point in a particular metric space', 'class PointABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the point', ' private PointInMetricSpace me;', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return me; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return checkMe.getDistance (me); ', ' }', ' ', ' // contruct a point', ' public PointABCD (PointInMetricSpace useMe) {', ' me = useMe; ', ' }', '}', '', 'class PQueueABCD <PointInMetricSpace, DataType> {', ' ', ' // this is an object in the queue', ' private class Wrapper {', ' DataWrapper <PointInMetricSpace, DataType> myData;', ' double distance;', ' }', ' ', ' // this is the actual queue', ' ArrayList <Wrapper> myList;', ' ', ' // this is the largest distance value currently in the queue', ' double large;', ' ', ' // this is the max number of objects', ' int maxCount;', ' ', ' // create a priority queue with the speced number of slots', ' PQueueABCD (int maxCountIn) {', ' maxCount = maxCountIn;', ' myList = new ArrayList <Wrapper> ();', ' large = 9e99;', ' }', ' ', ' // get the largest distance in the queue', ' double getDist () {', ' return large;', ' }', ' ', ' // add a new object to the queue... the insertion is ignored if the distance value', ' // exceeds the largest that is in the queue and the queue is already full', ' void insert (PointInMetricSpace key, DataType data, double distance) {', ' ', ' // if we are full, remove the one with the largest distance', ' if (myList.size () == maxCount && distance < large) {', ' ', ' int badIndex = 0;', ' double maxDist = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > maxDist) {', ' maxDist = myList.get (i).distance;', ' badIndex = i;', ' }', ' }', ' ', ' myList.remove (badIndex);', ' }', ' ', ' // see if there is room', ' if (myList.size () < maxCount) {', ' ', ' // add it ', ' Wrapper newOne = new Wrapper ();', ' newOne.myData = new DataWrapper <PointInMetricSpace, DataType> (key, data);', ' newOne.distance = distance;', ' myList.add (newOne); ', ' }', ' ', ' // if we are full, reset the max distance', ' if (myList.size () == maxCount) {', ' large = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > large) {', ' large = myList.get (i).distance;', ' }', ' }', ' }', ' ', ' }', ' ', ' // extracts the contents of the queue', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> done () {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' for (int i = 0; i < myList.size (); i++) {', ' returnVal.add (myList.get (i).myData); ', ' }', ' ', ' return returnVal;', ' }', ' ', '}', '', '// this is a sphere in a particular metric space', 'class SphereABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the center of the sphere and its radius', ' private PointInMetricSpace center;', ' private double radius;', ' ', ' // build a sphere out of its center and its radius', ' public SphereABCD (PointInMetricSpace centerIn, double radiusIn) {', ' center = centerIn;', ' radius = radiusIn;', ' }', ' ', ' // increase the size of the sphere so it contains the object swallowMe', ' public void swallow (IObjectInMetricSpaceABCD <PointInMetricSpace> swallowMe) {', ' ', ' // see if we need to increase the radius to swallow this guy', ' double dist = swallowMe.maxDistanceTo (center);', ' if (dist > radius)', ' radius = dist;', ' }', ' ', ' // check to see if a sphere intersects another sphere', ' public boolean intersects (SphereABCD <PointInMetricSpace> me) {', ' return (me.center.getDistance (center) <= me.radius + radius);', ' }', ' ', ' // check to see if the sphere contains a point', ' public boolean contains (PointInMetricSpace checkMe) {', ' return (checkMe.getDistance (center) <= radius);', ' }', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return center; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return radius + checkMe.getDistance (center); ', ' }', '}', '', '', '', 'class OneDimPoint implements IPointInMetricSpace <OneDimPoint> {', ' ', ' // this is the actual double', ' Double value;', ' ', ' // construct this out of a double value', ' public OneDimPoint (double makeFromMe) {', ' value = new Double (makeFromMe);', ' }', ' ', ' // get the distance to another point', ' public double getDistance (OneDimPoint toMe) {', ' if (value > toMe.value)', ' return value - toMe.value;', ' else', ' return toMe.value - value;', ' }', ' ', '}', '', 'class MultiDimPoint implements IPointInMetricSpace <MultiDimPoint> {', ' ', ' // this is the point in a multidimensional space', ' IDoubleVector me;', ' ', ' // make this out of an IDoubleVector', ' public MultiDimPoint (IDoubleVector useMe) {', ' me = useMe;', ' }', ' ', ' // get the Euclidean distance to another point', ' public double getDistance (MultiDimPoint toMe) {', ' double distance = 0.0;', ' try {', ' for (int i = 0; i < me.getLength (); i++) {', ' double diff = me.getItem (i) - toMe.me.getItem (i);', ' diff *= diff;', ' distance += diff;', ' }', ' } catch (OutOfBoundsException e) {', ' throw new IndexOutOfBoundsException ("Can\'t compare two MultiDimPoint objects with different dimensionality!"); ', ' }', ' return Math.sqrt(distance);', ' }', ' ', '}', '// this is a leaf node', 'class LeafMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements ', ' IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myData;', ' ', ' // contructor that takes a data list and builds a node out of it', ' private LeafMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myDataIn) {', ' myData = myDataIn; ', ' }', ' ', ' // constructor that creates an empty node', ' public LeafMTreeNodeABCD () {', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> (); ', ' }', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // just add in the new data', ' myData.add (new PointABCD <PointInMetricSpace> (keyToAdd), dataToAdd);', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> newOne = myData.splitInTwo ();', ' LeafMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' myQ.insert (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData (), ', ' query.getDistance (myData.get (i).getKey ().getPointInInterior ()));', ' }', ' }', ' }', ' ', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' returnVal.add (new DataWrapper <PointInMetricSpace, DataType> (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData ()));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return 1; ', ' }', '', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', '// this silly little class is just a wrapper for a key, data pair', 'class DataWrapper <Key, Data> {', ' ', ' Key key;', ' Data data;', ' ', ' public DataWrapper (Key keyIn, Data dataIn) {', ' key = keyIn;', ' data = dataIn;', ' }', ' ', ' public Key getKey () {', ' return key;', ' }', ' ', ' public Data getData () {', ' return data;', ' }', '}', '', '', '// this is an internal node', 'class InternalMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType>', ' implements IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> myData;', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' // this constructs a new internal node that holds precisely the two nodes that are passed in', ' public InternalMTreeNodeABCD (IMTreeNodeABCD <PointInMetricSpace, DataType> refOne,', ' IMTreeNodeABCD <PointInMetricSpace, DataType> refTwo) {', ' ', ' // create a necw list and add the two guys in', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> ();', ' myData.add (refOne.getBoundingSphere (), refOne);', ' myData.add (refTwo.getBoundingSphere (), refTwo);', ' }', ' ', ' // this constructs a new node that holds the list of data that we were passed in', ' public InternalMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> useMe) {', ' myData = useMe; ', ' }', ' ', ' // from the interface', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // find the best child; this is the one we are closest to', ' double bestDist = 9e99;', ' int bestIndex = 0;', ' for (int i = 0; i < myData.size (); i++) {', ' ', ' double newDist = myData.get (i).getKey ().getPointInInterior ().getDistance (keyToAdd);', ' if (newDist < bestDist) {', ' bestDist = newDist;', ' bestIndex = i;', ' }', ' }', ' ', ' // do the recursive insert', ' IMTreeNodeABCD <PointInMetricSpace, DataType> newRef = myData.get (bestIndex).getData ().insert (keyToAdd, dataToAdd);', ' ', ' // if we got something back, then there was a split, so add the new node into our list', ' if (newRef != null) {'] | [' myData.add (newRef.getBoundingSphere (), newRef);', ' }'] | [' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> newOne = myData.splitInTwo ();', ' InternalMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.intersects (myData.get (i).getKey ())) {', ' myData.get (i).getData ().findKClosest (query, myQ);', ' }', ' }', ' }', ' ', ' // from the interface', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.intersects (myData.get (i).getKey ())) {', ' returnVal.addAll (myData.get (i).getData ().find (query));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return myData.get (0).getData ().depth () + 1; ', ' }', ' ', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', 'abstract class AMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> implements IMetricDataListABCD <PointInMetricSpace,KeyType, DataType> {', '', ' // this is the data that is actually stored in the list', ' private ArrayList <DataWrapper <KeyType, DataType>> myData;', ' ', ' // this is the sphere that bounds everything in the list', ' private SphereABCD <PointInMetricSpace> myBoundingSphere;', ' ', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myBoundingSphere; ', ' }', ' ', ' public int size () {', ' if (myData != null)', ' return myData.size (); ', ' else', ' return 0;', ' }', ' ', ' public DataWrapper <KeyType, DataType> get (int pos) {', ' return myData.get (pos);', ' }', ' ', ' public void replaceKey (int pos, KeyType keyToAdd) {', ' DataWrapper <KeyType, DataType> temp = myData.remove (pos);', ' DataWrapper <KeyType, DataType> newOne = new DataWrapper <KeyType, DataType> (keyToAdd, temp.getData ());', ' myData.add (pos, newOne);', ' }', ' ', ' public void add (KeyType keyToAdd, DataType dataToAdd) {', ' ', ' // if this is the first add, then set everyone up', ' if (myData == null) {', ' PointInMetricSpace myCentroid = keyToAdd.getPointInInterior ();', ' myBoundingSphere = new SphereABCD <PointInMetricSpace> (myCentroid, keyToAdd.maxDistanceTo (myCentroid));', ' myData = new ArrayList <DataWrapper <KeyType, DataType>> ();', ' ', ' // otherwise, extend the sphere if needed', ' } else {', ' myBoundingSphere.swallow (keyToAdd);', ' }', ' ', ' // add the data', ' myData.add (new DataWrapper <KeyType, DataType> (keyToAdd, dataToAdd));', ' }', ' ', ' // we want to potentially allow many implementations of the splitting lalgorithm', ' abstract public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // this is here so the actual splitting algorithn can access the list and change the sphere', ' protected ArrayList <DataWrapper <KeyType, DataType>> getList () {', ' return myData;', ' }', ' ', ' // this is here so the splitting algorithm can modify the list and the sphere', ' protected void replaceGuts (AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> withMe) {', ' myData = withMe.myData;', ' myBoundingSphere = withMe.myBoundingSphere;', ' }', ' ', '}', '', '// this is a particular implementation of the metric data list that uses a simple quadratic clustering', '// algorithm to perform a list split. It picks two "seeds" (the most distant objects) and then repeatedly', '// adds to the two new lists by choosing the objects closest to the seeds', 'class ChrisMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> extends AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> {', '', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo () {', ' ', ' // first, we need to find the two most distant points in the list', ' ArrayList <DataWrapper <KeyType, DataType>> myData = getList ();', ' int bestI = 0, bestJ = 0;', ' double maxDist = -1.0;', ' for (int i = 0; i < myData.size (); i++) {', ' for (int j = i + 1; j < myData.size (); j++) {', ' ', ' // get the two keys', ' DataWrapper <KeyType, DataType> pointOne = myData.get (i);', ' DataWrapper <KeyType, DataType> pointTwo = myData.get (j);', ' ', ' // find the difference between them', ' double curDist = pointOne.getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', '', ' // see if it is the biggest', ' if (curDist > maxDist) {', ' maxDist = curDist;', ' bestI = i;', ' bestJ = j;', ' }', ' }', ' }', ' ', ' // now, we have the best two points; those are seeds for the clustering', ' DataWrapper <KeyType, DataType> pointOne = myData.remove (bestI);', ' DataWrapper <KeyType, DataType> pointTwo = myData.remove (bestJ - 1);', ' ', ' // these are the two new lists', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listOne = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listTwo = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' ', ' // put the two seeds in', ' listOne.add (pointOne.getKey (), pointOne.getData ());', ' listTwo.add (pointTwo.getKey (), pointTwo.getData ());', ' ', ' // and add everyone else in', ' while (myData.size () != 0) {', ' ', ' // find the one closest to the first seed', ' int bestIndex = 0;', ' double bestDist = 9e99;', ' ', ' // loop thru all of the candidate data objects', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listOne.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' ', ' // break if no more data', ' if (myData.size () == 0)', ' break;', ' ', ' // loop thru all of the candidate data objects', ' bestDist = 9e99;', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listTwo.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' }', ' ', ' // now we replace our own guts with the first list', ' replaceGuts (listOne);', ' ', ' // and return the other list', ' return listTwo;', ' }', '}', '', 'interface IMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> {', ' ', ' // add a new pair to the list', ' public void add (KeyType keyToAdd, DataType dataToAdd);', ' ', ' // replace a key at the indicated position', ' public void replaceKey (int pos, KeyType keyToAdd);', ' ', ' // get the key, data pair that resides at a particular position', ' public DataWrapper <KeyType, DataType> get (int pos);', ' ', ' // return the number of items in the list', ' public int size ();', ' ', ' // split the list in two, using some clutering algorithm', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // get a sphere that totally bounds all of the objects in the list', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class MTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public MTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class SCMTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public SCMTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', '', 'public class MTreeTester extends TestCase {', ' ', ' // compare two lists of strings to see if the contents are the same', ' private boolean compareStringSets (ArrayList <String> setOne, ArrayList <String> setTwo) {', ' ', ' // sort the sets and make sure they are the same', ' boolean returnVal = true;', ' if (setOne.size () == setTwo.size ()) {', ' Collections.sort (setOne);', ' Collections.sort (setTwo);', ' for (int i = 0; i < setOne.size (); i++) {', ' if (!setOne.get (i).equals (setTwo.get (i))) {', ' returnVal = false;', ' break; ', ' }', ' }', ' } else {', ' returnVal = false;', ' }', ' ', ' // print out the result', ' System.out.println ("**** Expected:");', ' for (int i = 0; i < setOne.size (); i++) {', ' System.out.format (setOne.get (i) + " ");', ' }', ' System.out.println ("\\n**** Got:");', ' for (int i = 0; i < setTwo.size (); i++) {', ' System.out.format (setTwo.get (i) + " ");', ' }', ' System.out.println ("");', ' ', ' return returnVal;', ' }', ' ', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST SIMPLE ONE DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testOneDimRangeQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.find (query, expectedQuerySize / 2);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.find (query, expectedQuerySize / 2);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (numPoints);', ' result1 = myTree.find (query, expectedQuerySize);', ' result2 = hisTree.find (query, expectedQuerySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // like the last one, but runs a top k', ' private void testOneDimTopKQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (167);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.findKClosest (query, querySize);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (0);', ' result1 = myTree.findKClosest (query, querySize);', ' result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST MULTI-DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimRangeQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' double dist1 = 0;', ' double dist2 = 0;', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' dist1 = Math.sqrt (numDims) * expectedQuerySize / 2.0;', ' dist2 = Math.sqrt (numDims) * expectedQuerySize;', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' // do a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, (int) expectedQuerySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = myTree.findKClosest (query2, (int) expectedQuerySize);', ' ', ' // find the distance to the furthest point in both cases', ' for (int i = 0; i < (int) expectedQuerySize; i++) {', ' double newDist = result1.get (i).getKey ().getDistance (query1);', ' if (newDist > dist1)', ' dist1 = newDist;', ' newDist = result2.get (i).getKey ().getDistance (query2);', ' if (newDist > dist2)', ' dist2 = newDist;', ' }', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.find (query1, dist1);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.find (query1, dist1);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.find (query2, dist2);', ' result2 = hisTree.find (query2, dist2);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimTopKQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, querySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.findKClosest (query1, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.findKClosest (query2, querySize);', ' result2 = hisTree.findKClosest (query2, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' ', ' /**', ' * "TIER 1" TESTS', ' * NONE OF THESE REQUIRE ANY SPLITS', ' */', ' public void testEasy1() {', ' testOneDimRangeQuery (true, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy2() {', ' testOneDimRangeQuery (false, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy3() {', ' testOneDimRangeQuery (true, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy4() {', ' testOneDimRangeQuery (false, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy5() {', ' testMultiDimRangeQuery (true, 1, 5, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy6() {', ' testMultiDimRangeQuery (false, 1, 10, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy7() {', ' testMultiDimRangeQuery (true, 1, 5, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy8() {', ' testMultiDimRangeQuery (false, 1, 15, 10000, 10000, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 2" TESTS', ' * NONE OF THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testMod1() {', ' testOneDimRangeQuery (true, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod2() {', ' testOneDimRangeQuery (false, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod3() {', ' testOneDimRangeQuery (true, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod4() {', ' testOneDimRangeQuery (false, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod5() {', ' testMultiDimRangeQuery (true, 2, 5, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod6() {', ' testMultiDimRangeQuery (false, 2, 10, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod7() {', ' testMultiDimRangeQuery (true, 2, 5, 10000, 100, 1000, 10);', ' }', ' ', ' public void testMod8() {', ' testMultiDimRangeQuery (false, 2, 15, 10000, 100, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 3" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testHard1() {', ' testOneDimRangeQuery (true, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard2() {', ' testOneDimRangeQuery (false, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard3() {', ' testOneDimRangeQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard4() {', ' testOneDimRangeQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard5() {', ' testMultiDimRangeQuery (true, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard6() {', ' testMultiDimRangeQuery (false, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard7() {', ' testMultiDimRangeQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard8() {', ' testMultiDimRangeQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', ' ', ' /**', ' * "TIER 4" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE AND THEY TEST THE TOPK FUNCTIONALITY', ' */', ' ', ' public void testTopK1() {', ' testOneDimTopKQuery (true, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK2() {', ' testOneDimTopKQuery (false, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK3() {', ' testOneDimTopKQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK4() {', ' testOneDimTopKQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK5() {', ' testMultiDimTopKQuery (true, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK6() {', ' testMultiDimTopKQuery (false, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK7() {', ' testMultiDimTopKQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK8() {', ' testMultiDimTopKQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', '}'] | [{'reason_category': 'If Body', 'usage_line': 496}] | Global_Variable 'myData' used at line 496 is defined at line 454 and has a Long-Range dependency.
Variable 'newRef' used at line 496 is defined at line 492 and has a Short-Range dependency. | {'If Body': 1} | {'Global_Variable Long-Range': 1, 'Variable Short-Range': 1} |
infilling_java | MTreeTester | 501 | 504 | ['import junit.framework.TestCase;', 'import java.util.ArrayList;', 'import java.util.Random;', 'import java.util.Collections;', '', '// this is a map from a set of keys of type PointInMetricSpace to a', '// set of data of type DataType', 'interface IMTree <Key extends IPointInMetricSpace <Key>, Data> {', ' ', ' // insert a new key/data pair into the map', ' void insert (Key keyToAdd, Data dataToAdd);', ' ', ' // find all of the key/data pairs in the map that fall within a', ' // particular distance of query point if no results are found, then', ' // an empty array is returned (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> find (Key query, double distance);', ' ', ' // find the k closest key/data pairs in the map to a particular', ' // query point ', ' //', ' // if the number of points in the map is less than k, then the', ' // returned list will have less than k pairs in it', ' //', ' // if the number of points is zero, then an empty array is returned', ' // (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> findKClosest (Key query, int k);', ' ', ' // returns the number of nodes that exist on a path from root to leaf in the tree...', ' // whtever the details of the implementation are, a tree with a single leaf node should return 1, and a tree', ' // with more than one lead node should return at least two (since it must have at least one internal node).', ' public int depth ();', ' ', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', '', 'interface IDoubleVector {', '', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '', '// this correponds to some geometric object in a metric space; the object is built out of', '// one or more points of type PointInMetricSpace', 'interface IObjectInMetricSpaceABCD <PointInMetricSpace extends IPointInMetricSpace<PointInMetricSpace>> {', ' ', ' // get the maximum distance from some point on the shape to a particular point in the metric space', ' double maxDistanceTo (PointInMetricSpace checkMe);', ' ', ' // return some arbitrary point on the interior of the geometric object', ' PointInMetricSpace getPointInInterior ();', '}', '', '', '// this interface corresponds to a point in some metric space', 'interface IPointInMetricSpace <PointInMetricSpace> {', ' ', ' // get the distance to another point', ' // ', ' // for this to work in an M-Tree, distances should be "metric" and', ' // obey the triangle inequality', ' double getDistance (PointInMetricSpace toMe);', '}', '', '// this is the basic node type in the structure', 'interface IMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> {', ' ', ' // insert a new key/data pair into the structure. The return value is a new MTreeNode if there was', ' // a split in response to the insertion, or a null if there was no split', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd);', ' ', ' // find all of the key/data pairs in the structure that fall within a particular query sphere', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query); ', ' ', ' // find the set of items closest to the given query point', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ);', ' ', ' // returns a sphere that totally encompasses everything in the node and its subtree', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', ' ', ' // returns the depth', ' public int depth ();', '}', '', '// this is a point in a particular metric space', 'class PointABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the point', ' private PointInMetricSpace me;', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return me; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return checkMe.getDistance (me); ', ' }', ' ', ' // contruct a point', ' public PointABCD (PointInMetricSpace useMe) {', ' me = useMe; ', ' }', '}', '', 'class PQueueABCD <PointInMetricSpace, DataType> {', ' ', ' // this is an object in the queue', ' private class Wrapper {', ' DataWrapper <PointInMetricSpace, DataType> myData;', ' double distance;', ' }', ' ', ' // this is the actual queue', ' ArrayList <Wrapper> myList;', ' ', ' // this is the largest distance value currently in the queue', ' double large;', ' ', ' // this is the max number of objects', ' int maxCount;', ' ', ' // create a priority queue with the speced number of slots', ' PQueueABCD (int maxCountIn) {', ' maxCount = maxCountIn;', ' myList = new ArrayList <Wrapper> ();', ' large = 9e99;', ' }', ' ', ' // get the largest distance in the queue', ' double getDist () {', ' return large;', ' }', ' ', ' // add a new object to the queue... the insertion is ignored if the distance value', ' // exceeds the largest that is in the queue and the queue is already full', ' void insert (PointInMetricSpace key, DataType data, double distance) {', ' ', ' // if we are full, remove the one with the largest distance', ' if (myList.size () == maxCount && distance < large) {', ' ', ' int badIndex = 0;', ' double maxDist = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > maxDist) {', ' maxDist = myList.get (i).distance;', ' badIndex = i;', ' }', ' }', ' ', ' myList.remove (badIndex);', ' }', ' ', ' // see if there is room', ' if (myList.size () < maxCount) {', ' ', ' // add it ', ' Wrapper newOne = new Wrapper ();', ' newOne.myData = new DataWrapper <PointInMetricSpace, DataType> (key, data);', ' newOne.distance = distance;', ' myList.add (newOne); ', ' }', ' ', ' // if we are full, reset the max distance', ' if (myList.size () == maxCount) {', ' large = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > large) {', ' large = myList.get (i).distance;', ' }', ' }', ' }', ' ', ' }', ' ', ' // extracts the contents of the queue', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> done () {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' for (int i = 0; i < myList.size (); i++) {', ' returnVal.add (myList.get (i).myData); ', ' }', ' ', ' return returnVal;', ' }', ' ', '}', '', '// this is a sphere in a particular metric space', 'class SphereABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the center of the sphere and its radius', ' private PointInMetricSpace center;', ' private double radius;', ' ', ' // build a sphere out of its center and its radius', ' public SphereABCD (PointInMetricSpace centerIn, double radiusIn) {', ' center = centerIn;', ' radius = radiusIn;', ' }', ' ', ' // increase the size of the sphere so it contains the object swallowMe', ' public void swallow (IObjectInMetricSpaceABCD <PointInMetricSpace> swallowMe) {', ' ', ' // see if we need to increase the radius to swallow this guy', ' double dist = swallowMe.maxDistanceTo (center);', ' if (dist > radius)', ' radius = dist;', ' }', ' ', ' // check to see if a sphere intersects another sphere', ' public boolean intersects (SphereABCD <PointInMetricSpace> me) {', ' return (me.center.getDistance (center) <= me.radius + radius);', ' }', ' ', ' // check to see if the sphere contains a point', ' public boolean contains (PointInMetricSpace checkMe) {', ' return (checkMe.getDistance (center) <= radius);', ' }', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return center; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return radius + checkMe.getDistance (center); ', ' }', '}', '', '', '', 'class OneDimPoint implements IPointInMetricSpace <OneDimPoint> {', ' ', ' // this is the actual double', ' Double value;', ' ', ' // construct this out of a double value', ' public OneDimPoint (double makeFromMe) {', ' value = new Double (makeFromMe);', ' }', ' ', ' // get the distance to another point', ' public double getDistance (OneDimPoint toMe) {', ' if (value > toMe.value)', ' return value - toMe.value;', ' else', ' return toMe.value - value;', ' }', ' ', '}', '', 'class MultiDimPoint implements IPointInMetricSpace <MultiDimPoint> {', ' ', ' // this is the point in a multidimensional space', ' IDoubleVector me;', ' ', ' // make this out of an IDoubleVector', ' public MultiDimPoint (IDoubleVector useMe) {', ' me = useMe;', ' }', ' ', ' // get the Euclidean distance to another point', ' public double getDistance (MultiDimPoint toMe) {', ' double distance = 0.0;', ' try {', ' for (int i = 0; i < me.getLength (); i++) {', ' double diff = me.getItem (i) - toMe.me.getItem (i);', ' diff *= diff;', ' distance += diff;', ' }', ' } catch (OutOfBoundsException e) {', ' throw new IndexOutOfBoundsException ("Can\'t compare two MultiDimPoint objects with different dimensionality!"); ', ' }', ' return Math.sqrt(distance);', ' }', ' ', '}', '// this is a leaf node', 'class LeafMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements ', ' IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myData;', ' ', ' // contructor that takes a data list and builds a node out of it', ' private LeafMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myDataIn) {', ' myData = myDataIn; ', ' }', ' ', ' // constructor that creates an empty node', ' public LeafMTreeNodeABCD () {', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> (); ', ' }', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // just add in the new data', ' myData.add (new PointABCD <PointInMetricSpace> (keyToAdd), dataToAdd);', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> newOne = myData.splitInTwo ();', ' LeafMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' myQ.insert (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData (), ', ' query.getDistance (myData.get (i).getKey ().getPointInInterior ()));', ' }', ' }', ' }', ' ', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' returnVal.add (new DataWrapper <PointInMetricSpace, DataType> (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData ()));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return 1; ', ' }', '', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', '// this silly little class is just a wrapper for a key, data pair', 'class DataWrapper <Key, Data> {', ' ', ' Key key;', ' Data data;', ' ', ' public DataWrapper (Key keyIn, Data dataIn) {', ' key = keyIn;', ' data = dataIn;', ' }', ' ', ' public Key getKey () {', ' return key;', ' }', ' ', ' public Data getData () {', ' return data;', ' }', '}', '', '', '// this is an internal node', 'class InternalMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType>', ' implements IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> myData;', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' // this constructs a new internal node that holds precisely the two nodes that are passed in', ' public InternalMTreeNodeABCD (IMTreeNodeABCD <PointInMetricSpace, DataType> refOne,', ' IMTreeNodeABCD <PointInMetricSpace, DataType> refTwo) {', ' ', ' // create a necw list and add the two guys in', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> ();', ' myData.add (refOne.getBoundingSphere (), refOne);', ' myData.add (refTwo.getBoundingSphere (), refTwo);', ' }', ' ', ' // this constructs a new node that holds the list of data that we were passed in', ' public InternalMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> useMe) {', ' myData = useMe; ', ' }', ' ', ' // from the interface', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // find the best child; this is the one we are closest to', ' double bestDist = 9e99;', ' int bestIndex = 0;', ' for (int i = 0; i < myData.size (); i++) {', ' ', ' double newDist = myData.get (i).getKey ().getPointInInterior ().getDistance (keyToAdd);', ' if (newDist < bestDist) {', ' bestDist = newDist;', ' bestIndex = i;', ' }', ' }', ' ', ' // do the recursive insert', ' IMTreeNodeABCD <PointInMetricSpace, DataType> newRef = myData.get (bestIndex).getData ().insert (keyToAdd, dataToAdd);', ' ', ' // if we got something back, then there was a split, so add the new node into our list', ' if (newRef != null) {', ' myData.add (newRef.getBoundingSphere (), newRef);', ' }', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {'] | [' IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> newOne = myData.splitInTwo ();', ' InternalMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }'] | [' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.intersects (myData.get (i).getKey ())) {', ' myData.get (i).getData ().findKClosest (query, myQ);', ' }', ' }', ' }', ' ', ' // from the interface', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.intersects (myData.get (i).getKey ())) {', ' returnVal.addAll (myData.get (i).getData ().find (query));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return myData.get (0).getData ().depth () + 1; ', ' }', ' ', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', 'abstract class AMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> implements IMetricDataListABCD <PointInMetricSpace,KeyType, DataType> {', '', ' // this is the data that is actually stored in the list', ' private ArrayList <DataWrapper <KeyType, DataType>> myData;', ' ', ' // this is the sphere that bounds everything in the list', ' private SphereABCD <PointInMetricSpace> myBoundingSphere;', ' ', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myBoundingSphere; ', ' }', ' ', ' public int size () {', ' if (myData != null)', ' return myData.size (); ', ' else', ' return 0;', ' }', ' ', ' public DataWrapper <KeyType, DataType> get (int pos) {', ' return myData.get (pos);', ' }', ' ', ' public void replaceKey (int pos, KeyType keyToAdd) {', ' DataWrapper <KeyType, DataType> temp = myData.remove (pos);', ' DataWrapper <KeyType, DataType> newOne = new DataWrapper <KeyType, DataType> (keyToAdd, temp.getData ());', ' myData.add (pos, newOne);', ' }', ' ', ' public void add (KeyType keyToAdd, DataType dataToAdd) {', ' ', ' // if this is the first add, then set everyone up', ' if (myData == null) {', ' PointInMetricSpace myCentroid = keyToAdd.getPointInInterior ();', ' myBoundingSphere = new SphereABCD <PointInMetricSpace> (myCentroid, keyToAdd.maxDistanceTo (myCentroid));', ' myData = new ArrayList <DataWrapper <KeyType, DataType>> ();', ' ', ' // otherwise, extend the sphere if needed', ' } else {', ' myBoundingSphere.swallow (keyToAdd);', ' }', ' ', ' // add the data', ' myData.add (new DataWrapper <KeyType, DataType> (keyToAdd, dataToAdd));', ' }', ' ', ' // we want to potentially allow many implementations of the splitting lalgorithm', ' abstract public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // this is here so the actual splitting algorithn can access the list and change the sphere', ' protected ArrayList <DataWrapper <KeyType, DataType>> getList () {', ' return myData;', ' }', ' ', ' // this is here so the splitting algorithm can modify the list and the sphere', ' protected void replaceGuts (AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> withMe) {', ' myData = withMe.myData;', ' myBoundingSphere = withMe.myBoundingSphere;', ' }', ' ', '}', '', '// this is a particular implementation of the metric data list that uses a simple quadratic clustering', '// algorithm to perform a list split. It picks two "seeds" (the most distant objects) and then repeatedly', '// adds to the two new lists by choosing the objects closest to the seeds', 'class ChrisMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> extends AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> {', '', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo () {', ' ', ' // first, we need to find the two most distant points in the list', ' ArrayList <DataWrapper <KeyType, DataType>> myData = getList ();', ' int bestI = 0, bestJ = 0;', ' double maxDist = -1.0;', ' for (int i = 0; i < myData.size (); i++) {', ' for (int j = i + 1; j < myData.size (); j++) {', ' ', ' // get the two keys', ' DataWrapper <KeyType, DataType> pointOne = myData.get (i);', ' DataWrapper <KeyType, DataType> pointTwo = myData.get (j);', ' ', ' // find the difference between them', ' double curDist = pointOne.getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', '', ' // see if it is the biggest', ' if (curDist > maxDist) {', ' maxDist = curDist;', ' bestI = i;', ' bestJ = j;', ' }', ' }', ' }', ' ', ' // now, we have the best two points; those are seeds for the clustering', ' DataWrapper <KeyType, DataType> pointOne = myData.remove (bestI);', ' DataWrapper <KeyType, DataType> pointTwo = myData.remove (bestJ - 1);', ' ', ' // these are the two new lists', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listOne = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listTwo = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' ', ' // put the two seeds in', ' listOne.add (pointOne.getKey (), pointOne.getData ());', ' listTwo.add (pointTwo.getKey (), pointTwo.getData ());', ' ', ' // and add everyone else in', ' while (myData.size () != 0) {', ' ', ' // find the one closest to the first seed', ' int bestIndex = 0;', ' double bestDist = 9e99;', ' ', ' // loop thru all of the candidate data objects', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listOne.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' ', ' // break if no more data', ' if (myData.size () == 0)', ' break;', ' ', ' // loop thru all of the candidate data objects', ' bestDist = 9e99;', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listTwo.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' }', ' ', ' // now we replace our own guts with the first list', ' replaceGuts (listOne);', ' ', ' // and return the other list', ' return listTwo;', ' }', '}', '', 'interface IMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> {', ' ', ' // add a new pair to the list', ' public void add (KeyType keyToAdd, DataType dataToAdd);', ' ', ' // replace a key at the indicated position', ' public void replaceKey (int pos, KeyType keyToAdd);', ' ', ' // get the key, data pair that resides at a particular position', ' public DataWrapper <KeyType, DataType> get (int pos);', ' ', ' // return the number of items in the list', ' public int size ();', ' ', ' // split the list in two, using some clutering algorithm', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // get a sphere that totally bounds all of the objects in the list', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class MTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public MTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class SCMTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public SCMTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', '', 'public class MTreeTester extends TestCase {', ' ', ' // compare two lists of strings to see if the contents are the same', ' private boolean compareStringSets (ArrayList <String> setOne, ArrayList <String> setTwo) {', ' ', ' // sort the sets and make sure they are the same', ' boolean returnVal = true;', ' if (setOne.size () == setTwo.size ()) {', ' Collections.sort (setOne);', ' Collections.sort (setTwo);', ' for (int i = 0; i < setOne.size (); i++) {', ' if (!setOne.get (i).equals (setTwo.get (i))) {', ' returnVal = false;', ' break; ', ' }', ' }', ' } else {', ' returnVal = false;', ' }', ' ', ' // print out the result', ' System.out.println ("**** Expected:");', ' for (int i = 0; i < setOne.size (); i++) {', ' System.out.format (setOne.get (i) + " ");', ' }', ' System.out.println ("\\n**** Got:");', ' for (int i = 0; i < setTwo.size (); i++) {', ' System.out.format (setTwo.get (i) + " ");', ' }', ' System.out.println ("");', ' ', ' return returnVal;', ' }', ' ', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST SIMPLE ONE DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testOneDimRangeQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.find (query, expectedQuerySize / 2);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.find (query, expectedQuerySize / 2);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (numPoints);', ' result1 = myTree.find (query, expectedQuerySize);', ' result2 = hisTree.find (query, expectedQuerySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // like the last one, but runs a top k', ' private void testOneDimTopKQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (167);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.findKClosest (query, querySize);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (0);', ' result1 = myTree.findKClosest (query, querySize);', ' result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST MULTI-DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimRangeQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' double dist1 = 0;', ' double dist2 = 0;', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' dist1 = Math.sqrt (numDims) * expectedQuerySize / 2.0;', ' dist2 = Math.sqrt (numDims) * expectedQuerySize;', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' // do a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, (int) expectedQuerySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = myTree.findKClosest (query2, (int) expectedQuerySize);', ' ', ' // find the distance to the furthest point in both cases', ' for (int i = 0; i < (int) expectedQuerySize; i++) {', ' double newDist = result1.get (i).getKey ().getDistance (query1);', ' if (newDist > dist1)', ' dist1 = newDist;', ' newDist = result2.get (i).getKey ().getDistance (query2);', ' if (newDist > dist2)', ' dist2 = newDist;', ' }', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.find (query1, dist1);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.find (query1, dist1);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.find (query2, dist2);', ' result2 = hisTree.find (query2, dist2);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimTopKQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, querySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.findKClosest (query1, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.findKClosest (query2, querySize);', ' result2 = hisTree.findKClosest (query2, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' ', ' /**', ' * "TIER 1" TESTS', ' * NONE OF THESE REQUIRE ANY SPLITS', ' */', ' public void testEasy1() {', ' testOneDimRangeQuery (true, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy2() {', ' testOneDimRangeQuery (false, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy3() {', ' testOneDimRangeQuery (true, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy4() {', ' testOneDimRangeQuery (false, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy5() {', ' testMultiDimRangeQuery (true, 1, 5, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy6() {', ' testMultiDimRangeQuery (false, 1, 10, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy7() {', ' testMultiDimRangeQuery (true, 1, 5, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy8() {', ' testMultiDimRangeQuery (false, 1, 15, 10000, 10000, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 2" TESTS', ' * NONE OF THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testMod1() {', ' testOneDimRangeQuery (true, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod2() {', ' testOneDimRangeQuery (false, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod3() {', ' testOneDimRangeQuery (true, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod4() {', ' testOneDimRangeQuery (false, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod5() {', ' testMultiDimRangeQuery (true, 2, 5, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod6() {', ' testMultiDimRangeQuery (false, 2, 10, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod7() {', ' testMultiDimRangeQuery (true, 2, 5, 10000, 100, 1000, 10);', ' }', ' ', ' public void testMod8() {', ' testMultiDimRangeQuery (false, 2, 15, 10000, 100, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 3" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testHard1() {', ' testOneDimRangeQuery (true, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard2() {', ' testOneDimRangeQuery (false, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard3() {', ' testOneDimRangeQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard4() {', ' testOneDimRangeQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard5() {', ' testMultiDimRangeQuery (true, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard6() {', ' testMultiDimRangeQuery (false, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard7() {', ' testMultiDimRangeQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard8() {', ' testMultiDimRangeQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', ' ', ' /**', ' * "TIER 4" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE AND THEY TEST THE TOPK FUNCTIONALITY', ' */', ' ', ' public void testTopK1() {', ' testOneDimTopKQuery (true, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK2() {', ' testOneDimTopKQuery (false, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK3() {', ' testOneDimTopKQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK4() {', ' testOneDimTopKQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK5() {', ' testMultiDimTopKQuery (true, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK6() {', ' testMultiDimTopKQuery (false, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK7() {', ' testMultiDimTopKQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK8() {', ' testMultiDimTopKQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', '}'] | [{'reason_category': 'If Body', 'usage_line': 501}, {'reason_category': 'If Body', 'usage_line': 502}, {'reason_category': 'If Body', 'usage_line': 503}, {'reason_category': 'If Body', 'usage_line': 504}] | Class 'SphereABCD' used at line 501 is defined at line 261 and has a Long-Range dependency.
Global_Variable 'myData' used at line 501 is defined at line 454 and has a Long-Range dependency.
Class 'InternalMTreeNodeABCD' used at line 502 is defined at line 450 and has a Long-Range dependency.
Variable 'newOne' used at line 502 is defined at line 501 and has a Short-Range dependency.
Variable 'returnVal' used at line 503 is defined at line 502 and has a Short-Range dependency. | {'If Body': 4} | {'Class Long-Range': 2, 'Global_Variable Long-Range': 1, 'Variable Short-Range': 2} |
infilling_java | MTreeTester | 514 | 515 | ['import junit.framework.TestCase;', 'import java.util.ArrayList;', 'import java.util.Random;', 'import java.util.Collections;', '', '// this is a map from a set of keys of type PointInMetricSpace to a', '// set of data of type DataType', 'interface IMTree <Key extends IPointInMetricSpace <Key>, Data> {', ' ', ' // insert a new key/data pair into the map', ' void insert (Key keyToAdd, Data dataToAdd);', ' ', ' // find all of the key/data pairs in the map that fall within a', ' // particular distance of query point if no results are found, then', ' // an empty array is returned (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> find (Key query, double distance);', ' ', ' // find the k closest key/data pairs in the map to a particular', ' // query point ', ' //', ' // if the number of points in the map is less than k, then the', ' // returned list will have less than k pairs in it', ' //', ' // if the number of points is zero, then an empty array is returned', ' // (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> findKClosest (Key query, int k);', ' ', ' // returns the number of nodes that exist on a path from root to leaf in the tree...', ' // whtever the details of the implementation are, a tree with a single leaf node should return 1, and a tree', ' // with more than one lead node should return at least two (since it must have at least one internal node).', ' public int depth ();', ' ', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', '', 'interface IDoubleVector {', '', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '', '// this correponds to some geometric object in a metric space; the object is built out of', '// one or more points of type PointInMetricSpace', 'interface IObjectInMetricSpaceABCD <PointInMetricSpace extends IPointInMetricSpace<PointInMetricSpace>> {', ' ', ' // get the maximum distance from some point on the shape to a particular point in the metric space', ' double maxDistanceTo (PointInMetricSpace checkMe);', ' ', ' // return some arbitrary point on the interior of the geometric object', ' PointInMetricSpace getPointInInterior ();', '}', '', '', '// this interface corresponds to a point in some metric space', 'interface IPointInMetricSpace <PointInMetricSpace> {', ' ', ' // get the distance to another point', ' // ', ' // for this to work in an M-Tree, distances should be "metric" and', ' // obey the triangle inequality', ' double getDistance (PointInMetricSpace toMe);', '}', '', '// this is the basic node type in the structure', 'interface IMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> {', ' ', ' // insert a new key/data pair into the structure. The return value is a new MTreeNode if there was', ' // a split in response to the insertion, or a null if there was no split', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd);', ' ', ' // find all of the key/data pairs in the structure that fall within a particular query sphere', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query); ', ' ', ' // find the set of items closest to the given query point', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ);', ' ', ' // returns a sphere that totally encompasses everything in the node and its subtree', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', ' ', ' // returns the depth', ' public int depth ();', '}', '', '// this is a point in a particular metric space', 'class PointABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the point', ' private PointInMetricSpace me;', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return me; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return checkMe.getDistance (me); ', ' }', ' ', ' // contruct a point', ' public PointABCD (PointInMetricSpace useMe) {', ' me = useMe; ', ' }', '}', '', 'class PQueueABCD <PointInMetricSpace, DataType> {', ' ', ' // this is an object in the queue', ' private class Wrapper {', ' DataWrapper <PointInMetricSpace, DataType> myData;', ' double distance;', ' }', ' ', ' // this is the actual queue', ' ArrayList <Wrapper> myList;', ' ', ' // this is the largest distance value currently in the queue', ' double large;', ' ', ' // this is the max number of objects', ' int maxCount;', ' ', ' // create a priority queue with the speced number of slots', ' PQueueABCD (int maxCountIn) {', ' maxCount = maxCountIn;', ' myList = new ArrayList <Wrapper> ();', ' large = 9e99;', ' }', ' ', ' // get the largest distance in the queue', ' double getDist () {', ' return large;', ' }', ' ', ' // add a new object to the queue... the insertion is ignored if the distance value', ' // exceeds the largest that is in the queue and the queue is already full', ' void insert (PointInMetricSpace key, DataType data, double distance) {', ' ', ' // if we are full, remove the one with the largest distance', ' if (myList.size () == maxCount && distance < large) {', ' ', ' int badIndex = 0;', ' double maxDist = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > maxDist) {', ' maxDist = myList.get (i).distance;', ' badIndex = i;', ' }', ' }', ' ', ' myList.remove (badIndex);', ' }', ' ', ' // see if there is room', ' if (myList.size () < maxCount) {', ' ', ' // add it ', ' Wrapper newOne = new Wrapper ();', ' newOne.myData = new DataWrapper <PointInMetricSpace, DataType> (key, data);', ' newOne.distance = distance;', ' myList.add (newOne); ', ' }', ' ', ' // if we are full, reset the max distance', ' if (myList.size () == maxCount) {', ' large = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > large) {', ' large = myList.get (i).distance;', ' }', ' }', ' }', ' ', ' }', ' ', ' // extracts the contents of the queue', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> done () {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' for (int i = 0; i < myList.size (); i++) {', ' returnVal.add (myList.get (i).myData); ', ' }', ' ', ' return returnVal;', ' }', ' ', '}', '', '// this is a sphere in a particular metric space', 'class SphereABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the center of the sphere and its radius', ' private PointInMetricSpace center;', ' private double radius;', ' ', ' // build a sphere out of its center and its radius', ' public SphereABCD (PointInMetricSpace centerIn, double radiusIn) {', ' center = centerIn;', ' radius = radiusIn;', ' }', ' ', ' // increase the size of the sphere so it contains the object swallowMe', ' public void swallow (IObjectInMetricSpaceABCD <PointInMetricSpace> swallowMe) {', ' ', ' // see if we need to increase the radius to swallow this guy', ' double dist = swallowMe.maxDistanceTo (center);', ' if (dist > radius)', ' radius = dist;', ' }', ' ', ' // check to see if a sphere intersects another sphere', ' public boolean intersects (SphereABCD <PointInMetricSpace> me) {', ' return (me.center.getDistance (center) <= me.radius + radius);', ' }', ' ', ' // check to see if the sphere contains a point', ' public boolean contains (PointInMetricSpace checkMe) {', ' return (checkMe.getDistance (center) <= radius);', ' }', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return center; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return radius + checkMe.getDistance (center); ', ' }', '}', '', '', '', 'class OneDimPoint implements IPointInMetricSpace <OneDimPoint> {', ' ', ' // this is the actual double', ' Double value;', ' ', ' // construct this out of a double value', ' public OneDimPoint (double makeFromMe) {', ' value = new Double (makeFromMe);', ' }', ' ', ' // get the distance to another point', ' public double getDistance (OneDimPoint toMe) {', ' if (value > toMe.value)', ' return value - toMe.value;', ' else', ' return toMe.value - value;', ' }', ' ', '}', '', 'class MultiDimPoint implements IPointInMetricSpace <MultiDimPoint> {', ' ', ' // this is the point in a multidimensional space', ' IDoubleVector me;', ' ', ' // make this out of an IDoubleVector', ' public MultiDimPoint (IDoubleVector useMe) {', ' me = useMe;', ' }', ' ', ' // get the Euclidean distance to another point', ' public double getDistance (MultiDimPoint toMe) {', ' double distance = 0.0;', ' try {', ' for (int i = 0; i < me.getLength (); i++) {', ' double diff = me.getItem (i) - toMe.me.getItem (i);', ' diff *= diff;', ' distance += diff;', ' }', ' } catch (OutOfBoundsException e) {', ' throw new IndexOutOfBoundsException ("Can\'t compare two MultiDimPoint objects with different dimensionality!"); ', ' }', ' return Math.sqrt(distance);', ' }', ' ', '}', '// this is a leaf node', 'class LeafMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements ', ' IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myData;', ' ', ' // contructor that takes a data list and builds a node out of it', ' private LeafMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myDataIn) {', ' myData = myDataIn; ', ' }', ' ', ' // constructor that creates an empty node', ' public LeafMTreeNodeABCD () {', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> (); ', ' }', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // just add in the new data', ' myData.add (new PointABCD <PointInMetricSpace> (keyToAdd), dataToAdd);', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> newOne = myData.splitInTwo ();', ' LeafMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' myQ.insert (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData (), ', ' query.getDistance (myData.get (i).getKey ().getPointInInterior ()));', ' }', ' }', ' }', ' ', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' returnVal.add (new DataWrapper <PointInMetricSpace, DataType> (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData ()));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return 1; ', ' }', '', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', '// this silly little class is just a wrapper for a key, data pair', 'class DataWrapper <Key, Data> {', ' ', ' Key key;', ' Data data;', ' ', ' public DataWrapper (Key keyIn, Data dataIn) {', ' key = keyIn;', ' data = dataIn;', ' }', ' ', ' public Key getKey () {', ' return key;', ' }', ' ', ' public Data getData () {', ' return data;', ' }', '}', '', '', '// this is an internal node', 'class InternalMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType>', ' implements IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> myData;', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' // this constructs a new internal node that holds precisely the two nodes that are passed in', ' public InternalMTreeNodeABCD (IMTreeNodeABCD <PointInMetricSpace, DataType> refOne,', ' IMTreeNodeABCD <PointInMetricSpace, DataType> refTwo) {', ' ', ' // create a necw list and add the two guys in', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> ();', ' myData.add (refOne.getBoundingSphere (), refOne);', ' myData.add (refTwo.getBoundingSphere (), refTwo);', ' }', ' ', ' // this constructs a new node that holds the list of data that we were passed in', ' public InternalMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> useMe) {', ' myData = useMe; ', ' }', ' ', ' // from the interface', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // find the best child; this is the one we are closest to', ' double bestDist = 9e99;', ' int bestIndex = 0;', ' for (int i = 0; i < myData.size (); i++) {', ' ', ' double newDist = myData.get (i).getKey ().getPointInInterior ().getDistance (keyToAdd);', ' if (newDist < bestDist) {', ' bestDist = newDist;', ' bestIndex = i;', ' }', ' }', ' ', ' // do the recursive insert', ' IMTreeNodeABCD <PointInMetricSpace, DataType> newRef = myData.get (bestIndex).getData ().insert (keyToAdd, dataToAdd);', ' ', ' // if we got something back, then there was a split, so add the new node into our list', ' if (newRef != null) {', ' myData.add (newRef.getBoundingSphere (), newRef);', ' }', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> newOne = myData.splitInTwo ();', ' InternalMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.intersects (myData.get (i).getKey ())) {'] | [' myData.get (i).getData ().findKClosest (query, myQ);', ' }'] | [' }', ' }', ' ', ' // from the interface', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.intersects (myData.get (i).getKey ())) {', ' returnVal.addAll (myData.get (i).getData ().find (query));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return myData.get (0).getData ().depth () + 1; ', ' }', ' ', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', 'abstract class AMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> implements IMetricDataListABCD <PointInMetricSpace,KeyType, DataType> {', '', ' // this is the data that is actually stored in the list', ' private ArrayList <DataWrapper <KeyType, DataType>> myData;', ' ', ' // this is the sphere that bounds everything in the list', ' private SphereABCD <PointInMetricSpace> myBoundingSphere;', ' ', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myBoundingSphere; ', ' }', ' ', ' public int size () {', ' if (myData != null)', ' return myData.size (); ', ' else', ' return 0;', ' }', ' ', ' public DataWrapper <KeyType, DataType> get (int pos) {', ' return myData.get (pos);', ' }', ' ', ' public void replaceKey (int pos, KeyType keyToAdd) {', ' DataWrapper <KeyType, DataType> temp = myData.remove (pos);', ' DataWrapper <KeyType, DataType> newOne = new DataWrapper <KeyType, DataType> (keyToAdd, temp.getData ());', ' myData.add (pos, newOne);', ' }', ' ', ' public void add (KeyType keyToAdd, DataType dataToAdd) {', ' ', ' // if this is the first add, then set everyone up', ' if (myData == null) {', ' PointInMetricSpace myCentroid = keyToAdd.getPointInInterior ();', ' myBoundingSphere = new SphereABCD <PointInMetricSpace> (myCentroid, keyToAdd.maxDistanceTo (myCentroid));', ' myData = new ArrayList <DataWrapper <KeyType, DataType>> ();', ' ', ' // otherwise, extend the sphere if needed', ' } else {', ' myBoundingSphere.swallow (keyToAdd);', ' }', ' ', ' // add the data', ' myData.add (new DataWrapper <KeyType, DataType> (keyToAdd, dataToAdd));', ' }', ' ', ' // we want to potentially allow many implementations of the splitting lalgorithm', ' abstract public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // this is here so the actual splitting algorithn can access the list and change the sphere', ' protected ArrayList <DataWrapper <KeyType, DataType>> getList () {', ' return myData;', ' }', ' ', ' // this is here so the splitting algorithm can modify the list and the sphere', ' protected void replaceGuts (AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> withMe) {', ' myData = withMe.myData;', ' myBoundingSphere = withMe.myBoundingSphere;', ' }', ' ', '}', '', '// this is a particular implementation of the metric data list that uses a simple quadratic clustering', '// algorithm to perform a list split. It picks two "seeds" (the most distant objects) and then repeatedly', '// adds to the two new lists by choosing the objects closest to the seeds', 'class ChrisMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> extends AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> {', '', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo () {', ' ', ' // first, we need to find the two most distant points in the list', ' ArrayList <DataWrapper <KeyType, DataType>> myData = getList ();', ' int bestI = 0, bestJ = 0;', ' double maxDist = -1.0;', ' for (int i = 0; i < myData.size (); i++) {', ' for (int j = i + 1; j < myData.size (); j++) {', ' ', ' // get the two keys', ' DataWrapper <KeyType, DataType> pointOne = myData.get (i);', ' DataWrapper <KeyType, DataType> pointTwo = myData.get (j);', ' ', ' // find the difference between them', ' double curDist = pointOne.getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', '', ' // see if it is the biggest', ' if (curDist > maxDist) {', ' maxDist = curDist;', ' bestI = i;', ' bestJ = j;', ' }', ' }', ' }', ' ', ' // now, we have the best two points; those are seeds for the clustering', ' DataWrapper <KeyType, DataType> pointOne = myData.remove (bestI);', ' DataWrapper <KeyType, DataType> pointTwo = myData.remove (bestJ - 1);', ' ', ' // these are the two new lists', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listOne = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listTwo = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' ', ' // put the two seeds in', ' listOne.add (pointOne.getKey (), pointOne.getData ());', ' listTwo.add (pointTwo.getKey (), pointTwo.getData ());', ' ', ' // and add everyone else in', ' while (myData.size () != 0) {', ' ', ' // find the one closest to the first seed', ' int bestIndex = 0;', ' double bestDist = 9e99;', ' ', ' // loop thru all of the candidate data objects', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listOne.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' ', ' // break if no more data', ' if (myData.size () == 0)', ' break;', ' ', ' // loop thru all of the candidate data objects', ' bestDist = 9e99;', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listTwo.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' }', ' ', ' // now we replace our own guts with the first list', ' replaceGuts (listOne);', ' ', ' // and return the other list', ' return listTwo;', ' }', '}', '', 'interface IMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> {', ' ', ' // add a new pair to the list', ' public void add (KeyType keyToAdd, DataType dataToAdd);', ' ', ' // replace a key at the indicated position', ' public void replaceKey (int pos, KeyType keyToAdd);', ' ', ' // get the key, data pair that resides at a particular position', ' public DataWrapper <KeyType, DataType> get (int pos);', ' ', ' // return the number of items in the list', ' public int size ();', ' ', ' // split the list in two, using some clutering algorithm', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // get a sphere that totally bounds all of the objects in the list', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class MTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public MTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class SCMTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public SCMTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', '', 'public class MTreeTester extends TestCase {', ' ', ' // compare two lists of strings to see if the contents are the same', ' private boolean compareStringSets (ArrayList <String> setOne, ArrayList <String> setTwo) {', ' ', ' // sort the sets and make sure they are the same', ' boolean returnVal = true;', ' if (setOne.size () == setTwo.size ()) {', ' Collections.sort (setOne);', ' Collections.sort (setTwo);', ' for (int i = 0; i < setOne.size (); i++) {', ' if (!setOne.get (i).equals (setTwo.get (i))) {', ' returnVal = false;', ' break; ', ' }', ' }', ' } else {', ' returnVal = false;', ' }', ' ', ' // print out the result', ' System.out.println ("**** Expected:");', ' for (int i = 0; i < setOne.size (); i++) {', ' System.out.format (setOne.get (i) + " ");', ' }', ' System.out.println ("\\n**** Got:");', ' for (int i = 0; i < setTwo.size (); i++) {', ' System.out.format (setTwo.get (i) + " ");', ' }', ' System.out.println ("");', ' ', ' return returnVal;', ' }', ' ', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST SIMPLE ONE DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testOneDimRangeQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.find (query, expectedQuerySize / 2);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.find (query, expectedQuerySize / 2);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (numPoints);', ' result1 = myTree.find (query, expectedQuerySize);', ' result2 = hisTree.find (query, expectedQuerySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // like the last one, but runs a top k', ' private void testOneDimTopKQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (167);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.findKClosest (query, querySize);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (0);', ' result1 = myTree.findKClosest (query, querySize);', ' result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST MULTI-DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimRangeQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' double dist1 = 0;', ' double dist2 = 0;', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' dist1 = Math.sqrt (numDims) * expectedQuerySize / 2.0;', ' dist2 = Math.sqrt (numDims) * expectedQuerySize;', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' // do a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, (int) expectedQuerySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = myTree.findKClosest (query2, (int) expectedQuerySize);', ' ', ' // find the distance to the furthest point in both cases', ' for (int i = 0; i < (int) expectedQuerySize; i++) {', ' double newDist = result1.get (i).getKey ().getDistance (query1);', ' if (newDist > dist1)', ' dist1 = newDist;', ' newDist = result2.get (i).getKey ().getDistance (query2);', ' if (newDist > dist2)', ' dist2 = newDist;', ' }', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.find (query1, dist1);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.find (query1, dist1);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.find (query2, dist2);', ' result2 = hisTree.find (query2, dist2);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimTopKQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, querySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.findKClosest (query1, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.findKClosest (query2, querySize);', ' result2 = hisTree.findKClosest (query2, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' ', ' /**', ' * "TIER 1" TESTS', ' * NONE OF THESE REQUIRE ANY SPLITS', ' */', ' public void testEasy1() {', ' testOneDimRangeQuery (true, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy2() {', ' testOneDimRangeQuery (false, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy3() {', ' testOneDimRangeQuery (true, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy4() {', ' testOneDimRangeQuery (false, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy5() {', ' testMultiDimRangeQuery (true, 1, 5, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy6() {', ' testMultiDimRangeQuery (false, 1, 10, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy7() {', ' testMultiDimRangeQuery (true, 1, 5, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy8() {', ' testMultiDimRangeQuery (false, 1, 15, 10000, 10000, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 2" TESTS', ' * NONE OF THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testMod1() {', ' testOneDimRangeQuery (true, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod2() {', ' testOneDimRangeQuery (false, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod3() {', ' testOneDimRangeQuery (true, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod4() {', ' testOneDimRangeQuery (false, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod5() {', ' testMultiDimRangeQuery (true, 2, 5, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod6() {', ' testMultiDimRangeQuery (false, 2, 10, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod7() {', ' testMultiDimRangeQuery (true, 2, 5, 10000, 100, 1000, 10);', ' }', ' ', ' public void testMod8() {', ' testMultiDimRangeQuery (false, 2, 15, 10000, 100, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 3" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testHard1() {', ' testOneDimRangeQuery (true, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard2() {', ' testOneDimRangeQuery (false, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard3() {', ' testOneDimRangeQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard4() {', ' testOneDimRangeQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard5() {', ' testMultiDimRangeQuery (true, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard6() {', ' testMultiDimRangeQuery (false, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard7() {', ' testMultiDimRangeQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard8() {', ' testMultiDimRangeQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', ' ', ' /**', ' * "TIER 4" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE AND THEY TEST THE TOPK FUNCTIONALITY', ' */', ' ', ' public void testTopK1() {', ' testOneDimTopKQuery (true, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK2() {', ' testOneDimTopKQuery (false, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK3() {', ' testOneDimTopKQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK4() {', ' testOneDimTopKQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK5() {', ' testMultiDimTopKQuery (true, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK6() {', ' testMultiDimTopKQuery (false, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK7() {', ' testMultiDimTopKQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK8() {', ' testMultiDimTopKQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', '}'] | [{'reason_category': 'Loop Body', 'usage_line': 514}, {'reason_category': 'If Body', 'usage_line': 514}, {'reason_category': 'Loop Body', 'usage_line': 515}, {'reason_category': 'If Body', 'usage_line': 515}] | Global_Variable 'myData' used at line 514 is defined at line 454 and has a Long-Range dependency.
Variable 'i' used at line 514 is defined at line 511 and has a Short-Range dependency.
Function 'getData' used at line 514 is defined at line 443 and has a Long-Range dependency.
Function 'findKClosest' used at line 514 is defined at line 510 and has a Short-Range dependency.
Variable 'query' used at line 514 is defined at line 510 and has a Short-Range dependency.
Variable 'myQ' used at line 514 is defined at line 510 and has a Short-Range dependency. | {'Loop Body': 2, 'If Body': 2} | {'Global_Variable Long-Range': 1, 'Variable Short-Range': 3, 'Function Long-Range': 1, 'Function Short-Range': 1} |
infilling_java | MTreeTester | 513 | 516 | ['import junit.framework.TestCase;', 'import java.util.ArrayList;', 'import java.util.Random;', 'import java.util.Collections;', '', '// this is a map from a set of keys of type PointInMetricSpace to a', '// set of data of type DataType', 'interface IMTree <Key extends IPointInMetricSpace <Key>, Data> {', ' ', ' // insert a new key/data pair into the map', ' void insert (Key keyToAdd, Data dataToAdd);', ' ', ' // find all of the key/data pairs in the map that fall within a', ' // particular distance of query point if no results are found, then', ' // an empty array is returned (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> find (Key query, double distance);', ' ', ' // find the k closest key/data pairs in the map to a particular', ' // query point ', ' //', ' // if the number of points in the map is less than k, then the', ' // returned list will have less than k pairs in it', ' //', ' // if the number of points is zero, then an empty array is returned', ' // (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> findKClosest (Key query, int k);', ' ', ' // returns the number of nodes that exist on a path from root to leaf in the tree...', ' // whtever the details of the implementation are, a tree with a single leaf node should return 1, and a tree', ' // with more than one lead node should return at least two (since it must have at least one internal node).', ' public int depth ();', ' ', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', '', 'interface IDoubleVector {', '', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '', '// this correponds to some geometric object in a metric space; the object is built out of', '// one or more points of type PointInMetricSpace', 'interface IObjectInMetricSpaceABCD <PointInMetricSpace extends IPointInMetricSpace<PointInMetricSpace>> {', ' ', ' // get the maximum distance from some point on the shape to a particular point in the metric space', ' double maxDistanceTo (PointInMetricSpace checkMe);', ' ', ' // return some arbitrary point on the interior of the geometric object', ' PointInMetricSpace getPointInInterior ();', '}', '', '', '// this interface corresponds to a point in some metric space', 'interface IPointInMetricSpace <PointInMetricSpace> {', ' ', ' // get the distance to another point', ' // ', ' // for this to work in an M-Tree, distances should be "metric" and', ' // obey the triangle inequality', ' double getDistance (PointInMetricSpace toMe);', '}', '', '// this is the basic node type in the structure', 'interface IMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> {', ' ', ' // insert a new key/data pair into the structure. The return value is a new MTreeNode if there was', ' // a split in response to the insertion, or a null if there was no split', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd);', ' ', ' // find all of the key/data pairs in the structure that fall within a particular query sphere', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query); ', ' ', ' // find the set of items closest to the given query point', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ);', ' ', ' // returns a sphere that totally encompasses everything in the node and its subtree', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', ' ', ' // returns the depth', ' public int depth ();', '}', '', '// this is a point in a particular metric space', 'class PointABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the point', ' private PointInMetricSpace me;', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return me; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return checkMe.getDistance (me); ', ' }', ' ', ' // contruct a point', ' public PointABCD (PointInMetricSpace useMe) {', ' me = useMe; ', ' }', '}', '', 'class PQueueABCD <PointInMetricSpace, DataType> {', ' ', ' // this is an object in the queue', ' private class Wrapper {', ' DataWrapper <PointInMetricSpace, DataType> myData;', ' double distance;', ' }', ' ', ' // this is the actual queue', ' ArrayList <Wrapper> myList;', ' ', ' // this is the largest distance value currently in the queue', ' double large;', ' ', ' // this is the max number of objects', ' int maxCount;', ' ', ' // create a priority queue with the speced number of slots', ' PQueueABCD (int maxCountIn) {', ' maxCount = maxCountIn;', ' myList = new ArrayList <Wrapper> ();', ' large = 9e99;', ' }', ' ', ' // get the largest distance in the queue', ' double getDist () {', ' return large;', ' }', ' ', ' // add a new object to the queue... the insertion is ignored if the distance value', ' // exceeds the largest that is in the queue and the queue is already full', ' void insert (PointInMetricSpace key, DataType data, double distance) {', ' ', ' // if we are full, remove the one with the largest distance', ' if (myList.size () == maxCount && distance < large) {', ' ', ' int badIndex = 0;', ' double maxDist = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > maxDist) {', ' maxDist = myList.get (i).distance;', ' badIndex = i;', ' }', ' }', ' ', ' myList.remove (badIndex);', ' }', ' ', ' // see if there is room', ' if (myList.size () < maxCount) {', ' ', ' // add it ', ' Wrapper newOne = new Wrapper ();', ' newOne.myData = new DataWrapper <PointInMetricSpace, DataType> (key, data);', ' newOne.distance = distance;', ' myList.add (newOne); ', ' }', ' ', ' // if we are full, reset the max distance', ' if (myList.size () == maxCount) {', ' large = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > large) {', ' large = myList.get (i).distance;', ' }', ' }', ' }', ' ', ' }', ' ', ' // extracts the contents of the queue', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> done () {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' for (int i = 0; i < myList.size (); i++) {', ' returnVal.add (myList.get (i).myData); ', ' }', ' ', ' return returnVal;', ' }', ' ', '}', '', '// this is a sphere in a particular metric space', 'class SphereABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the center of the sphere and its radius', ' private PointInMetricSpace center;', ' private double radius;', ' ', ' // build a sphere out of its center and its radius', ' public SphereABCD (PointInMetricSpace centerIn, double radiusIn) {', ' center = centerIn;', ' radius = radiusIn;', ' }', ' ', ' // increase the size of the sphere so it contains the object swallowMe', ' public void swallow (IObjectInMetricSpaceABCD <PointInMetricSpace> swallowMe) {', ' ', ' // see if we need to increase the radius to swallow this guy', ' double dist = swallowMe.maxDistanceTo (center);', ' if (dist > radius)', ' radius = dist;', ' }', ' ', ' // check to see if a sphere intersects another sphere', ' public boolean intersects (SphereABCD <PointInMetricSpace> me) {', ' return (me.center.getDistance (center) <= me.radius + radius);', ' }', ' ', ' // check to see if the sphere contains a point', ' public boolean contains (PointInMetricSpace checkMe) {', ' return (checkMe.getDistance (center) <= radius);', ' }', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return center; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return radius + checkMe.getDistance (center); ', ' }', '}', '', '', '', 'class OneDimPoint implements IPointInMetricSpace <OneDimPoint> {', ' ', ' // this is the actual double', ' Double value;', ' ', ' // construct this out of a double value', ' public OneDimPoint (double makeFromMe) {', ' value = new Double (makeFromMe);', ' }', ' ', ' // get the distance to another point', ' public double getDistance (OneDimPoint toMe) {', ' if (value > toMe.value)', ' return value - toMe.value;', ' else', ' return toMe.value - value;', ' }', ' ', '}', '', 'class MultiDimPoint implements IPointInMetricSpace <MultiDimPoint> {', ' ', ' // this is the point in a multidimensional space', ' IDoubleVector me;', ' ', ' // make this out of an IDoubleVector', ' public MultiDimPoint (IDoubleVector useMe) {', ' me = useMe;', ' }', ' ', ' // get the Euclidean distance to another point', ' public double getDistance (MultiDimPoint toMe) {', ' double distance = 0.0;', ' try {', ' for (int i = 0; i < me.getLength (); i++) {', ' double diff = me.getItem (i) - toMe.me.getItem (i);', ' diff *= diff;', ' distance += diff;', ' }', ' } catch (OutOfBoundsException e) {', ' throw new IndexOutOfBoundsException ("Can\'t compare two MultiDimPoint objects with different dimensionality!"); ', ' }', ' return Math.sqrt(distance);', ' }', ' ', '}', '// this is a leaf node', 'class LeafMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements ', ' IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myData;', ' ', ' // contructor that takes a data list and builds a node out of it', ' private LeafMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myDataIn) {', ' myData = myDataIn; ', ' }', ' ', ' // constructor that creates an empty node', ' public LeafMTreeNodeABCD () {', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> (); ', ' }', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // just add in the new data', ' myData.add (new PointABCD <PointInMetricSpace> (keyToAdd), dataToAdd);', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> newOne = myData.splitInTwo ();', ' LeafMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' myQ.insert (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData (), ', ' query.getDistance (myData.get (i).getKey ().getPointInInterior ()));', ' }', ' }', ' }', ' ', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' returnVal.add (new DataWrapper <PointInMetricSpace, DataType> (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData ()));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return 1; ', ' }', '', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', '// this silly little class is just a wrapper for a key, data pair', 'class DataWrapper <Key, Data> {', ' ', ' Key key;', ' Data data;', ' ', ' public DataWrapper (Key keyIn, Data dataIn) {', ' key = keyIn;', ' data = dataIn;', ' }', ' ', ' public Key getKey () {', ' return key;', ' }', ' ', ' public Data getData () {', ' return data;', ' }', '}', '', '', '// this is an internal node', 'class InternalMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType>', ' implements IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> myData;', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' // this constructs a new internal node that holds precisely the two nodes that are passed in', ' public InternalMTreeNodeABCD (IMTreeNodeABCD <PointInMetricSpace, DataType> refOne,', ' IMTreeNodeABCD <PointInMetricSpace, DataType> refTwo) {', ' ', ' // create a necw list and add the two guys in', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> ();', ' myData.add (refOne.getBoundingSphere (), refOne);', ' myData.add (refTwo.getBoundingSphere (), refTwo);', ' }', ' ', ' // this constructs a new node that holds the list of data that we were passed in', ' public InternalMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> useMe) {', ' myData = useMe; ', ' }', ' ', ' // from the interface', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // find the best child; this is the one we are closest to', ' double bestDist = 9e99;', ' int bestIndex = 0;', ' for (int i = 0; i < myData.size (); i++) {', ' ', ' double newDist = myData.get (i).getKey ().getPointInInterior ().getDistance (keyToAdd);', ' if (newDist < bestDist) {', ' bestDist = newDist;', ' bestIndex = i;', ' }', ' }', ' ', ' // do the recursive insert', ' IMTreeNodeABCD <PointInMetricSpace, DataType> newRef = myData.get (bestIndex).getData ().insert (keyToAdd, dataToAdd);', ' ', ' // if we got something back, then there was a split, so add the new node into our list', ' if (newRef != null) {', ' myData.add (newRef.getBoundingSphere (), newRef);', ' }', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> newOne = myData.splitInTwo ();', ' InternalMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());'] | [' if (mySphere.intersects (myData.get (i).getKey ())) {', ' myData.get (i).getData ().findKClosest (query, myQ);', ' }', ' }'] | [' }', ' ', ' // from the interface', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.intersects (myData.get (i).getKey ())) {', ' returnVal.addAll (myData.get (i).getData ().find (query));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return myData.get (0).getData ().depth () + 1; ', ' }', ' ', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', 'abstract class AMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> implements IMetricDataListABCD <PointInMetricSpace,KeyType, DataType> {', '', ' // this is the data that is actually stored in the list', ' private ArrayList <DataWrapper <KeyType, DataType>> myData;', ' ', ' // this is the sphere that bounds everything in the list', ' private SphereABCD <PointInMetricSpace> myBoundingSphere;', ' ', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myBoundingSphere; ', ' }', ' ', ' public int size () {', ' if (myData != null)', ' return myData.size (); ', ' else', ' return 0;', ' }', ' ', ' public DataWrapper <KeyType, DataType> get (int pos) {', ' return myData.get (pos);', ' }', ' ', ' public void replaceKey (int pos, KeyType keyToAdd) {', ' DataWrapper <KeyType, DataType> temp = myData.remove (pos);', ' DataWrapper <KeyType, DataType> newOne = new DataWrapper <KeyType, DataType> (keyToAdd, temp.getData ());', ' myData.add (pos, newOne);', ' }', ' ', ' public void add (KeyType keyToAdd, DataType dataToAdd) {', ' ', ' // if this is the first add, then set everyone up', ' if (myData == null) {', ' PointInMetricSpace myCentroid = keyToAdd.getPointInInterior ();', ' myBoundingSphere = new SphereABCD <PointInMetricSpace> (myCentroid, keyToAdd.maxDistanceTo (myCentroid));', ' myData = new ArrayList <DataWrapper <KeyType, DataType>> ();', ' ', ' // otherwise, extend the sphere if needed', ' } else {', ' myBoundingSphere.swallow (keyToAdd);', ' }', ' ', ' // add the data', ' myData.add (new DataWrapper <KeyType, DataType> (keyToAdd, dataToAdd));', ' }', ' ', ' // we want to potentially allow many implementations of the splitting lalgorithm', ' abstract public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // this is here so the actual splitting algorithn can access the list and change the sphere', ' protected ArrayList <DataWrapper <KeyType, DataType>> getList () {', ' return myData;', ' }', ' ', ' // this is here so the splitting algorithm can modify the list and the sphere', ' protected void replaceGuts (AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> withMe) {', ' myData = withMe.myData;', ' myBoundingSphere = withMe.myBoundingSphere;', ' }', ' ', '}', '', '// this is a particular implementation of the metric data list that uses a simple quadratic clustering', '// algorithm to perform a list split. It picks two "seeds" (the most distant objects) and then repeatedly', '// adds to the two new lists by choosing the objects closest to the seeds', 'class ChrisMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> extends AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> {', '', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo () {', ' ', ' // first, we need to find the two most distant points in the list', ' ArrayList <DataWrapper <KeyType, DataType>> myData = getList ();', ' int bestI = 0, bestJ = 0;', ' double maxDist = -1.0;', ' for (int i = 0; i < myData.size (); i++) {', ' for (int j = i + 1; j < myData.size (); j++) {', ' ', ' // get the two keys', ' DataWrapper <KeyType, DataType> pointOne = myData.get (i);', ' DataWrapper <KeyType, DataType> pointTwo = myData.get (j);', ' ', ' // find the difference between them', ' double curDist = pointOne.getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', '', ' // see if it is the biggest', ' if (curDist > maxDist) {', ' maxDist = curDist;', ' bestI = i;', ' bestJ = j;', ' }', ' }', ' }', ' ', ' // now, we have the best two points; those are seeds for the clustering', ' DataWrapper <KeyType, DataType> pointOne = myData.remove (bestI);', ' DataWrapper <KeyType, DataType> pointTwo = myData.remove (bestJ - 1);', ' ', ' // these are the two new lists', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listOne = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listTwo = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' ', ' // put the two seeds in', ' listOne.add (pointOne.getKey (), pointOne.getData ());', ' listTwo.add (pointTwo.getKey (), pointTwo.getData ());', ' ', ' // and add everyone else in', ' while (myData.size () != 0) {', ' ', ' // find the one closest to the first seed', ' int bestIndex = 0;', ' double bestDist = 9e99;', ' ', ' // loop thru all of the candidate data objects', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listOne.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' ', ' // break if no more data', ' if (myData.size () == 0)', ' break;', ' ', ' // loop thru all of the candidate data objects', ' bestDist = 9e99;', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listTwo.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' }', ' ', ' // now we replace our own guts with the first list', ' replaceGuts (listOne);', ' ', ' // and return the other list', ' return listTwo;', ' }', '}', '', 'interface IMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> {', ' ', ' // add a new pair to the list', ' public void add (KeyType keyToAdd, DataType dataToAdd);', ' ', ' // replace a key at the indicated position', ' public void replaceKey (int pos, KeyType keyToAdd);', ' ', ' // get the key, data pair that resides at a particular position', ' public DataWrapper <KeyType, DataType> get (int pos);', ' ', ' // return the number of items in the list', ' public int size ();', ' ', ' // split the list in two, using some clutering algorithm', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // get a sphere that totally bounds all of the objects in the list', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class MTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public MTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class SCMTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public SCMTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', '', 'public class MTreeTester extends TestCase {', ' ', ' // compare two lists of strings to see if the contents are the same', ' private boolean compareStringSets (ArrayList <String> setOne, ArrayList <String> setTwo) {', ' ', ' // sort the sets and make sure they are the same', ' boolean returnVal = true;', ' if (setOne.size () == setTwo.size ()) {', ' Collections.sort (setOne);', ' Collections.sort (setTwo);', ' for (int i = 0; i < setOne.size (); i++) {', ' if (!setOne.get (i).equals (setTwo.get (i))) {', ' returnVal = false;', ' break; ', ' }', ' }', ' } else {', ' returnVal = false;', ' }', ' ', ' // print out the result', ' System.out.println ("**** Expected:");', ' for (int i = 0; i < setOne.size (); i++) {', ' System.out.format (setOne.get (i) + " ");', ' }', ' System.out.println ("\\n**** Got:");', ' for (int i = 0; i < setTwo.size (); i++) {', ' System.out.format (setTwo.get (i) + " ");', ' }', ' System.out.println ("");', ' ', ' return returnVal;', ' }', ' ', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST SIMPLE ONE DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testOneDimRangeQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.find (query, expectedQuerySize / 2);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.find (query, expectedQuerySize / 2);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (numPoints);', ' result1 = myTree.find (query, expectedQuerySize);', ' result2 = hisTree.find (query, expectedQuerySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // like the last one, but runs a top k', ' private void testOneDimTopKQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (167);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.findKClosest (query, querySize);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (0);', ' result1 = myTree.findKClosest (query, querySize);', ' result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST MULTI-DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimRangeQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' double dist1 = 0;', ' double dist2 = 0;', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' dist1 = Math.sqrt (numDims) * expectedQuerySize / 2.0;', ' dist2 = Math.sqrt (numDims) * expectedQuerySize;', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' // do a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, (int) expectedQuerySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = myTree.findKClosest (query2, (int) expectedQuerySize);', ' ', ' // find the distance to the furthest point in both cases', ' for (int i = 0; i < (int) expectedQuerySize; i++) {', ' double newDist = result1.get (i).getKey ().getDistance (query1);', ' if (newDist > dist1)', ' dist1 = newDist;', ' newDist = result2.get (i).getKey ().getDistance (query2);', ' if (newDist > dist2)', ' dist2 = newDist;', ' }', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.find (query1, dist1);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.find (query1, dist1);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.find (query2, dist2);', ' result2 = hisTree.find (query2, dist2);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimTopKQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, querySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.findKClosest (query1, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.findKClosest (query2, querySize);', ' result2 = hisTree.findKClosest (query2, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' ', ' /**', ' * "TIER 1" TESTS', ' * NONE OF THESE REQUIRE ANY SPLITS', ' */', ' public void testEasy1() {', ' testOneDimRangeQuery (true, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy2() {', ' testOneDimRangeQuery (false, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy3() {', ' testOneDimRangeQuery (true, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy4() {', ' testOneDimRangeQuery (false, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy5() {', ' testMultiDimRangeQuery (true, 1, 5, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy6() {', ' testMultiDimRangeQuery (false, 1, 10, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy7() {', ' testMultiDimRangeQuery (true, 1, 5, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy8() {', ' testMultiDimRangeQuery (false, 1, 15, 10000, 10000, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 2" TESTS', ' * NONE OF THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testMod1() {', ' testOneDimRangeQuery (true, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod2() {', ' testOneDimRangeQuery (false, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod3() {', ' testOneDimRangeQuery (true, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod4() {', ' testOneDimRangeQuery (false, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod5() {', ' testMultiDimRangeQuery (true, 2, 5, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod6() {', ' testMultiDimRangeQuery (false, 2, 10, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod7() {', ' testMultiDimRangeQuery (true, 2, 5, 10000, 100, 1000, 10);', ' }', ' ', ' public void testMod8() {', ' testMultiDimRangeQuery (false, 2, 15, 10000, 100, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 3" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testHard1() {', ' testOneDimRangeQuery (true, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard2() {', ' testOneDimRangeQuery (false, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard3() {', ' testOneDimRangeQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard4() {', ' testOneDimRangeQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard5() {', ' testMultiDimRangeQuery (true, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard6() {', ' testMultiDimRangeQuery (false, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard7() {', ' testMultiDimRangeQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard8() {', ' testMultiDimRangeQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', ' ', ' /**', ' * "TIER 4" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE AND THEY TEST THE TOPK FUNCTIONALITY', ' */', ' ', ' public void testTopK1() {', ' testOneDimTopKQuery (true, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK2() {', ' testOneDimTopKQuery (false, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK3() {', ' testOneDimTopKQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK4() {', ' testOneDimTopKQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK5() {', ' testMultiDimTopKQuery (true, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK6() {', ' testMultiDimTopKQuery (false, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK7() {', ' testMultiDimTopKQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK8() {', ' testMultiDimTopKQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', '}'] | [{'reason_category': 'Loop Body', 'usage_line': 513}, {'reason_category': 'If Condition', 'usage_line': 513}, {'reason_category': 'Loop Body', 'usage_line': 514}, {'reason_category': 'If Body', 'usage_line': 514}, {'reason_category': 'Loop Body', 'usage_line': 515}, {'reason_category': 'If Body', 'usage_line': 515}, {'reason_category': 'Loop Body', 'usage_line': 516}] | Function 'SphereABCD.intersects' used at line 513 is defined at line 284 and has a Long-Range dependency.
Global_Variable 'myData' used at line 513 is defined at line 454 and has a Long-Range dependency.
Variable 'i' used at line 513 is defined at line 511 and has a Short-Range dependency.
Function 'getKey' used at line 513 is defined at line 439 and has a Long-Range dependency.
Global_Variable 'myData' used at line 514 is defined at line 454 and has a Long-Range dependency.
Variable 'i' used at line 514 is defined at line 511 and has a Short-Range dependency.
Function 'getData' used at line 514 is defined at line 443 and has a Long-Range dependency.
Function 'findKClosest' used at line 514 is defined at line 510 and has a Short-Range dependency.
Variable 'query' used at line 514 is defined at line 510 and has a Short-Range dependency.
Variable 'myQ' used at line 514 is defined at line 510 and has a Short-Range dependency. | {'Loop Body': 4, 'If Condition': 1, 'If Body': 2} | {'Function Long-Range': 3, 'Global_Variable Long-Range': 2, 'Variable Short-Range': 4, 'Function Short-Range': 1} |
infilling_java | MTreeTester | 511 | 517 | ['import junit.framework.TestCase;', 'import java.util.ArrayList;', 'import java.util.Random;', 'import java.util.Collections;', '', '// this is a map from a set of keys of type PointInMetricSpace to a', '// set of data of type DataType', 'interface IMTree <Key extends IPointInMetricSpace <Key>, Data> {', ' ', ' // insert a new key/data pair into the map', ' void insert (Key keyToAdd, Data dataToAdd);', ' ', ' // find all of the key/data pairs in the map that fall within a', ' // particular distance of query point if no results are found, then', ' // an empty array is returned (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> find (Key query, double distance);', ' ', ' // find the k closest key/data pairs in the map to a particular', ' // query point ', ' //', ' // if the number of points in the map is less than k, then the', ' // returned list will have less than k pairs in it', ' //', ' // if the number of points is zero, then an empty array is returned', ' // (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> findKClosest (Key query, int k);', ' ', ' // returns the number of nodes that exist on a path from root to leaf in the tree...', ' // whtever the details of the implementation are, a tree with a single leaf node should return 1, and a tree', ' // with more than one lead node should return at least two (since it must have at least one internal node).', ' public int depth ();', ' ', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', '', 'interface IDoubleVector {', '', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '', '// this correponds to some geometric object in a metric space; the object is built out of', '// one or more points of type PointInMetricSpace', 'interface IObjectInMetricSpaceABCD <PointInMetricSpace extends IPointInMetricSpace<PointInMetricSpace>> {', ' ', ' // get the maximum distance from some point on the shape to a particular point in the metric space', ' double maxDistanceTo (PointInMetricSpace checkMe);', ' ', ' // return some arbitrary point on the interior of the geometric object', ' PointInMetricSpace getPointInInterior ();', '}', '', '', '// this interface corresponds to a point in some metric space', 'interface IPointInMetricSpace <PointInMetricSpace> {', ' ', ' // get the distance to another point', ' // ', ' // for this to work in an M-Tree, distances should be "metric" and', ' // obey the triangle inequality', ' double getDistance (PointInMetricSpace toMe);', '}', '', '// this is the basic node type in the structure', 'interface IMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> {', ' ', ' // insert a new key/data pair into the structure. The return value is a new MTreeNode if there was', ' // a split in response to the insertion, or a null if there was no split', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd);', ' ', ' // find all of the key/data pairs in the structure that fall within a particular query sphere', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query); ', ' ', ' // find the set of items closest to the given query point', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ);', ' ', ' // returns a sphere that totally encompasses everything in the node and its subtree', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', ' ', ' // returns the depth', ' public int depth ();', '}', '', '// this is a point in a particular metric space', 'class PointABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the point', ' private PointInMetricSpace me;', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return me; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return checkMe.getDistance (me); ', ' }', ' ', ' // contruct a point', ' public PointABCD (PointInMetricSpace useMe) {', ' me = useMe; ', ' }', '}', '', 'class PQueueABCD <PointInMetricSpace, DataType> {', ' ', ' // this is an object in the queue', ' private class Wrapper {', ' DataWrapper <PointInMetricSpace, DataType> myData;', ' double distance;', ' }', ' ', ' // this is the actual queue', ' ArrayList <Wrapper> myList;', ' ', ' // this is the largest distance value currently in the queue', ' double large;', ' ', ' // this is the max number of objects', ' int maxCount;', ' ', ' // create a priority queue with the speced number of slots', ' PQueueABCD (int maxCountIn) {', ' maxCount = maxCountIn;', ' myList = new ArrayList <Wrapper> ();', ' large = 9e99;', ' }', ' ', ' // get the largest distance in the queue', ' double getDist () {', ' return large;', ' }', ' ', ' // add a new object to the queue... the insertion is ignored if the distance value', ' // exceeds the largest that is in the queue and the queue is already full', ' void insert (PointInMetricSpace key, DataType data, double distance) {', ' ', ' // if we are full, remove the one with the largest distance', ' if (myList.size () == maxCount && distance < large) {', ' ', ' int badIndex = 0;', ' double maxDist = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > maxDist) {', ' maxDist = myList.get (i).distance;', ' badIndex = i;', ' }', ' }', ' ', ' myList.remove (badIndex);', ' }', ' ', ' // see if there is room', ' if (myList.size () < maxCount) {', ' ', ' // add it ', ' Wrapper newOne = new Wrapper ();', ' newOne.myData = new DataWrapper <PointInMetricSpace, DataType> (key, data);', ' newOne.distance = distance;', ' myList.add (newOne); ', ' }', ' ', ' // if we are full, reset the max distance', ' if (myList.size () == maxCount) {', ' large = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > large) {', ' large = myList.get (i).distance;', ' }', ' }', ' }', ' ', ' }', ' ', ' // extracts the contents of the queue', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> done () {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' for (int i = 0; i < myList.size (); i++) {', ' returnVal.add (myList.get (i).myData); ', ' }', ' ', ' return returnVal;', ' }', ' ', '}', '', '// this is a sphere in a particular metric space', 'class SphereABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the center of the sphere and its radius', ' private PointInMetricSpace center;', ' private double radius;', ' ', ' // build a sphere out of its center and its radius', ' public SphereABCD (PointInMetricSpace centerIn, double radiusIn) {', ' center = centerIn;', ' radius = radiusIn;', ' }', ' ', ' // increase the size of the sphere so it contains the object swallowMe', ' public void swallow (IObjectInMetricSpaceABCD <PointInMetricSpace> swallowMe) {', ' ', ' // see if we need to increase the radius to swallow this guy', ' double dist = swallowMe.maxDistanceTo (center);', ' if (dist > radius)', ' radius = dist;', ' }', ' ', ' // check to see if a sphere intersects another sphere', ' public boolean intersects (SphereABCD <PointInMetricSpace> me) {', ' return (me.center.getDistance (center) <= me.radius + radius);', ' }', ' ', ' // check to see if the sphere contains a point', ' public boolean contains (PointInMetricSpace checkMe) {', ' return (checkMe.getDistance (center) <= radius);', ' }', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return center; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return radius + checkMe.getDistance (center); ', ' }', '}', '', '', '', 'class OneDimPoint implements IPointInMetricSpace <OneDimPoint> {', ' ', ' // this is the actual double', ' Double value;', ' ', ' // construct this out of a double value', ' public OneDimPoint (double makeFromMe) {', ' value = new Double (makeFromMe);', ' }', ' ', ' // get the distance to another point', ' public double getDistance (OneDimPoint toMe) {', ' if (value > toMe.value)', ' return value - toMe.value;', ' else', ' return toMe.value - value;', ' }', ' ', '}', '', 'class MultiDimPoint implements IPointInMetricSpace <MultiDimPoint> {', ' ', ' // this is the point in a multidimensional space', ' IDoubleVector me;', ' ', ' // make this out of an IDoubleVector', ' public MultiDimPoint (IDoubleVector useMe) {', ' me = useMe;', ' }', ' ', ' // get the Euclidean distance to another point', ' public double getDistance (MultiDimPoint toMe) {', ' double distance = 0.0;', ' try {', ' for (int i = 0; i < me.getLength (); i++) {', ' double diff = me.getItem (i) - toMe.me.getItem (i);', ' diff *= diff;', ' distance += diff;', ' }', ' } catch (OutOfBoundsException e) {', ' throw new IndexOutOfBoundsException ("Can\'t compare two MultiDimPoint objects with different dimensionality!"); ', ' }', ' return Math.sqrt(distance);', ' }', ' ', '}', '// this is a leaf node', 'class LeafMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements ', ' IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myData;', ' ', ' // contructor that takes a data list and builds a node out of it', ' private LeafMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myDataIn) {', ' myData = myDataIn; ', ' }', ' ', ' // constructor that creates an empty node', ' public LeafMTreeNodeABCD () {', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> (); ', ' }', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // just add in the new data', ' myData.add (new PointABCD <PointInMetricSpace> (keyToAdd), dataToAdd);', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> newOne = myData.splitInTwo ();', ' LeafMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' myQ.insert (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData (), ', ' query.getDistance (myData.get (i).getKey ().getPointInInterior ()));', ' }', ' }', ' }', ' ', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' returnVal.add (new DataWrapper <PointInMetricSpace, DataType> (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData ()));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return 1; ', ' }', '', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', '// this silly little class is just a wrapper for a key, data pair', 'class DataWrapper <Key, Data> {', ' ', ' Key key;', ' Data data;', ' ', ' public DataWrapper (Key keyIn, Data dataIn) {', ' key = keyIn;', ' data = dataIn;', ' }', ' ', ' public Key getKey () {', ' return key;', ' }', ' ', ' public Data getData () {', ' return data;', ' }', '}', '', '', '// this is an internal node', 'class InternalMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType>', ' implements IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> myData;', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' // this constructs a new internal node that holds precisely the two nodes that are passed in', ' public InternalMTreeNodeABCD (IMTreeNodeABCD <PointInMetricSpace, DataType> refOne,', ' IMTreeNodeABCD <PointInMetricSpace, DataType> refTwo) {', ' ', ' // create a necw list and add the two guys in', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> ();', ' myData.add (refOne.getBoundingSphere (), refOne);', ' myData.add (refTwo.getBoundingSphere (), refTwo);', ' }', ' ', ' // this constructs a new node that holds the list of data that we were passed in', ' public InternalMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> useMe) {', ' myData = useMe; ', ' }', ' ', ' // from the interface', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // find the best child; this is the one we are closest to', ' double bestDist = 9e99;', ' int bestIndex = 0;', ' for (int i = 0; i < myData.size (); i++) {', ' ', ' double newDist = myData.get (i).getKey ().getPointInInterior ().getDistance (keyToAdd);', ' if (newDist < bestDist) {', ' bestDist = newDist;', ' bestIndex = i;', ' }', ' }', ' ', ' // do the recursive insert', ' IMTreeNodeABCD <PointInMetricSpace, DataType> newRef = myData.get (bestIndex).getData ().insert (keyToAdd, dataToAdd);', ' ', ' // if we got something back, then there was a split, so add the new node into our list', ' if (newRef != null) {', ' myData.add (newRef.getBoundingSphere (), newRef);', ' }', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> newOne = myData.splitInTwo ();', ' InternalMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {'] | [' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.intersects (myData.get (i).getKey ())) {', ' myData.get (i).getData ().findKClosest (query, myQ);', ' }', ' }', ' }'] | [' ', ' // from the interface', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.intersects (myData.get (i).getKey ())) {', ' returnVal.addAll (myData.get (i).getData ().find (query));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return myData.get (0).getData ().depth () + 1; ', ' }', ' ', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', 'abstract class AMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> implements IMetricDataListABCD <PointInMetricSpace,KeyType, DataType> {', '', ' // this is the data that is actually stored in the list', ' private ArrayList <DataWrapper <KeyType, DataType>> myData;', ' ', ' // this is the sphere that bounds everything in the list', ' private SphereABCD <PointInMetricSpace> myBoundingSphere;', ' ', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myBoundingSphere; ', ' }', ' ', ' public int size () {', ' if (myData != null)', ' return myData.size (); ', ' else', ' return 0;', ' }', ' ', ' public DataWrapper <KeyType, DataType> get (int pos) {', ' return myData.get (pos);', ' }', ' ', ' public void replaceKey (int pos, KeyType keyToAdd) {', ' DataWrapper <KeyType, DataType> temp = myData.remove (pos);', ' DataWrapper <KeyType, DataType> newOne = new DataWrapper <KeyType, DataType> (keyToAdd, temp.getData ());', ' myData.add (pos, newOne);', ' }', ' ', ' public void add (KeyType keyToAdd, DataType dataToAdd) {', ' ', ' // if this is the first add, then set everyone up', ' if (myData == null) {', ' PointInMetricSpace myCentroid = keyToAdd.getPointInInterior ();', ' myBoundingSphere = new SphereABCD <PointInMetricSpace> (myCentroid, keyToAdd.maxDistanceTo (myCentroid));', ' myData = new ArrayList <DataWrapper <KeyType, DataType>> ();', ' ', ' // otherwise, extend the sphere if needed', ' } else {', ' myBoundingSphere.swallow (keyToAdd);', ' }', ' ', ' // add the data', ' myData.add (new DataWrapper <KeyType, DataType> (keyToAdd, dataToAdd));', ' }', ' ', ' // we want to potentially allow many implementations of the splitting lalgorithm', ' abstract public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // this is here so the actual splitting algorithn can access the list and change the sphere', ' protected ArrayList <DataWrapper <KeyType, DataType>> getList () {', ' return myData;', ' }', ' ', ' // this is here so the splitting algorithm can modify the list and the sphere', ' protected void replaceGuts (AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> withMe) {', ' myData = withMe.myData;', ' myBoundingSphere = withMe.myBoundingSphere;', ' }', ' ', '}', '', '// this is a particular implementation of the metric data list that uses a simple quadratic clustering', '// algorithm to perform a list split. It picks two "seeds" (the most distant objects) and then repeatedly', '// adds to the two new lists by choosing the objects closest to the seeds', 'class ChrisMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> extends AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> {', '', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo () {', ' ', ' // first, we need to find the two most distant points in the list', ' ArrayList <DataWrapper <KeyType, DataType>> myData = getList ();', ' int bestI = 0, bestJ = 0;', ' double maxDist = -1.0;', ' for (int i = 0; i < myData.size (); i++) {', ' for (int j = i + 1; j < myData.size (); j++) {', ' ', ' // get the two keys', ' DataWrapper <KeyType, DataType> pointOne = myData.get (i);', ' DataWrapper <KeyType, DataType> pointTwo = myData.get (j);', ' ', ' // find the difference between them', ' double curDist = pointOne.getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', '', ' // see if it is the biggest', ' if (curDist > maxDist) {', ' maxDist = curDist;', ' bestI = i;', ' bestJ = j;', ' }', ' }', ' }', ' ', ' // now, we have the best two points; those are seeds for the clustering', ' DataWrapper <KeyType, DataType> pointOne = myData.remove (bestI);', ' DataWrapper <KeyType, DataType> pointTwo = myData.remove (bestJ - 1);', ' ', ' // these are the two new lists', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listOne = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listTwo = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' ', ' // put the two seeds in', ' listOne.add (pointOne.getKey (), pointOne.getData ());', ' listTwo.add (pointTwo.getKey (), pointTwo.getData ());', ' ', ' // and add everyone else in', ' while (myData.size () != 0) {', ' ', ' // find the one closest to the first seed', ' int bestIndex = 0;', ' double bestDist = 9e99;', ' ', ' // loop thru all of the candidate data objects', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listOne.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' ', ' // break if no more data', ' if (myData.size () == 0)', ' break;', ' ', ' // loop thru all of the candidate data objects', ' bestDist = 9e99;', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listTwo.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' }', ' ', ' // now we replace our own guts with the first list', ' replaceGuts (listOne);', ' ', ' // and return the other list', ' return listTwo;', ' }', '}', '', 'interface IMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> {', ' ', ' // add a new pair to the list', ' public void add (KeyType keyToAdd, DataType dataToAdd);', ' ', ' // replace a key at the indicated position', ' public void replaceKey (int pos, KeyType keyToAdd);', ' ', ' // get the key, data pair that resides at a particular position', ' public DataWrapper <KeyType, DataType> get (int pos);', ' ', ' // return the number of items in the list', ' public int size ();', ' ', ' // split the list in two, using some clutering algorithm', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // get a sphere that totally bounds all of the objects in the list', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class MTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public MTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class SCMTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public SCMTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', '', 'public class MTreeTester extends TestCase {', ' ', ' // compare two lists of strings to see if the contents are the same', ' private boolean compareStringSets (ArrayList <String> setOne, ArrayList <String> setTwo) {', ' ', ' // sort the sets and make sure they are the same', ' boolean returnVal = true;', ' if (setOne.size () == setTwo.size ()) {', ' Collections.sort (setOne);', ' Collections.sort (setTwo);', ' for (int i = 0; i < setOne.size (); i++) {', ' if (!setOne.get (i).equals (setTwo.get (i))) {', ' returnVal = false;', ' break; ', ' }', ' }', ' } else {', ' returnVal = false;', ' }', ' ', ' // print out the result', ' System.out.println ("**** Expected:");', ' for (int i = 0; i < setOne.size (); i++) {', ' System.out.format (setOne.get (i) + " ");', ' }', ' System.out.println ("\\n**** Got:");', ' for (int i = 0; i < setTwo.size (); i++) {', ' System.out.format (setTwo.get (i) + " ");', ' }', ' System.out.println ("");', ' ', ' return returnVal;', ' }', ' ', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST SIMPLE ONE DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testOneDimRangeQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.find (query, expectedQuerySize / 2);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.find (query, expectedQuerySize / 2);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (numPoints);', ' result1 = myTree.find (query, expectedQuerySize);', ' result2 = hisTree.find (query, expectedQuerySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // like the last one, but runs a top k', ' private void testOneDimTopKQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (167);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.findKClosest (query, querySize);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (0);', ' result1 = myTree.findKClosest (query, querySize);', ' result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST MULTI-DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimRangeQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' double dist1 = 0;', ' double dist2 = 0;', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' dist1 = Math.sqrt (numDims) * expectedQuerySize / 2.0;', ' dist2 = Math.sqrt (numDims) * expectedQuerySize;', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' // do a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, (int) expectedQuerySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = myTree.findKClosest (query2, (int) expectedQuerySize);', ' ', ' // find the distance to the furthest point in both cases', ' for (int i = 0; i < (int) expectedQuerySize; i++) {', ' double newDist = result1.get (i).getKey ().getDistance (query1);', ' if (newDist > dist1)', ' dist1 = newDist;', ' newDist = result2.get (i).getKey ().getDistance (query2);', ' if (newDist > dist2)', ' dist2 = newDist;', ' }', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.find (query1, dist1);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.find (query1, dist1);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.find (query2, dist2);', ' result2 = hisTree.find (query2, dist2);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimTopKQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, querySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.findKClosest (query1, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.findKClosest (query2, querySize);', ' result2 = hisTree.findKClosest (query2, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' ', ' /**', ' * "TIER 1" TESTS', ' * NONE OF THESE REQUIRE ANY SPLITS', ' */', ' public void testEasy1() {', ' testOneDimRangeQuery (true, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy2() {', ' testOneDimRangeQuery (false, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy3() {', ' testOneDimRangeQuery (true, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy4() {', ' testOneDimRangeQuery (false, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy5() {', ' testMultiDimRangeQuery (true, 1, 5, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy6() {', ' testMultiDimRangeQuery (false, 1, 10, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy7() {', ' testMultiDimRangeQuery (true, 1, 5, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy8() {', ' testMultiDimRangeQuery (false, 1, 15, 10000, 10000, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 2" TESTS', ' * NONE OF THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testMod1() {', ' testOneDimRangeQuery (true, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod2() {', ' testOneDimRangeQuery (false, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod3() {', ' testOneDimRangeQuery (true, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod4() {', ' testOneDimRangeQuery (false, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod5() {', ' testMultiDimRangeQuery (true, 2, 5, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod6() {', ' testMultiDimRangeQuery (false, 2, 10, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod7() {', ' testMultiDimRangeQuery (true, 2, 5, 10000, 100, 1000, 10);', ' }', ' ', ' public void testMod8() {', ' testMultiDimRangeQuery (false, 2, 15, 10000, 100, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 3" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testHard1() {', ' testOneDimRangeQuery (true, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard2() {', ' testOneDimRangeQuery (false, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard3() {', ' testOneDimRangeQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard4() {', ' testOneDimRangeQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard5() {', ' testMultiDimRangeQuery (true, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard6() {', ' testMultiDimRangeQuery (false, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard7() {', ' testMultiDimRangeQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard8() {', ' testMultiDimRangeQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', ' ', ' /**', ' * "TIER 4" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE AND THEY TEST THE TOPK FUNCTIONALITY', ' */', ' ', ' public void testTopK1() {', ' testOneDimTopKQuery (true, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK2() {', ' testOneDimTopKQuery (false, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK3() {', ' testOneDimTopKQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK4() {', ' testOneDimTopKQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK5() {', ' testMultiDimTopKQuery (true, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK6() {', ' testMultiDimTopKQuery (false, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK7() {', ' testMultiDimTopKQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK8() {', ' testMultiDimTopKQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', '}'] | [{'reason_category': 'Define Stop Criteria', 'usage_line': 511}, {'reason_category': 'Loop Body', 'usage_line': 512}, {'reason_category': 'Loop Body', 'usage_line': 513}, {'reason_category': 'If Condition', 'usage_line': 513}, {'reason_category': 'Loop Body', 'usage_line': 514}, {'reason_category': 'If Body', 'usage_line': 514}, {'reason_category': 'Loop Body', 'usage_line': 515}, {'reason_category': 'If Body', 'usage_line': 515}, {'reason_category': 'Loop Body', 'usage_line': 516}] | Variable 'i' used at line 511 is defined at line 511 and has a Short-Range dependency.
Global_Variable 'myData' used at line 511 is defined at line 454 and has a Long-Range dependency.
Class 'SphereABCD' used at line 512 is defined at line 261 and has a Long-Range dependency.
Variable 'query' used at line 512 is defined at line 510 and has a Short-Range dependency.
Variable 'myQ' used at line 512 is defined at line 510 and has a Short-Range dependency.
Function 'SphereABCD.intersects' used at line 513 is defined at line 284 and has a Long-Range dependency.
Global_Variable 'myData' used at line 513 is defined at line 454 and has a Long-Range dependency.
Variable 'i' used at line 513 is defined at line 511 and has a Short-Range dependency.
Function 'getKey' used at line 513 is defined at line 439 and has a Long-Range dependency.
Global_Variable 'myData' used at line 514 is defined at line 454 and has a Long-Range dependency.
Variable 'i' used at line 514 is defined at line 511 and has a Short-Range dependency.
Function 'getData' used at line 514 is defined at line 443 and has a Long-Range dependency.
Function 'findKClosest' used at line 514 is defined at line 510 and has a Short-Range dependency.
Variable 'query' used at line 514 is defined at line 510 and has a Short-Range dependency.
Variable 'myQ' used at line 514 is defined at line 510 and has a Short-Range dependency. | {'Define Stop Criteria': 1, 'Loop Body': 5, 'If Condition': 1, 'If Body': 2} | {'Variable Short-Range': 7, 'Global_Variable Long-Range': 3, 'Class Long-Range': 1, 'Function Long-Range': 3, 'Function Short-Range': 1} |
infilling_java | MTreeTester | 527 | 528 | ['import junit.framework.TestCase;', 'import java.util.ArrayList;', 'import java.util.Random;', 'import java.util.Collections;', '', '// this is a map from a set of keys of type PointInMetricSpace to a', '// set of data of type DataType', 'interface IMTree <Key extends IPointInMetricSpace <Key>, Data> {', ' ', ' // insert a new key/data pair into the map', ' void insert (Key keyToAdd, Data dataToAdd);', ' ', ' // find all of the key/data pairs in the map that fall within a', ' // particular distance of query point if no results are found, then', ' // an empty array is returned (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> find (Key query, double distance);', ' ', ' // find the k closest key/data pairs in the map to a particular', ' // query point ', ' //', ' // if the number of points in the map is less than k, then the', ' // returned list will have less than k pairs in it', ' //', ' // if the number of points is zero, then an empty array is returned', ' // (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> findKClosest (Key query, int k);', ' ', ' // returns the number of nodes that exist on a path from root to leaf in the tree...', ' // whtever the details of the implementation are, a tree with a single leaf node should return 1, and a tree', ' // with more than one lead node should return at least two (since it must have at least one internal node).', ' public int depth ();', ' ', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', '', 'interface IDoubleVector {', '', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '', '// this correponds to some geometric object in a metric space; the object is built out of', '// one or more points of type PointInMetricSpace', 'interface IObjectInMetricSpaceABCD <PointInMetricSpace extends IPointInMetricSpace<PointInMetricSpace>> {', ' ', ' // get the maximum distance from some point on the shape to a particular point in the metric space', ' double maxDistanceTo (PointInMetricSpace checkMe);', ' ', ' // return some arbitrary point on the interior of the geometric object', ' PointInMetricSpace getPointInInterior ();', '}', '', '', '// this interface corresponds to a point in some metric space', 'interface IPointInMetricSpace <PointInMetricSpace> {', ' ', ' // get the distance to another point', ' // ', ' // for this to work in an M-Tree, distances should be "metric" and', ' // obey the triangle inequality', ' double getDistance (PointInMetricSpace toMe);', '}', '', '// this is the basic node type in the structure', 'interface IMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> {', ' ', ' // insert a new key/data pair into the structure. The return value is a new MTreeNode if there was', ' // a split in response to the insertion, or a null if there was no split', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd);', ' ', ' // find all of the key/data pairs in the structure that fall within a particular query sphere', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query); ', ' ', ' // find the set of items closest to the given query point', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ);', ' ', ' // returns a sphere that totally encompasses everything in the node and its subtree', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', ' ', ' // returns the depth', ' public int depth ();', '}', '', '// this is a point in a particular metric space', 'class PointABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the point', ' private PointInMetricSpace me;', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return me; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return checkMe.getDistance (me); ', ' }', ' ', ' // contruct a point', ' public PointABCD (PointInMetricSpace useMe) {', ' me = useMe; ', ' }', '}', '', 'class PQueueABCD <PointInMetricSpace, DataType> {', ' ', ' // this is an object in the queue', ' private class Wrapper {', ' DataWrapper <PointInMetricSpace, DataType> myData;', ' double distance;', ' }', ' ', ' // this is the actual queue', ' ArrayList <Wrapper> myList;', ' ', ' // this is the largest distance value currently in the queue', ' double large;', ' ', ' // this is the max number of objects', ' int maxCount;', ' ', ' // create a priority queue with the speced number of slots', ' PQueueABCD (int maxCountIn) {', ' maxCount = maxCountIn;', ' myList = new ArrayList <Wrapper> ();', ' large = 9e99;', ' }', ' ', ' // get the largest distance in the queue', ' double getDist () {', ' return large;', ' }', ' ', ' // add a new object to the queue... the insertion is ignored if the distance value', ' // exceeds the largest that is in the queue and the queue is already full', ' void insert (PointInMetricSpace key, DataType data, double distance) {', ' ', ' // if we are full, remove the one with the largest distance', ' if (myList.size () == maxCount && distance < large) {', ' ', ' int badIndex = 0;', ' double maxDist = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > maxDist) {', ' maxDist = myList.get (i).distance;', ' badIndex = i;', ' }', ' }', ' ', ' myList.remove (badIndex);', ' }', ' ', ' // see if there is room', ' if (myList.size () < maxCount) {', ' ', ' // add it ', ' Wrapper newOne = new Wrapper ();', ' newOne.myData = new DataWrapper <PointInMetricSpace, DataType> (key, data);', ' newOne.distance = distance;', ' myList.add (newOne); ', ' }', ' ', ' // if we are full, reset the max distance', ' if (myList.size () == maxCount) {', ' large = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > large) {', ' large = myList.get (i).distance;', ' }', ' }', ' }', ' ', ' }', ' ', ' // extracts the contents of the queue', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> done () {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' for (int i = 0; i < myList.size (); i++) {', ' returnVal.add (myList.get (i).myData); ', ' }', ' ', ' return returnVal;', ' }', ' ', '}', '', '// this is a sphere in a particular metric space', 'class SphereABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the center of the sphere and its radius', ' private PointInMetricSpace center;', ' private double radius;', ' ', ' // build a sphere out of its center and its radius', ' public SphereABCD (PointInMetricSpace centerIn, double radiusIn) {', ' center = centerIn;', ' radius = radiusIn;', ' }', ' ', ' // increase the size of the sphere so it contains the object swallowMe', ' public void swallow (IObjectInMetricSpaceABCD <PointInMetricSpace> swallowMe) {', ' ', ' // see if we need to increase the radius to swallow this guy', ' double dist = swallowMe.maxDistanceTo (center);', ' if (dist > radius)', ' radius = dist;', ' }', ' ', ' // check to see if a sphere intersects another sphere', ' public boolean intersects (SphereABCD <PointInMetricSpace> me) {', ' return (me.center.getDistance (center) <= me.radius + radius);', ' }', ' ', ' // check to see if the sphere contains a point', ' public boolean contains (PointInMetricSpace checkMe) {', ' return (checkMe.getDistance (center) <= radius);', ' }', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return center; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return radius + checkMe.getDistance (center); ', ' }', '}', '', '', '', 'class OneDimPoint implements IPointInMetricSpace <OneDimPoint> {', ' ', ' // this is the actual double', ' Double value;', ' ', ' // construct this out of a double value', ' public OneDimPoint (double makeFromMe) {', ' value = new Double (makeFromMe);', ' }', ' ', ' // get the distance to another point', ' public double getDistance (OneDimPoint toMe) {', ' if (value > toMe.value)', ' return value - toMe.value;', ' else', ' return toMe.value - value;', ' }', ' ', '}', '', 'class MultiDimPoint implements IPointInMetricSpace <MultiDimPoint> {', ' ', ' // this is the point in a multidimensional space', ' IDoubleVector me;', ' ', ' // make this out of an IDoubleVector', ' public MultiDimPoint (IDoubleVector useMe) {', ' me = useMe;', ' }', ' ', ' // get the Euclidean distance to another point', ' public double getDistance (MultiDimPoint toMe) {', ' double distance = 0.0;', ' try {', ' for (int i = 0; i < me.getLength (); i++) {', ' double diff = me.getItem (i) - toMe.me.getItem (i);', ' diff *= diff;', ' distance += diff;', ' }', ' } catch (OutOfBoundsException e) {', ' throw new IndexOutOfBoundsException ("Can\'t compare two MultiDimPoint objects with different dimensionality!"); ', ' }', ' return Math.sqrt(distance);', ' }', ' ', '}', '// this is a leaf node', 'class LeafMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements ', ' IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myData;', ' ', ' // contructor that takes a data list and builds a node out of it', ' private LeafMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myDataIn) {', ' myData = myDataIn; ', ' }', ' ', ' // constructor that creates an empty node', ' public LeafMTreeNodeABCD () {', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> (); ', ' }', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // just add in the new data', ' myData.add (new PointABCD <PointInMetricSpace> (keyToAdd), dataToAdd);', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> newOne = myData.splitInTwo ();', ' LeafMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' myQ.insert (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData (), ', ' query.getDistance (myData.get (i).getKey ().getPointInInterior ()));', ' }', ' }', ' }', ' ', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' returnVal.add (new DataWrapper <PointInMetricSpace, DataType> (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData ()));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return 1; ', ' }', '', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', '// this silly little class is just a wrapper for a key, data pair', 'class DataWrapper <Key, Data> {', ' ', ' Key key;', ' Data data;', ' ', ' public DataWrapper (Key keyIn, Data dataIn) {', ' key = keyIn;', ' data = dataIn;', ' }', ' ', ' public Key getKey () {', ' return key;', ' }', ' ', ' public Data getData () {', ' return data;', ' }', '}', '', '', '// this is an internal node', 'class InternalMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType>', ' implements IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> myData;', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' // this constructs a new internal node that holds precisely the two nodes that are passed in', ' public InternalMTreeNodeABCD (IMTreeNodeABCD <PointInMetricSpace, DataType> refOne,', ' IMTreeNodeABCD <PointInMetricSpace, DataType> refTwo) {', ' ', ' // create a necw list and add the two guys in', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> ();', ' myData.add (refOne.getBoundingSphere (), refOne);', ' myData.add (refTwo.getBoundingSphere (), refTwo);', ' }', ' ', ' // this constructs a new node that holds the list of data that we were passed in', ' public InternalMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> useMe) {', ' myData = useMe; ', ' }', ' ', ' // from the interface', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // find the best child; this is the one we are closest to', ' double bestDist = 9e99;', ' int bestIndex = 0;', ' for (int i = 0; i < myData.size (); i++) {', ' ', ' double newDist = myData.get (i).getKey ().getPointInInterior ().getDistance (keyToAdd);', ' if (newDist < bestDist) {', ' bestDist = newDist;', ' bestIndex = i;', ' }', ' }', ' ', ' // do the recursive insert', ' IMTreeNodeABCD <PointInMetricSpace, DataType> newRef = myData.get (bestIndex).getData ().insert (keyToAdd, dataToAdd);', ' ', ' // if we got something back, then there was a split, so add the new node into our list', ' if (newRef != null) {', ' myData.add (newRef.getBoundingSphere (), newRef);', ' }', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> newOne = myData.splitInTwo ();', ' InternalMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.intersects (myData.get (i).getKey ())) {', ' myData.get (i).getData ().findKClosest (query, myQ);', ' }', ' }', ' }', ' ', ' // from the interface', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.intersects (myData.get (i).getKey ())) {'] | [' returnVal.addAll (myData.get (i).getData ().find (query));', ' }'] | [' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return myData.get (0).getData ().depth () + 1; ', ' }', ' ', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', 'abstract class AMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> implements IMetricDataListABCD <PointInMetricSpace,KeyType, DataType> {', '', ' // this is the data that is actually stored in the list', ' private ArrayList <DataWrapper <KeyType, DataType>> myData;', ' ', ' // this is the sphere that bounds everything in the list', ' private SphereABCD <PointInMetricSpace> myBoundingSphere;', ' ', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myBoundingSphere; ', ' }', ' ', ' public int size () {', ' if (myData != null)', ' return myData.size (); ', ' else', ' return 0;', ' }', ' ', ' public DataWrapper <KeyType, DataType> get (int pos) {', ' return myData.get (pos);', ' }', ' ', ' public void replaceKey (int pos, KeyType keyToAdd) {', ' DataWrapper <KeyType, DataType> temp = myData.remove (pos);', ' DataWrapper <KeyType, DataType> newOne = new DataWrapper <KeyType, DataType> (keyToAdd, temp.getData ());', ' myData.add (pos, newOne);', ' }', ' ', ' public void add (KeyType keyToAdd, DataType dataToAdd) {', ' ', ' // if this is the first add, then set everyone up', ' if (myData == null) {', ' PointInMetricSpace myCentroid = keyToAdd.getPointInInterior ();', ' myBoundingSphere = new SphereABCD <PointInMetricSpace> (myCentroid, keyToAdd.maxDistanceTo (myCentroid));', ' myData = new ArrayList <DataWrapper <KeyType, DataType>> ();', ' ', ' // otherwise, extend the sphere if needed', ' } else {', ' myBoundingSphere.swallow (keyToAdd);', ' }', ' ', ' // add the data', ' myData.add (new DataWrapper <KeyType, DataType> (keyToAdd, dataToAdd));', ' }', ' ', ' // we want to potentially allow many implementations of the splitting lalgorithm', ' abstract public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // this is here so the actual splitting algorithn can access the list and change the sphere', ' protected ArrayList <DataWrapper <KeyType, DataType>> getList () {', ' return myData;', ' }', ' ', ' // this is here so the splitting algorithm can modify the list and the sphere', ' protected void replaceGuts (AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> withMe) {', ' myData = withMe.myData;', ' myBoundingSphere = withMe.myBoundingSphere;', ' }', ' ', '}', '', '// this is a particular implementation of the metric data list that uses a simple quadratic clustering', '// algorithm to perform a list split. It picks two "seeds" (the most distant objects) and then repeatedly', '// adds to the two new lists by choosing the objects closest to the seeds', 'class ChrisMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> extends AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> {', '', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo () {', ' ', ' // first, we need to find the two most distant points in the list', ' ArrayList <DataWrapper <KeyType, DataType>> myData = getList ();', ' int bestI = 0, bestJ = 0;', ' double maxDist = -1.0;', ' for (int i = 0; i < myData.size (); i++) {', ' for (int j = i + 1; j < myData.size (); j++) {', ' ', ' // get the two keys', ' DataWrapper <KeyType, DataType> pointOne = myData.get (i);', ' DataWrapper <KeyType, DataType> pointTwo = myData.get (j);', ' ', ' // find the difference between them', ' double curDist = pointOne.getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', '', ' // see if it is the biggest', ' if (curDist > maxDist) {', ' maxDist = curDist;', ' bestI = i;', ' bestJ = j;', ' }', ' }', ' }', ' ', ' // now, we have the best two points; those are seeds for the clustering', ' DataWrapper <KeyType, DataType> pointOne = myData.remove (bestI);', ' DataWrapper <KeyType, DataType> pointTwo = myData.remove (bestJ - 1);', ' ', ' // these are the two new lists', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listOne = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listTwo = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' ', ' // put the two seeds in', ' listOne.add (pointOne.getKey (), pointOne.getData ());', ' listTwo.add (pointTwo.getKey (), pointTwo.getData ());', ' ', ' // and add everyone else in', ' while (myData.size () != 0) {', ' ', ' // find the one closest to the first seed', ' int bestIndex = 0;', ' double bestDist = 9e99;', ' ', ' // loop thru all of the candidate data objects', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listOne.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' ', ' // break if no more data', ' if (myData.size () == 0)', ' break;', ' ', ' // loop thru all of the candidate data objects', ' bestDist = 9e99;', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listTwo.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' }', ' ', ' // now we replace our own guts with the first list', ' replaceGuts (listOne);', ' ', ' // and return the other list', ' return listTwo;', ' }', '}', '', 'interface IMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> {', ' ', ' // add a new pair to the list', ' public void add (KeyType keyToAdd, DataType dataToAdd);', ' ', ' // replace a key at the indicated position', ' public void replaceKey (int pos, KeyType keyToAdd);', ' ', ' // get the key, data pair that resides at a particular position', ' public DataWrapper <KeyType, DataType> get (int pos);', ' ', ' // return the number of items in the list', ' public int size ();', ' ', ' // split the list in two, using some clutering algorithm', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // get a sphere that totally bounds all of the objects in the list', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class MTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public MTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class SCMTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public SCMTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', '', 'public class MTreeTester extends TestCase {', ' ', ' // compare two lists of strings to see if the contents are the same', ' private boolean compareStringSets (ArrayList <String> setOne, ArrayList <String> setTwo) {', ' ', ' // sort the sets and make sure they are the same', ' boolean returnVal = true;', ' if (setOne.size () == setTwo.size ()) {', ' Collections.sort (setOne);', ' Collections.sort (setTwo);', ' for (int i = 0; i < setOne.size (); i++) {', ' if (!setOne.get (i).equals (setTwo.get (i))) {', ' returnVal = false;', ' break; ', ' }', ' }', ' } else {', ' returnVal = false;', ' }', ' ', ' // print out the result', ' System.out.println ("**** Expected:");', ' for (int i = 0; i < setOne.size (); i++) {', ' System.out.format (setOne.get (i) + " ");', ' }', ' System.out.println ("\\n**** Got:");', ' for (int i = 0; i < setTwo.size (); i++) {', ' System.out.format (setTwo.get (i) + " ");', ' }', ' System.out.println ("");', ' ', ' return returnVal;', ' }', ' ', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST SIMPLE ONE DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testOneDimRangeQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.find (query, expectedQuerySize / 2);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.find (query, expectedQuerySize / 2);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (numPoints);', ' result1 = myTree.find (query, expectedQuerySize);', ' result2 = hisTree.find (query, expectedQuerySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // like the last one, but runs a top k', ' private void testOneDimTopKQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (167);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.findKClosest (query, querySize);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (0);', ' result1 = myTree.findKClosest (query, querySize);', ' result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST MULTI-DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimRangeQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' double dist1 = 0;', ' double dist2 = 0;', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' dist1 = Math.sqrt (numDims) * expectedQuerySize / 2.0;', ' dist2 = Math.sqrt (numDims) * expectedQuerySize;', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' // do a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, (int) expectedQuerySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = myTree.findKClosest (query2, (int) expectedQuerySize);', ' ', ' // find the distance to the furthest point in both cases', ' for (int i = 0; i < (int) expectedQuerySize; i++) {', ' double newDist = result1.get (i).getKey ().getDistance (query1);', ' if (newDist > dist1)', ' dist1 = newDist;', ' newDist = result2.get (i).getKey ().getDistance (query2);', ' if (newDist > dist2)', ' dist2 = newDist;', ' }', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.find (query1, dist1);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.find (query1, dist1);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.find (query2, dist2);', ' result2 = hisTree.find (query2, dist2);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimTopKQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, querySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.findKClosest (query1, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.findKClosest (query2, querySize);', ' result2 = hisTree.findKClosest (query2, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' ', ' /**', ' * "TIER 1" TESTS', ' * NONE OF THESE REQUIRE ANY SPLITS', ' */', ' public void testEasy1() {', ' testOneDimRangeQuery (true, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy2() {', ' testOneDimRangeQuery (false, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy3() {', ' testOneDimRangeQuery (true, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy4() {', ' testOneDimRangeQuery (false, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy5() {', ' testMultiDimRangeQuery (true, 1, 5, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy6() {', ' testMultiDimRangeQuery (false, 1, 10, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy7() {', ' testMultiDimRangeQuery (true, 1, 5, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy8() {', ' testMultiDimRangeQuery (false, 1, 15, 10000, 10000, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 2" TESTS', ' * NONE OF THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testMod1() {', ' testOneDimRangeQuery (true, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod2() {', ' testOneDimRangeQuery (false, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod3() {', ' testOneDimRangeQuery (true, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod4() {', ' testOneDimRangeQuery (false, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod5() {', ' testMultiDimRangeQuery (true, 2, 5, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod6() {', ' testMultiDimRangeQuery (false, 2, 10, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod7() {', ' testMultiDimRangeQuery (true, 2, 5, 10000, 100, 1000, 10);', ' }', ' ', ' public void testMod8() {', ' testMultiDimRangeQuery (false, 2, 15, 10000, 100, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 3" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testHard1() {', ' testOneDimRangeQuery (true, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard2() {', ' testOneDimRangeQuery (false, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard3() {', ' testOneDimRangeQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard4() {', ' testOneDimRangeQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard5() {', ' testMultiDimRangeQuery (true, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard6() {', ' testMultiDimRangeQuery (false, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard7() {', ' testMultiDimRangeQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard8() {', ' testMultiDimRangeQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', ' ', ' /**', ' * "TIER 4" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE AND THEY TEST THE TOPK FUNCTIONALITY', ' */', ' ', ' public void testTopK1() {', ' testOneDimTopKQuery (true, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK2() {', ' testOneDimTopKQuery (false, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK3() {', ' testOneDimTopKQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK4() {', ' testOneDimTopKQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK5() {', ' testMultiDimTopKQuery (true, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK6() {', ' testMultiDimTopKQuery (false, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK7() {', ' testMultiDimTopKQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK8() {', ' testMultiDimTopKQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', '}'] | [{'reason_category': 'Loop Body', 'usage_line': 527}, {'reason_category': 'If Body', 'usage_line': 527}, {'reason_category': 'Loop Body', 'usage_line': 528}, {'reason_category': 'If Body', 'usage_line': 528}] | Variable 'returnVal' used at line 527 is defined at line 522 and has a Short-Range dependency.
Global_Variable 'myData' used at line 527 is defined at line 454 and has a Long-Range dependency.
Variable 'i' used at line 527 is defined at line 525 and has a Short-Range dependency.
Function 'getData' used at line 527 is defined at line 443 and has a Long-Range dependency.
Function 'find' used at line 527 is defined at line 520 and has a Short-Range dependency.
Variable 'query' used at line 527 is defined at line 520 and has a Short-Range dependency. | {'Loop Body': 2, 'If Body': 2} | {'Variable Short-Range': 3, 'Global_Variable Long-Range': 1, 'Function Long-Range': 1, 'Function Short-Range': 1} |
infilling_java | MTreeTester | 526 | 529 | ['import junit.framework.TestCase;', 'import java.util.ArrayList;', 'import java.util.Random;', 'import java.util.Collections;', '', '// this is a map from a set of keys of type PointInMetricSpace to a', '// set of data of type DataType', 'interface IMTree <Key extends IPointInMetricSpace <Key>, Data> {', ' ', ' // insert a new key/data pair into the map', ' void insert (Key keyToAdd, Data dataToAdd);', ' ', ' // find all of the key/data pairs in the map that fall within a', ' // particular distance of query point if no results are found, then', ' // an empty array is returned (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> find (Key query, double distance);', ' ', ' // find the k closest key/data pairs in the map to a particular', ' // query point ', ' //', ' // if the number of points in the map is less than k, then the', ' // returned list will have less than k pairs in it', ' //', ' // if the number of points is zero, then an empty array is returned', ' // (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> findKClosest (Key query, int k);', ' ', ' // returns the number of nodes that exist on a path from root to leaf in the tree...', ' // whtever the details of the implementation are, a tree with a single leaf node should return 1, and a tree', ' // with more than one lead node should return at least two (since it must have at least one internal node).', ' public int depth ();', ' ', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', '', 'interface IDoubleVector {', '', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '', '// this correponds to some geometric object in a metric space; the object is built out of', '// one or more points of type PointInMetricSpace', 'interface IObjectInMetricSpaceABCD <PointInMetricSpace extends IPointInMetricSpace<PointInMetricSpace>> {', ' ', ' // get the maximum distance from some point on the shape to a particular point in the metric space', ' double maxDistanceTo (PointInMetricSpace checkMe);', ' ', ' // return some arbitrary point on the interior of the geometric object', ' PointInMetricSpace getPointInInterior ();', '}', '', '', '// this interface corresponds to a point in some metric space', 'interface IPointInMetricSpace <PointInMetricSpace> {', ' ', ' // get the distance to another point', ' // ', ' // for this to work in an M-Tree, distances should be "metric" and', ' // obey the triangle inequality', ' double getDistance (PointInMetricSpace toMe);', '}', '', '// this is the basic node type in the structure', 'interface IMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> {', ' ', ' // insert a new key/data pair into the structure. The return value is a new MTreeNode if there was', ' // a split in response to the insertion, or a null if there was no split', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd);', ' ', ' // find all of the key/data pairs in the structure that fall within a particular query sphere', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query); ', ' ', ' // find the set of items closest to the given query point', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ);', ' ', ' // returns a sphere that totally encompasses everything in the node and its subtree', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', ' ', ' // returns the depth', ' public int depth ();', '}', '', '// this is a point in a particular metric space', 'class PointABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the point', ' private PointInMetricSpace me;', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return me; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return checkMe.getDistance (me); ', ' }', ' ', ' // contruct a point', ' public PointABCD (PointInMetricSpace useMe) {', ' me = useMe; ', ' }', '}', '', 'class PQueueABCD <PointInMetricSpace, DataType> {', ' ', ' // this is an object in the queue', ' private class Wrapper {', ' DataWrapper <PointInMetricSpace, DataType> myData;', ' double distance;', ' }', ' ', ' // this is the actual queue', ' ArrayList <Wrapper> myList;', ' ', ' // this is the largest distance value currently in the queue', ' double large;', ' ', ' // this is the max number of objects', ' int maxCount;', ' ', ' // create a priority queue with the speced number of slots', ' PQueueABCD (int maxCountIn) {', ' maxCount = maxCountIn;', ' myList = new ArrayList <Wrapper> ();', ' large = 9e99;', ' }', ' ', ' // get the largest distance in the queue', ' double getDist () {', ' return large;', ' }', ' ', ' // add a new object to the queue... the insertion is ignored if the distance value', ' // exceeds the largest that is in the queue and the queue is already full', ' void insert (PointInMetricSpace key, DataType data, double distance) {', ' ', ' // if we are full, remove the one with the largest distance', ' if (myList.size () == maxCount && distance < large) {', ' ', ' int badIndex = 0;', ' double maxDist = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > maxDist) {', ' maxDist = myList.get (i).distance;', ' badIndex = i;', ' }', ' }', ' ', ' myList.remove (badIndex);', ' }', ' ', ' // see if there is room', ' if (myList.size () < maxCount) {', ' ', ' // add it ', ' Wrapper newOne = new Wrapper ();', ' newOne.myData = new DataWrapper <PointInMetricSpace, DataType> (key, data);', ' newOne.distance = distance;', ' myList.add (newOne); ', ' }', ' ', ' // if we are full, reset the max distance', ' if (myList.size () == maxCount) {', ' large = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > large) {', ' large = myList.get (i).distance;', ' }', ' }', ' }', ' ', ' }', ' ', ' // extracts the contents of the queue', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> done () {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' for (int i = 0; i < myList.size (); i++) {', ' returnVal.add (myList.get (i).myData); ', ' }', ' ', ' return returnVal;', ' }', ' ', '}', '', '// this is a sphere in a particular metric space', 'class SphereABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the center of the sphere and its radius', ' private PointInMetricSpace center;', ' private double radius;', ' ', ' // build a sphere out of its center and its radius', ' public SphereABCD (PointInMetricSpace centerIn, double radiusIn) {', ' center = centerIn;', ' radius = radiusIn;', ' }', ' ', ' // increase the size of the sphere so it contains the object swallowMe', ' public void swallow (IObjectInMetricSpaceABCD <PointInMetricSpace> swallowMe) {', ' ', ' // see if we need to increase the radius to swallow this guy', ' double dist = swallowMe.maxDistanceTo (center);', ' if (dist > radius)', ' radius = dist;', ' }', ' ', ' // check to see if a sphere intersects another sphere', ' public boolean intersects (SphereABCD <PointInMetricSpace> me) {', ' return (me.center.getDistance (center) <= me.radius + radius);', ' }', ' ', ' // check to see if the sphere contains a point', ' public boolean contains (PointInMetricSpace checkMe) {', ' return (checkMe.getDistance (center) <= radius);', ' }', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return center; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return radius + checkMe.getDistance (center); ', ' }', '}', '', '', '', 'class OneDimPoint implements IPointInMetricSpace <OneDimPoint> {', ' ', ' // this is the actual double', ' Double value;', ' ', ' // construct this out of a double value', ' public OneDimPoint (double makeFromMe) {', ' value = new Double (makeFromMe);', ' }', ' ', ' // get the distance to another point', ' public double getDistance (OneDimPoint toMe) {', ' if (value > toMe.value)', ' return value - toMe.value;', ' else', ' return toMe.value - value;', ' }', ' ', '}', '', 'class MultiDimPoint implements IPointInMetricSpace <MultiDimPoint> {', ' ', ' // this is the point in a multidimensional space', ' IDoubleVector me;', ' ', ' // make this out of an IDoubleVector', ' public MultiDimPoint (IDoubleVector useMe) {', ' me = useMe;', ' }', ' ', ' // get the Euclidean distance to another point', ' public double getDistance (MultiDimPoint toMe) {', ' double distance = 0.0;', ' try {', ' for (int i = 0; i < me.getLength (); i++) {', ' double diff = me.getItem (i) - toMe.me.getItem (i);', ' diff *= diff;', ' distance += diff;', ' }', ' } catch (OutOfBoundsException e) {', ' throw new IndexOutOfBoundsException ("Can\'t compare two MultiDimPoint objects with different dimensionality!"); ', ' }', ' return Math.sqrt(distance);', ' }', ' ', '}', '// this is a leaf node', 'class LeafMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements ', ' IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myData;', ' ', ' // contructor that takes a data list and builds a node out of it', ' private LeafMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myDataIn) {', ' myData = myDataIn; ', ' }', ' ', ' // constructor that creates an empty node', ' public LeafMTreeNodeABCD () {', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> (); ', ' }', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // just add in the new data', ' myData.add (new PointABCD <PointInMetricSpace> (keyToAdd), dataToAdd);', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> newOne = myData.splitInTwo ();', ' LeafMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' myQ.insert (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData (), ', ' query.getDistance (myData.get (i).getKey ().getPointInInterior ()));', ' }', ' }', ' }', ' ', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' returnVal.add (new DataWrapper <PointInMetricSpace, DataType> (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData ()));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return 1; ', ' }', '', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', '// this silly little class is just a wrapper for a key, data pair', 'class DataWrapper <Key, Data> {', ' ', ' Key key;', ' Data data;', ' ', ' public DataWrapper (Key keyIn, Data dataIn) {', ' key = keyIn;', ' data = dataIn;', ' }', ' ', ' public Key getKey () {', ' return key;', ' }', ' ', ' public Data getData () {', ' return data;', ' }', '}', '', '', '// this is an internal node', 'class InternalMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType>', ' implements IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> myData;', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' // this constructs a new internal node that holds precisely the two nodes that are passed in', ' public InternalMTreeNodeABCD (IMTreeNodeABCD <PointInMetricSpace, DataType> refOne,', ' IMTreeNodeABCD <PointInMetricSpace, DataType> refTwo) {', ' ', ' // create a necw list and add the two guys in', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> ();', ' myData.add (refOne.getBoundingSphere (), refOne);', ' myData.add (refTwo.getBoundingSphere (), refTwo);', ' }', ' ', ' // this constructs a new node that holds the list of data that we were passed in', ' public InternalMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> useMe) {', ' myData = useMe; ', ' }', ' ', ' // from the interface', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // find the best child; this is the one we are closest to', ' double bestDist = 9e99;', ' int bestIndex = 0;', ' for (int i = 0; i < myData.size (); i++) {', ' ', ' double newDist = myData.get (i).getKey ().getPointInInterior ().getDistance (keyToAdd);', ' if (newDist < bestDist) {', ' bestDist = newDist;', ' bestIndex = i;', ' }', ' }', ' ', ' // do the recursive insert', ' IMTreeNodeABCD <PointInMetricSpace, DataType> newRef = myData.get (bestIndex).getData ().insert (keyToAdd, dataToAdd);', ' ', ' // if we got something back, then there was a split, so add the new node into our list', ' if (newRef != null) {', ' myData.add (newRef.getBoundingSphere (), newRef);', ' }', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> newOne = myData.splitInTwo ();', ' InternalMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.intersects (myData.get (i).getKey ())) {', ' myData.get (i).getData ().findKClosest (query, myQ);', ' }', ' }', ' }', ' ', ' // from the interface', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {'] | [' if (query.intersects (myData.get (i).getKey ())) {', ' returnVal.addAll (myData.get (i).getData ().find (query));', ' }', ' }'] | [' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return myData.get (0).getData ().depth () + 1; ', ' }', ' ', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', 'abstract class AMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> implements IMetricDataListABCD <PointInMetricSpace,KeyType, DataType> {', '', ' // this is the data that is actually stored in the list', ' private ArrayList <DataWrapper <KeyType, DataType>> myData;', ' ', ' // this is the sphere that bounds everything in the list', ' private SphereABCD <PointInMetricSpace> myBoundingSphere;', ' ', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myBoundingSphere; ', ' }', ' ', ' public int size () {', ' if (myData != null)', ' return myData.size (); ', ' else', ' return 0;', ' }', ' ', ' public DataWrapper <KeyType, DataType> get (int pos) {', ' return myData.get (pos);', ' }', ' ', ' public void replaceKey (int pos, KeyType keyToAdd) {', ' DataWrapper <KeyType, DataType> temp = myData.remove (pos);', ' DataWrapper <KeyType, DataType> newOne = new DataWrapper <KeyType, DataType> (keyToAdd, temp.getData ());', ' myData.add (pos, newOne);', ' }', ' ', ' public void add (KeyType keyToAdd, DataType dataToAdd) {', ' ', ' // if this is the first add, then set everyone up', ' if (myData == null) {', ' PointInMetricSpace myCentroid = keyToAdd.getPointInInterior ();', ' myBoundingSphere = new SphereABCD <PointInMetricSpace> (myCentroid, keyToAdd.maxDistanceTo (myCentroid));', ' myData = new ArrayList <DataWrapper <KeyType, DataType>> ();', ' ', ' // otherwise, extend the sphere if needed', ' } else {', ' myBoundingSphere.swallow (keyToAdd);', ' }', ' ', ' // add the data', ' myData.add (new DataWrapper <KeyType, DataType> (keyToAdd, dataToAdd));', ' }', ' ', ' // we want to potentially allow many implementations of the splitting lalgorithm', ' abstract public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // this is here so the actual splitting algorithn can access the list and change the sphere', ' protected ArrayList <DataWrapper <KeyType, DataType>> getList () {', ' return myData;', ' }', ' ', ' // this is here so the splitting algorithm can modify the list and the sphere', ' protected void replaceGuts (AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> withMe) {', ' myData = withMe.myData;', ' myBoundingSphere = withMe.myBoundingSphere;', ' }', ' ', '}', '', '// this is a particular implementation of the metric data list that uses a simple quadratic clustering', '// algorithm to perform a list split. It picks two "seeds" (the most distant objects) and then repeatedly', '// adds to the two new lists by choosing the objects closest to the seeds', 'class ChrisMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> extends AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> {', '', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo () {', ' ', ' // first, we need to find the two most distant points in the list', ' ArrayList <DataWrapper <KeyType, DataType>> myData = getList ();', ' int bestI = 0, bestJ = 0;', ' double maxDist = -1.0;', ' for (int i = 0; i < myData.size (); i++) {', ' for (int j = i + 1; j < myData.size (); j++) {', ' ', ' // get the two keys', ' DataWrapper <KeyType, DataType> pointOne = myData.get (i);', ' DataWrapper <KeyType, DataType> pointTwo = myData.get (j);', ' ', ' // find the difference between them', ' double curDist = pointOne.getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', '', ' // see if it is the biggest', ' if (curDist > maxDist) {', ' maxDist = curDist;', ' bestI = i;', ' bestJ = j;', ' }', ' }', ' }', ' ', ' // now, we have the best two points; those are seeds for the clustering', ' DataWrapper <KeyType, DataType> pointOne = myData.remove (bestI);', ' DataWrapper <KeyType, DataType> pointTwo = myData.remove (bestJ - 1);', ' ', ' // these are the two new lists', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listOne = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listTwo = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' ', ' // put the two seeds in', ' listOne.add (pointOne.getKey (), pointOne.getData ());', ' listTwo.add (pointTwo.getKey (), pointTwo.getData ());', ' ', ' // and add everyone else in', ' while (myData.size () != 0) {', ' ', ' // find the one closest to the first seed', ' int bestIndex = 0;', ' double bestDist = 9e99;', ' ', ' // loop thru all of the candidate data objects', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listOne.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' ', ' // break if no more data', ' if (myData.size () == 0)', ' break;', ' ', ' // loop thru all of the candidate data objects', ' bestDist = 9e99;', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listTwo.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' }', ' ', ' // now we replace our own guts with the first list', ' replaceGuts (listOne);', ' ', ' // and return the other list', ' return listTwo;', ' }', '}', '', 'interface IMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> {', ' ', ' // add a new pair to the list', ' public void add (KeyType keyToAdd, DataType dataToAdd);', ' ', ' // replace a key at the indicated position', ' public void replaceKey (int pos, KeyType keyToAdd);', ' ', ' // get the key, data pair that resides at a particular position', ' public DataWrapper <KeyType, DataType> get (int pos);', ' ', ' // return the number of items in the list', ' public int size ();', ' ', ' // split the list in two, using some clutering algorithm', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // get a sphere that totally bounds all of the objects in the list', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class MTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public MTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class SCMTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public SCMTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', '', 'public class MTreeTester extends TestCase {', ' ', ' // compare two lists of strings to see if the contents are the same', ' private boolean compareStringSets (ArrayList <String> setOne, ArrayList <String> setTwo) {', ' ', ' // sort the sets and make sure they are the same', ' boolean returnVal = true;', ' if (setOne.size () == setTwo.size ()) {', ' Collections.sort (setOne);', ' Collections.sort (setTwo);', ' for (int i = 0; i < setOne.size (); i++) {', ' if (!setOne.get (i).equals (setTwo.get (i))) {', ' returnVal = false;', ' break; ', ' }', ' }', ' } else {', ' returnVal = false;', ' }', ' ', ' // print out the result', ' System.out.println ("**** Expected:");', ' for (int i = 0; i < setOne.size (); i++) {', ' System.out.format (setOne.get (i) + " ");', ' }', ' System.out.println ("\\n**** Got:");', ' for (int i = 0; i < setTwo.size (); i++) {', ' System.out.format (setTwo.get (i) + " ");', ' }', ' System.out.println ("");', ' ', ' return returnVal;', ' }', ' ', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST SIMPLE ONE DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testOneDimRangeQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.find (query, expectedQuerySize / 2);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.find (query, expectedQuerySize / 2);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (numPoints);', ' result1 = myTree.find (query, expectedQuerySize);', ' result2 = hisTree.find (query, expectedQuerySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // like the last one, but runs a top k', ' private void testOneDimTopKQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (167);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.findKClosest (query, querySize);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (0);', ' result1 = myTree.findKClosest (query, querySize);', ' result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST MULTI-DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimRangeQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' double dist1 = 0;', ' double dist2 = 0;', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' dist1 = Math.sqrt (numDims) * expectedQuerySize / 2.0;', ' dist2 = Math.sqrt (numDims) * expectedQuerySize;', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' // do a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, (int) expectedQuerySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = myTree.findKClosest (query2, (int) expectedQuerySize);', ' ', ' // find the distance to the furthest point in both cases', ' for (int i = 0; i < (int) expectedQuerySize; i++) {', ' double newDist = result1.get (i).getKey ().getDistance (query1);', ' if (newDist > dist1)', ' dist1 = newDist;', ' newDist = result2.get (i).getKey ().getDistance (query2);', ' if (newDist > dist2)', ' dist2 = newDist;', ' }', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.find (query1, dist1);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.find (query1, dist1);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.find (query2, dist2);', ' result2 = hisTree.find (query2, dist2);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimTopKQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, querySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.findKClosest (query1, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.findKClosest (query2, querySize);', ' result2 = hisTree.findKClosest (query2, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' ', ' /**', ' * "TIER 1" TESTS', ' * NONE OF THESE REQUIRE ANY SPLITS', ' */', ' public void testEasy1() {', ' testOneDimRangeQuery (true, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy2() {', ' testOneDimRangeQuery (false, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy3() {', ' testOneDimRangeQuery (true, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy4() {', ' testOneDimRangeQuery (false, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy5() {', ' testMultiDimRangeQuery (true, 1, 5, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy6() {', ' testMultiDimRangeQuery (false, 1, 10, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy7() {', ' testMultiDimRangeQuery (true, 1, 5, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy8() {', ' testMultiDimRangeQuery (false, 1, 15, 10000, 10000, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 2" TESTS', ' * NONE OF THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testMod1() {', ' testOneDimRangeQuery (true, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod2() {', ' testOneDimRangeQuery (false, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod3() {', ' testOneDimRangeQuery (true, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod4() {', ' testOneDimRangeQuery (false, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod5() {', ' testMultiDimRangeQuery (true, 2, 5, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod6() {', ' testMultiDimRangeQuery (false, 2, 10, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod7() {', ' testMultiDimRangeQuery (true, 2, 5, 10000, 100, 1000, 10);', ' }', ' ', ' public void testMod8() {', ' testMultiDimRangeQuery (false, 2, 15, 10000, 100, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 3" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testHard1() {', ' testOneDimRangeQuery (true, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard2() {', ' testOneDimRangeQuery (false, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard3() {', ' testOneDimRangeQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard4() {', ' testOneDimRangeQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard5() {', ' testMultiDimRangeQuery (true, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard6() {', ' testMultiDimRangeQuery (false, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard7() {', ' testMultiDimRangeQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard8() {', ' testMultiDimRangeQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', ' ', ' /**', ' * "TIER 4" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE AND THEY TEST THE TOPK FUNCTIONALITY', ' */', ' ', ' public void testTopK1() {', ' testOneDimTopKQuery (true, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK2() {', ' testOneDimTopKQuery (false, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK3() {', ' testOneDimTopKQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK4() {', ' testOneDimTopKQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK5() {', ' testMultiDimTopKQuery (true, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK6() {', ' testMultiDimTopKQuery (false, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK7() {', ' testMultiDimTopKQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK8() {', ' testMultiDimTopKQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', '}'] | [{'reason_category': 'Loop Body', 'usage_line': 526}, {'reason_category': 'If Condition', 'usage_line': 526}, {'reason_category': 'Loop Body', 'usage_line': 527}, {'reason_category': 'If Body', 'usage_line': 527}, {'reason_category': 'Loop Body', 'usage_line': 528}, {'reason_category': 'If Body', 'usage_line': 528}, {'reason_category': 'Loop Body', 'usage_line': 529}] | Variable 'query' used at line 526 is defined at line 520 and has a Short-Range dependency.
Global_Variable 'myData' used at line 526 is defined at line 454 and has a Long-Range dependency.
Variable 'i' used at line 526 is defined at line 525 and has a Short-Range dependency.
Function 'getKey' used at line 526 is defined at line 439 and has a Long-Range dependency.
Variable 'returnVal' used at line 527 is defined at line 522 and has a Short-Range dependency.
Global_Variable 'myData' used at line 527 is defined at line 454 and has a Long-Range dependency.
Variable 'i' used at line 527 is defined at line 525 and has a Short-Range dependency.
Function 'getData' used at line 527 is defined at line 443 and has a Long-Range dependency.
Function 'find' used at line 527 is defined at line 520 and has a Short-Range dependency.
Variable 'query' used at line 527 is defined at line 520 and has a Short-Range dependency. | {'Loop Body': 4, 'If Condition': 1, 'If Body': 2} | {'Variable Short-Range': 5, 'Global_Variable Long-Range': 2, 'Function Long-Range': 2, 'Function Short-Range': 1} |
infilling_java | MTreeTester | 535 | 536 | ['import junit.framework.TestCase;', 'import java.util.ArrayList;', 'import java.util.Random;', 'import java.util.Collections;', '', '// this is a map from a set of keys of type PointInMetricSpace to a', '// set of data of type DataType', 'interface IMTree <Key extends IPointInMetricSpace <Key>, Data> {', ' ', ' // insert a new key/data pair into the map', ' void insert (Key keyToAdd, Data dataToAdd);', ' ', ' // find all of the key/data pairs in the map that fall within a', ' // particular distance of query point if no results are found, then', ' // an empty array is returned (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> find (Key query, double distance);', ' ', ' // find the k closest key/data pairs in the map to a particular', ' // query point ', ' //', ' // if the number of points in the map is less than k, then the', ' // returned list will have less than k pairs in it', ' //', ' // if the number of points is zero, then an empty array is returned', ' // (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> findKClosest (Key query, int k);', ' ', ' // returns the number of nodes that exist on a path from root to leaf in the tree...', ' // whtever the details of the implementation are, a tree with a single leaf node should return 1, and a tree', ' // with more than one lead node should return at least two (since it must have at least one internal node).', ' public int depth ();', ' ', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', '', 'interface IDoubleVector {', '', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '', '// this correponds to some geometric object in a metric space; the object is built out of', '// one or more points of type PointInMetricSpace', 'interface IObjectInMetricSpaceABCD <PointInMetricSpace extends IPointInMetricSpace<PointInMetricSpace>> {', ' ', ' // get the maximum distance from some point on the shape to a particular point in the metric space', ' double maxDistanceTo (PointInMetricSpace checkMe);', ' ', ' // return some arbitrary point on the interior of the geometric object', ' PointInMetricSpace getPointInInterior ();', '}', '', '', '// this interface corresponds to a point in some metric space', 'interface IPointInMetricSpace <PointInMetricSpace> {', ' ', ' // get the distance to another point', ' // ', ' // for this to work in an M-Tree, distances should be "metric" and', ' // obey the triangle inequality', ' double getDistance (PointInMetricSpace toMe);', '}', '', '// this is the basic node type in the structure', 'interface IMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> {', ' ', ' // insert a new key/data pair into the structure. The return value is a new MTreeNode if there was', ' // a split in response to the insertion, or a null if there was no split', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd);', ' ', ' // find all of the key/data pairs in the structure that fall within a particular query sphere', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query); ', ' ', ' // find the set of items closest to the given query point', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ);', ' ', ' // returns a sphere that totally encompasses everything in the node and its subtree', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', ' ', ' // returns the depth', ' public int depth ();', '}', '', '// this is a point in a particular metric space', 'class PointABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the point', ' private PointInMetricSpace me;', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return me; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return checkMe.getDistance (me); ', ' }', ' ', ' // contruct a point', ' public PointABCD (PointInMetricSpace useMe) {', ' me = useMe; ', ' }', '}', '', 'class PQueueABCD <PointInMetricSpace, DataType> {', ' ', ' // this is an object in the queue', ' private class Wrapper {', ' DataWrapper <PointInMetricSpace, DataType> myData;', ' double distance;', ' }', ' ', ' // this is the actual queue', ' ArrayList <Wrapper> myList;', ' ', ' // this is the largest distance value currently in the queue', ' double large;', ' ', ' // this is the max number of objects', ' int maxCount;', ' ', ' // create a priority queue with the speced number of slots', ' PQueueABCD (int maxCountIn) {', ' maxCount = maxCountIn;', ' myList = new ArrayList <Wrapper> ();', ' large = 9e99;', ' }', ' ', ' // get the largest distance in the queue', ' double getDist () {', ' return large;', ' }', ' ', ' // add a new object to the queue... the insertion is ignored if the distance value', ' // exceeds the largest that is in the queue and the queue is already full', ' void insert (PointInMetricSpace key, DataType data, double distance) {', ' ', ' // if we are full, remove the one with the largest distance', ' if (myList.size () == maxCount && distance < large) {', ' ', ' int badIndex = 0;', ' double maxDist = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > maxDist) {', ' maxDist = myList.get (i).distance;', ' badIndex = i;', ' }', ' }', ' ', ' myList.remove (badIndex);', ' }', ' ', ' // see if there is room', ' if (myList.size () < maxCount) {', ' ', ' // add it ', ' Wrapper newOne = new Wrapper ();', ' newOne.myData = new DataWrapper <PointInMetricSpace, DataType> (key, data);', ' newOne.distance = distance;', ' myList.add (newOne); ', ' }', ' ', ' // if we are full, reset the max distance', ' if (myList.size () == maxCount) {', ' large = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > large) {', ' large = myList.get (i).distance;', ' }', ' }', ' }', ' ', ' }', ' ', ' // extracts the contents of the queue', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> done () {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' for (int i = 0; i < myList.size (); i++) {', ' returnVal.add (myList.get (i).myData); ', ' }', ' ', ' return returnVal;', ' }', ' ', '}', '', '// this is a sphere in a particular metric space', 'class SphereABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the center of the sphere and its radius', ' private PointInMetricSpace center;', ' private double radius;', ' ', ' // build a sphere out of its center and its radius', ' public SphereABCD (PointInMetricSpace centerIn, double radiusIn) {', ' center = centerIn;', ' radius = radiusIn;', ' }', ' ', ' // increase the size of the sphere so it contains the object swallowMe', ' public void swallow (IObjectInMetricSpaceABCD <PointInMetricSpace> swallowMe) {', ' ', ' // see if we need to increase the radius to swallow this guy', ' double dist = swallowMe.maxDistanceTo (center);', ' if (dist > radius)', ' radius = dist;', ' }', ' ', ' // check to see if a sphere intersects another sphere', ' public boolean intersects (SphereABCD <PointInMetricSpace> me) {', ' return (me.center.getDistance (center) <= me.radius + radius);', ' }', ' ', ' // check to see if the sphere contains a point', ' public boolean contains (PointInMetricSpace checkMe) {', ' return (checkMe.getDistance (center) <= radius);', ' }', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return center; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return radius + checkMe.getDistance (center); ', ' }', '}', '', '', '', 'class OneDimPoint implements IPointInMetricSpace <OneDimPoint> {', ' ', ' // this is the actual double', ' Double value;', ' ', ' // construct this out of a double value', ' public OneDimPoint (double makeFromMe) {', ' value = new Double (makeFromMe);', ' }', ' ', ' // get the distance to another point', ' public double getDistance (OneDimPoint toMe) {', ' if (value > toMe.value)', ' return value - toMe.value;', ' else', ' return toMe.value - value;', ' }', ' ', '}', '', 'class MultiDimPoint implements IPointInMetricSpace <MultiDimPoint> {', ' ', ' // this is the point in a multidimensional space', ' IDoubleVector me;', ' ', ' // make this out of an IDoubleVector', ' public MultiDimPoint (IDoubleVector useMe) {', ' me = useMe;', ' }', ' ', ' // get the Euclidean distance to another point', ' public double getDistance (MultiDimPoint toMe) {', ' double distance = 0.0;', ' try {', ' for (int i = 0; i < me.getLength (); i++) {', ' double diff = me.getItem (i) - toMe.me.getItem (i);', ' diff *= diff;', ' distance += diff;', ' }', ' } catch (OutOfBoundsException e) {', ' throw new IndexOutOfBoundsException ("Can\'t compare two MultiDimPoint objects with different dimensionality!"); ', ' }', ' return Math.sqrt(distance);', ' }', ' ', '}', '// this is a leaf node', 'class LeafMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements ', ' IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myData;', ' ', ' // contructor that takes a data list and builds a node out of it', ' private LeafMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myDataIn) {', ' myData = myDataIn; ', ' }', ' ', ' // constructor that creates an empty node', ' public LeafMTreeNodeABCD () {', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> (); ', ' }', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // just add in the new data', ' myData.add (new PointABCD <PointInMetricSpace> (keyToAdd), dataToAdd);', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> newOne = myData.splitInTwo ();', ' LeafMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' myQ.insert (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData (), ', ' query.getDistance (myData.get (i).getKey ().getPointInInterior ()));', ' }', ' }', ' }', ' ', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' returnVal.add (new DataWrapper <PointInMetricSpace, DataType> (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData ()));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return 1; ', ' }', '', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', '// this silly little class is just a wrapper for a key, data pair', 'class DataWrapper <Key, Data> {', ' ', ' Key key;', ' Data data;', ' ', ' public DataWrapper (Key keyIn, Data dataIn) {', ' key = keyIn;', ' data = dataIn;', ' }', ' ', ' public Key getKey () {', ' return key;', ' }', ' ', ' public Data getData () {', ' return data;', ' }', '}', '', '', '// this is an internal node', 'class InternalMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType>', ' implements IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> myData;', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' // this constructs a new internal node that holds precisely the two nodes that are passed in', ' public InternalMTreeNodeABCD (IMTreeNodeABCD <PointInMetricSpace, DataType> refOne,', ' IMTreeNodeABCD <PointInMetricSpace, DataType> refTwo) {', ' ', ' // create a necw list and add the two guys in', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> ();', ' myData.add (refOne.getBoundingSphere (), refOne);', ' myData.add (refTwo.getBoundingSphere (), refTwo);', ' }', ' ', ' // this constructs a new node that holds the list of data that we were passed in', ' public InternalMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> useMe) {', ' myData = useMe; ', ' }', ' ', ' // from the interface', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // find the best child; this is the one we are closest to', ' double bestDist = 9e99;', ' int bestIndex = 0;', ' for (int i = 0; i < myData.size (); i++) {', ' ', ' double newDist = myData.get (i).getKey ().getPointInInterior ().getDistance (keyToAdd);', ' if (newDist < bestDist) {', ' bestDist = newDist;', ' bestIndex = i;', ' }', ' }', ' ', ' // do the recursive insert', ' IMTreeNodeABCD <PointInMetricSpace, DataType> newRef = myData.get (bestIndex).getData ().insert (keyToAdd, dataToAdd);', ' ', ' // if we got something back, then there was a split, so add the new node into our list', ' if (newRef != null) {', ' myData.add (newRef.getBoundingSphere (), newRef);', ' }', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> newOne = myData.splitInTwo ();', ' InternalMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.intersects (myData.get (i).getKey ())) {', ' myData.get (i).getData ().findKClosest (query, myQ);', ' }', ' }', ' }', ' ', ' // from the interface', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.intersects (myData.get (i).getKey ())) {', ' returnVal.addAll (myData.get (i).getData ().find (query));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {'] | [' return myData.get (0).getData ().depth () + 1; ', ' }'] | [' ', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', 'abstract class AMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> implements IMetricDataListABCD <PointInMetricSpace,KeyType, DataType> {', '', ' // this is the data that is actually stored in the list', ' private ArrayList <DataWrapper <KeyType, DataType>> myData;', ' ', ' // this is the sphere that bounds everything in the list', ' private SphereABCD <PointInMetricSpace> myBoundingSphere;', ' ', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myBoundingSphere; ', ' }', ' ', ' public int size () {', ' if (myData != null)', ' return myData.size (); ', ' else', ' return 0;', ' }', ' ', ' public DataWrapper <KeyType, DataType> get (int pos) {', ' return myData.get (pos);', ' }', ' ', ' public void replaceKey (int pos, KeyType keyToAdd) {', ' DataWrapper <KeyType, DataType> temp = myData.remove (pos);', ' DataWrapper <KeyType, DataType> newOne = new DataWrapper <KeyType, DataType> (keyToAdd, temp.getData ());', ' myData.add (pos, newOne);', ' }', ' ', ' public void add (KeyType keyToAdd, DataType dataToAdd) {', ' ', ' // if this is the first add, then set everyone up', ' if (myData == null) {', ' PointInMetricSpace myCentroid = keyToAdd.getPointInInterior ();', ' myBoundingSphere = new SphereABCD <PointInMetricSpace> (myCentroid, keyToAdd.maxDistanceTo (myCentroid));', ' myData = new ArrayList <DataWrapper <KeyType, DataType>> ();', ' ', ' // otherwise, extend the sphere if needed', ' } else {', ' myBoundingSphere.swallow (keyToAdd);', ' }', ' ', ' // add the data', ' myData.add (new DataWrapper <KeyType, DataType> (keyToAdd, dataToAdd));', ' }', ' ', ' // we want to potentially allow many implementations of the splitting lalgorithm', ' abstract public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // this is here so the actual splitting algorithn can access the list and change the sphere', ' protected ArrayList <DataWrapper <KeyType, DataType>> getList () {', ' return myData;', ' }', ' ', ' // this is here so the splitting algorithm can modify the list and the sphere', ' protected void replaceGuts (AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> withMe) {', ' myData = withMe.myData;', ' myBoundingSphere = withMe.myBoundingSphere;', ' }', ' ', '}', '', '// this is a particular implementation of the metric data list that uses a simple quadratic clustering', '// algorithm to perform a list split. It picks two "seeds" (the most distant objects) and then repeatedly', '// adds to the two new lists by choosing the objects closest to the seeds', 'class ChrisMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> extends AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> {', '', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo () {', ' ', ' // first, we need to find the two most distant points in the list', ' ArrayList <DataWrapper <KeyType, DataType>> myData = getList ();', ' int bestI = 0, bestJ = 0;', ' double maxDist = -1.0;', ' for (int i = 0; i < myData.size (); i++) {', ' for (int j = i + 1; j < myData.size (); j++) {', ' ', ' // get the two keys', ' DataWrapper <KeyType, DataType> pointOne = myData.get (i);', ' DataWrapper <KeyType, DataType> pointTwo = myData.get (j);', ' ', ' // find the difference between them', ' double curDist = pointOne.getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', '', ' // see if it is the biggest', ' if (curDist > maxDist) {', ' maxDist = curDist;', ' bestI = i;', ' bestJ = j;', ' }', ' }', ' }', ' ', ' // now, we have the best two points; those are seeds for the clustering', ' DataWrapper <KeyType, DataType> pointOne = myData.remove (bestI);', ' DataWrapper <KeyType, DataType> pointTwo = myData.remove (bestJ - 1);', ' ', ' // these are the two new lists', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listOne = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listTwo = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' ', ' // put the two seeds in', ' listOne.add (pointOne.getKey (), pointOne.getData ());', ' listTwo.add (pointTwo.getKey (), pointTwo.getData ());', ' ', ' // and add everyone else in', ' while (myData.size () != 0) {', ' ', ' // find the one closest to the first seed', ' int bestIndex = 0;', ' double bestDist = 9e99;', ' ', ' // loop thru all of the candidate data objects', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listOne.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' ', ' // break if no more data', ' if (myData.size () == 0)', ' break;', ' ', ' // loop thru all of the candidate data objects', ' bestDist = 9e99;', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listTwo.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' }', ' ', ' // now we replace our own guts with the first list', ' replaceGuts (listOne);', ' ', ' // and return the other list', ' return listTwo;', ' }', '}', '', 'interface IMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> {', ' ', ' // add a new pair to the list', ' public void add (KeyType keyToAdd, DataType dataToAdd);', ' ', ' // replace a key at the indicated position', ' public void replaceKey (int pos, KeyType keyToAdd);', ' ', ' // get the key, data pair that resides at a particular position', ' public DataWrapper <KeyType, DataType> get (int pos);', ' ', ' // return the number of items in the list', ' public int size ();', ' ', ' // split the list in two, using some clutering algorithm', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // get a sphere that totally bounds all of the objects in the list', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class MTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public MTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class SCMTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public SCMTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', '', 'public class MTreeTester extends TestCase {', ' ', ' // compare two lists of strings to see if the contents are the same', ' private boolean compareStringSets (ArrayList <String> setOne, ArrayList <String> setTwo) {', ' ', ' // sort the sets and make sure they are the same', ' boolean returnVal = true;', ' if (setOne.size () == setTwo.size ()) {', ' Collections.sort (setOne);', ' Collections.sort (setTwo);', ' for (int i = 0; i < setOne.size (); i++) {', ' if (!setOne.get (i).equals (setTwo.get (i))) {', ' returnVal = false;', ' break; ', ' }', ' }', ' } else {', ' returnVal = false;', ' }', ' ', ' // print out the result', ' System.out.println ("**** Expected:");', ' for (int i = 0; i < setOne.size (); i++) {', ' System.out.format (setOne.get (i) + " ");', ' }', ' System.out.println ("\\n**** Got:");', ' for (int i = 0; i < setTwo.size (); i++) {', ' System.out.format (setTwo.get (i) + " ");', ' }', ' System.out.println ("");', ' ', ' return returnVal;', ' }', ' ', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST SIMPLE ONE DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testOneDimRangeQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.find (query, expectedQuerySize / 2);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.find (query, expectedQuerySize / 2);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (numPoints);', ' result1 = myTree.find (query, expectedQuerySize);', ' result2 = hisTree.find (query, expectedQuerySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // like the last one, but runs a top k', ' private void testOneDimTopKQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (167);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.findKClosest (query, querySize);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (0);', ' result1 = myTree.findKClosest (query, querySize);', ' result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST MULTI-DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimRangeQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' double dist1 = 0;', ' double dist2 = 0;', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' dist1 = Math.sqrt (numDims) * expectedQuerySize / 2.0;', ' dist2 = Math.sqrt (numDims) * expectedQuerySize;', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' // do a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, (int) expectedQuerySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = myTree.findKClosest (query2, (int) expectedQuerySize);', ' ', ' // find the distance to the furthest point in both cases', ' for (int i = 0; i < (int) expectedQuerySize; i++) {', ' double newDist = result1.get (i).getKey ().getDistance (query1);', ' if (newDist > dist1)', ' dist1 = newDist;', ' newDist = result2.get (i).getKey ().getDistance (query2);', ' if (newDist > dist2)', ' dist2 = newDist;', ' }', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.find (query1, dist1);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.find (query1, dist1);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.find (query2, dist2);', ' result2 = hisTree.find (query2, dist2);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimTopKQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, querySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.findKClosest (query1, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.findKClosest (query2, querySize);', ' result2 = hisTree.findKClosest (query2, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' ', ' /**', ' * "TIER 1" TESTS', ' * NONE OF THESE REQUIRE ANY SPLITS', ' */', ' public void testEasy1() {', ' testOneDimRangeQuery (true, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy2() {', ' testOneDimRangeQuery (false, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy3() {', ' testOneDimRangeQuery (true, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy4() {', ' testOneDimRangeQuery (false, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy5() {', ' testMultiDimRangeQuery (true, 1, 5, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy6() {', ' testMultiDimRangeQuery (false, 1, 10, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy7() {', ' testMultiDimRangeQuery (true, 1, 5, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy8() {', ' testMultiDimRangeQuery (false, 1, 15, 10000, 10000, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 2" TESTS', ' * NONE OF THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testMod1() {', ' testOneDimRangeQuery (true, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod2() {', ' testOneDimRangeQuery (false, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod3() {', ' testOneDimRangeQuery (true, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod4() {', ' testOneDimRangeQuery (false, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod5() {', ' testMultiDimRangeQuery (true, 2, 5, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod6() {', ' testMultiDimRangeQuery (false, 2, 10, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod7() {', ' testMultiDimRangeQuery (true, 2, 5, 10000, 100, 1000, 10);', ' }', ' ', ' public void testMod8() {', ' testMultiDimRangeQuery (false, 2, 15, 10000, 100, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 3" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testHard1() {', ' testOneDimRangeQuery (true, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard2() {', ' testOneDimRangeQuery (false, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard3() {', ' testOneDimRangeQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard4() {', ' testOneDimRangeQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard5() {', ' testMultiDimRangeQuery (true, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard6() {', ' testMultiDimRangeQuery (false, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard7() {', ' testMultiDimRangeQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard8() {', ' testMultiDimRangeQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', ' ', ' /**', ' * "TIER 4" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE AND THEY TEST THE TOPK FUNCTIONALITY', ' */', ' ', ' public void testTopK1() {', ' testOneDimTopKQuery (true, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK2() {', ' testOneDimTopKQuery (false, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK3() {', ' testOneDimTopKQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK4() {', ' testOneDimTopKQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK5() {', ' testMultiDimTopKQuery (true, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK6() {', ' testMultiDimTopKQuery (false, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK7() {', ' testMultiDimTopKQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK8() {', ' testMultiDimTopKQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', '}'] | [] | Global_Variable 'myData' used at line 535 is defined at line 454 and has a Long-Range dependency.
Function 'getData' used at line 535 is defined at line 443 and has a Long-Range dependency.
Function 'depth' used at line 535 is defined at line 534 and has a Short-Range dependency. | {} | {'Global_Variable Long-Range': 1, 'Function Long-Range': 1, 'Function Short-Range': 1} |
infilling_java | MTreeTester | 543 | 544 | ['import junit.framework.TestCase;', 'import java.util.ArrayList;', 'import java.util.Random;', 'import java.util.Collections;', '', '// this is a map from a set of keys of type PointInMetricSpace to a', '// set of data of type DataType', 'interface IMTree <Key extends IPointInMetricSpace <Key>, Data> {', ' ', ' // insert a new key/data pair into the map', ' void insert (Key keyToAdd, Data dataToAdd);', ' ', ' // find all of the key/data pairs in the map that fall within a', ' // particular distance of query point if no results are found, then', ' // an empty array is returned (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> find (Key query, double distance);', ' ', ' // find the k closest key/data pairs in the map to a particular', ' // query point ', ' //', ' // if the number of points in the map is less than k, then the', ' // returned list will have less than k pairs in it', ' //', ' // if the number of points is zero, then an empty array is returned', ' // (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> findKClosest (Key query, int k);', ' ', ' // returns the number of nodes that exist on a path from root to leaf in the tree...', ' // whtever the details of the implementation are, a tree with a single leaf node should return 1, and a tree', ' // with more than one lead node should return at least two (since it must have at least one internal node).', ' public int depth ();', ' ', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', '', 'interface IDoubleVector {', '', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '', '// this correponds to some geometric object in a metric space; the object is built out of', '// one or more points of type PointInMetricSpace', 'interface IObjectInMetricSpaceABCD <PointInMetricSpace extends IPointInMetricSpace<PointInMetricSpace>> {', ' ', ' // get the maximum distance from some point on the shape to a particular point in the metric space', ' double maxDistanceTo (PointInMetricSpace checkMe);', ' ', ' // return some arbitrary point on the interior of the geometric object', ' PointInMetricSpace getPointInInterior ();', '}', '', '', '// this interface corresponds to a point in some metric space', 'interface IPointInMetricSpace <PointInMetricSpace> {', ' ', ' // get the distance to another point', ' // ', ' // for this to work in an M-Tree, distances should be "metric" and', ' // obey the triangle inequality', ' double getDistance (PointInMetricSpace toMe);', '}', '', '// this is the basic node type in the structure', 'interface IMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> {', ' ', ' // insert a new key/data pair into the structure. The return value is a new MTreeNode if there was', ' // a split in response to the insertion, or a null if there was no split', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd);', ' ', ' // find all of the key/data pairs in the structure that fall within a particular query sphere', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query); ', ' ', ' // find the set of items closest to the given query point', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ);', ' ', ' // returns a sphere that totally encompasses everything in the node and its subtree', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', ' ', ' // returns the depth', ' public int depth ();', '}', '', '// this is a point in a particular metric space', 'class PointABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the point', ' private PointInMetricSpace me;', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return me; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return checkMe.getDistance (me); ', ' }', ' ', ' // contruct a point', ' public PointABCD (PointInMetricSpace useMe) {', ' me = useMe; ', ' }', '}', '', 'class PQueueABCD <PointInMetricSpace, DataType> {', ' ', ' // this is an object in the queue', ' private class Wrapper {', ' DataWrapper <PointInMetricSpace, DataType> myData;', ' double distance;', ' }', ' ', ' // this is the actual queue', ' ArrayList <Wrapper> myList;', ' ', ' // this is the largest distance value currently in the queue', ' double large;', ' ', ' // this is the max number of objects', ' int maxCount;', ' ', ' // create a priority queue with the speced number of slots', ' PQueueABCD (int maxCountIn) {', ' maxCount = maxCountIn;', ' myList = new ArrayList <Wrapper> ();', ' large = 9e99;', ' }', ' ', ' // get the largest distance in the queue', ' double getDist () {', ' return large;', ' }', ' ', ' // add a new object to the queue... the insertion is ignored if the distance value', ' // exceeds the largest that is in the queue and the queue is already full', ' void insert (PointInMetricSpace key, DataType data, double distance) {', ' ', ' // if we are full, remove the one with the largest distance', ' if (myList.size () == maxCount && distance < large) {', ' ', ' int badIndex = 0;', ' double maxDist = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > maxDist) {', ' maxDist = myList.get (i).distance;', ' badIndex = i;', ' }', ' }', ' ', ' myList.remove (badIndex);', ' }', ' ', ' // see if there is room', ' if (myList.size () < maxCount) {', ' ', ' // add it ', ' Wrapper newOne = new Wrapper ();', ' newOne.myData = new DataWrapper <PointInMetricSpace, DataType> (key, data);', ' newOne.distance = distance;', ' myList.add (newOne); ', ' }', ' ', ' // if we are full, reset the max distance', ' if (myList.size () == maxCount) {', ' large = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > large) {', ' large = myList.get (i).distance;', ' }', ' }', ' }', ' ', ' }', ' ', ' // extracts the contents of the queue', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> done () {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' for (int i = 0; i < myList.size (); i++) {', ' returnVal.add (myList.get (i).myData); ', ' }', ' ', ' return returnVal;', ' }', ' ', '}', '', '// this is a sphere in a particular metric space', 'class SphereABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the center of the sphere and its radius', ' private PointInMetricSpace center;', ' private double radius;', ' ', ' // build a sphere out of its center and its radius', ' public SphereABCD (PointInMetricSpace centerIn, double radiusIn) {', ' center = centerIn;', ' radius = radiusIn;', ' }', ' ', ' // increase the size of the sphere so it contains the object swallowMe', ' public void swallow (IObjectInMetricSpaceABCD <PointInMetricSpace> swallowMe) {', ' ', ' // see if we need to increase the radius to swallow this guy', ' double dist = swallowMe.maxDistanceTo (center);', ' if (dist > radius)', ' radius = dist;', ' }', ' ', ' // check to see if a sphere intersects another sphere', ' public boolean intersects (SphereABCD <PointInMetricSpace> me) {', ' return (me.center.getDistance (center) <= me.radius + radius);', ' }', ' ', ' // check to see if the sphere contains a point', ' public boolean contains (PointInMetricSpace checkMe) {', ' return (checkMe.getDistance (center) <= radius);', ' }', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return center; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return radius + checkMe.getDistance (center); ', ' }', '}', '', '', '', 'class OneDimPoint implements IPointInMetricSpace <OneDimPoint> {', ' ', ' // this is the actual double', ' Double value;', ' ', ' // construct this out of a double value', ' public OneDimPoint (double makeFromMe) {', ' value = new Double (makeFromMe);', ' }', ' ', ' // get the distance to another point', ' public double getDistance (OneDimPoint toMe) {', ' if (value > toMe.value)', ' return value - toMe.value;', ' else', ' return toMe.value - value;', ' }', ' ', '}', '', 'class MultiDimPoint implements IPointInMetricSpace <MultiDimPoint> {', ' ', ' // this is the point in a multidimensional space', ' IDoubleVector me;', ' ', ' // make this out of an IDoubleVector', ' public MultiDimPoint (IDoubleVector useMe) {', ' me = useMe;', ' }', ' ', ' // get the Euclidean distance to another point', ' public double getDistance (MultiDimPoint toMe) {', ' double distance = 0.0;', ' try {', ' for (int i = 0; i < me.getLength (); i++) {', ' double diff = me.getItem (i) - toMe.me.getItem (i);', ' diff *= diff;', ' distance += diff;', ' }', ' } catch (OutOfBoundsException e) {', ' throw new IndexOutOfBoundsException ("Can\'t compare two MultiDimPoint objects with different dimensionality!"); ', ' }', ' return Math.sqrt(distance);', ' }', ' ', '}', '// this is a leaf node', 'class LeafMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements ', ' IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myData;', ' ', ' // contructor that takes a data list and builds a node out of it', ' private LeafMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myDataIn) {', ' myData = myDataIn; ', ' }', ' ', ' // constructor that creates an empty node', ' public LeafMTreeNodeABCD () {', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> (); ', ' }', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // just add in the new data', ' myData.add (new PointABCD <PointInMetricSpace> (keyToAdd), dataToAdd);', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> newOne = myData.splitInTwo ();', ' LeafMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' myQ.insert (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData (), ', ' query.getDistance (myData.get (i).getKey ().getPointInInterior ()));', ' }', ' }', ' }', ' ', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' returnVal.add (new DataWrapper <PointInMetricSpace, DataType> (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData ()));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return 1; ', ' }', '', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', '// this silly little class is just a wrapper for a key, data pair', 'class DataWrapper <Key, Data> {', ' ', ' Key key;', ' Data data;', ' ', ' public DataWrapper (Key keyIn, Data dataIn) {', ' key = keyIn;', ' data = dataIn;', ' }', ' ', ' public Key getKey () {', ' return key;', ' }', ' ', ' public Data getData () {', ' return data;', ' }', '}', '', '', '// this is an internal node', 'class InternalMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType>', ' implements IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> myData;', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' // this constructs a new internal node that holds precisely the two nodes that are passed in', ' public InternalMTreeNodeABCD (IMTreeNodeABCD <PointInMetricSpace, DataType> refOne,', ' IMTreeNodeABCD <PointInMetricSpace, DataType> refTwo) {', ' ', ' // create a necw list and add the two guys in', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> ();', ' myData.add (refOne.getBoundingSphere (), refOne);', ' myData.add (refTwo.getBoundingSphere (), refTwo);', ' }', ' ', ' // this constructs a new node that holds the list of data that we were passed in', ' public InternalMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> useMe) {', ' myData = useMe; ', ' }', ' ', ' // from the interface', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // find the best child; this is the one we are closest to', ' double bestDist = 9e99;', ' int bestIndex = 0;', ' for (int i = 0; i < myData.size (); i++) {', ' ', ' double newDist = myData.get (i).getKey ().getPointInInterior ().getDistance (keyToAdd);', ' if (newDist < bestDist) {', ' bestDist = newDist;', ' bestIndex = i;', ' }', ' }', ' ', ' // do the recursive insert', ' IMTreeNodeABCD <PointInMetricSpace, DataType> newRef = myData.get (bestIndex).getData ().insert (keyToAdd, dataToAdd);', ' ', ' // if we got something back, then there was a split, so add the new node into our list', ' if (newRef != null) {', ' myData.add (newRef.getBoundingSphere (), newRef);', ' }', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> newOne = myData.splitInTwo ();', ' InternalMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.intersects (myData.get (i).getKey ())) {', ' myData.get (i).getData ().findKClosest (query, myQ);', ' }', ' }', ' }', ' ', ' // from the interface', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.intersects (myData.get (i).getKey ())) {', ' returnVal.addAll (myData.get (i).getData ().find (query));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return myData.get (0).getData ().depth () + 1; ', ' }', ' ', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {'] | [' maxSize = toMe; ', ' }'] | [' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', 'abstract class AMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> implements IMetricDataListABCD <PointInMetricSpace,KeyType, DataType> {', '', ' // this is the data that is actually stored in the list', ' private ArrayList <DataWrapper <KeyType, DataType>> myData;', ' ', ' // this is the sphere that bounds everything in the list', ' private SphereABCD <PointInMetricSpace> myBoundingSphere;', ' ', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myBoundingSphere; ', ' }', ' ', ' public int size () {', ' if (myData != null)', ' return myData.size (); ', ' else', ' return 0;', ' }', ' ', ' public DataWrapper <KeyType, DataType> get (int pos) {', ' return myData.get (pos);', ' }', ' ', ' public void replaceKey (int pos, KeyType keyToAdd) {', ' DataWrapper <KeyType, DataType> temp = myData.remove (pos);', ' DataWrapper <KeyType, DataType> newOne = new DataWrapper <KeyType, DataType> (keyToAdd, temp.getData ());', ' myData.add (pos, newOne);', ' }', ' ', ' public void add (KeyType keyToAdd, DataType dataToAdd) {', ' ', ' // if this is the first add, then set everyone up', ' if (myData == null) {', ' PointInMetricSpace myCentroid = keyToAdd.getPointInInterior ();', ' myBoundingSphere = new SphereABCD <PointInMetricSpace> (myCentroid, keyToAdd.maxDistanceTo (myCentroid));', ' myData = new ArrayList <DataWrapper <KeyType, DataType>> ();', ' ', ' // otherwise, extend the sphere if needed', ' } else {', ' myBoundingSphere.swallow (keyToAdd);', ' }', ' ', ' // add the data', ' myData.add (new DataWrapper <KeyType, DataType> (keyToAdd, dataToAdd));', ' }', ' ', ' // we want to potentially allow many implementations of the splitting lalgorithm', ' abstract public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // this is here so the actual splitting algorithn can access the list and change the sphere', ' protected ArrayList <DataWrapper <KeyType, DataType>> getList () {', ' return myData;', ' }', ' ', ' // this is here so the splitting algorithm can modify the list and the sphere', ' protected void replaceGuts (AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> withMe) {', ' myData = withMe.myData;', ' myBoundingSphere = withMe.myBoundingSphere;', ' }', ' ', '}', '', '// this is a particular implementation of the metric data list that uses a simple quadratic clustering', '// algorithm to perform a list split. It picks two "seeds" (the most distant objects) and then repeatedly', '// adds to the two new lists by choosing the objects closest to the seeds', 'class ChrisMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> extends AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> {', '', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo () {', ' ', ' // first, we need to find the two most distant points in the list', ' ArrayList <DataWrapper <KeyType, DataType>> myData = getList ();', ' int bestI = 0, bestJ = 0;', ' double maxDist = -1.0;', ' for (int i = 0; i < myData.size (); i++) {', ' for (int j = i + 1; j < myData.size (); j++) {', ' ', ' // get the two keys', ' DataWrapper <KeyType, DataType> pointOne = myData.get (i);', ' DataWrapper <KeyType, DataType> pointTwo = myData.get (j);', ' ', ' // find the difference between them', ' double curDist = pointOne.getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', '', ' // see if it is the biggest', ' if (curDist > maxDist) {', ' maxDist = curDist;', ' bestI = i;', ' bestJ = j;', ' }', ' }', ' }', ' ', ' // now, we have the best two points; those are seeds for the clustering', ' DataWrapper <KeyType, DataType> pointOne = myData.remove (bestI);', ' DataWrapper <KeyType, DataType> pointTwo = myData.remove (bestJ - 1);', ' ', ' // these are the two new lists', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listOne = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listTwo = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' ', ' // put the two seeds in', ' listOne.add (pointOne.getKey (), pointOne.getData ());', ' listTwo.add (pointTwo.getKey (), pointTwo.getData ());', ' ', ' // and add everyone else in', ' while (myData.size () != 0) {', ' ', ' // find the one closest to the first seed', ' int bestIndex = 0;', ' double bestDist = 9e99;', ' ', ' // loop thru all of the candidate data objects', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listOne.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' ', ' // break if no more data', ' if (myData.size () == 0)', ' break;', ' ', ' // loop thru all of the candidate data objects', ' bestDist = 9e99;', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listTwo.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' }', ' ', ' // now we replace our own guts with the first list', ' replaceGuts (listOne);', ' ', ' // and return the other list', ' return listTwo;', ' }', '}', '', 'interface IMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> {', ' ', ' // add a new pair to the list', ' public void add (KeyType keyToAdd, DataType dataToAdd);', ' ', ' // replace a key at the indicated position', ' public void replaceKey (int pos, KeyType keyToAdd);', ' ', ' // get the key, data pair that resides at a particular position', ' public DataWrapper <KeyType, DataType> get (int pos);', ' ', ' // return the number of items in the list', ' public int size ();', ' ', ' // split the list in two, using some clutering algorithm', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // get a sphere that totally bounds all of the objects in the list', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class MTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public MTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class SCMTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public SCMTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', '', 'public class MTreeTester extends TestCase {', ' ', ' // compare two lists of strings to see if the contents are the same', ' private boolean compareStringSets (ArrayList <String> setOne, ArrayList <String> setTwo) {', ' ', ' // sort the sets and make sure they are the same', ' boolean returnVal = true;', ' if (setOne.size () == setTwo.size ()) {', ' Collections.sort (setOne);', ' Collections.sort (setTwo);', ' for (int i = 0; i < setOne.size (); i++) {', ' if (!setOne.get (i).equals (setTwo.get (i))) {', ' returnVal = false;', ' break; ', ' }', ' }', ' } else {', ' returnVal = false;', ' }', ' ', ' // print out the result', ' System.out.println ("**** Expected:");', ' for (int i = 0; i < setOne.size (); i++) {', ' System.out.format (setOne.get (i) + " ");', ' }', ' System.out.println ("\\n**** Got:");', ' for (int i = 0; i < setTwo.size (); i++) {', ' System.out.format (setTwo.get (i) + " ");', ' }', ' System.out.println ("");', ' ', ' return returnVal;', ' }', ' ', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST SIMPLE ONE DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testOneDimRangeQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.find (query, expectedQuerySize / 2);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.find (query, expectedQuerySize / 2);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (numPoints);', ' result1 = myTree.find (query, expectedQuerySize);', ' result2 = hisTree.find (query, expectedQuerySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // like the last one, but runs a top k', ' private void testOneDimTopKQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (167);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.findKClosest (query, querySize);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (0);', ' result1 = myTree.findKClosest (query, querySize);', ' result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST MULTI-DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimRangeQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' double dist1 = 0;', ' double dist2 = 0;', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' dist1 = Math.sqrt (numDims) * expectedQuerySize / 2.0;', ' dist2 = Math.sqrt (numDims) * expectedQuerySize;', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' // do a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, (int) expectedQuerySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = myTree.findKClosest (query2, (int) expectedQuerySize);', ' ', ' // find the distance to the furthest point in both cases', ' for (int i = 0; i < (int) expectedQuerySize; i++) {', ' double newDist = result1.get (i).getKey ().getDistance (query1);', ' if (newDist > dist1)', ' dist1 = newDist;', ' newDist = result2.get (i).getKey ().getDistance (query2);', ' if (newDist > dist2)', ' dist2 = newDist;', ' }', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.find (query1, dist1);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.find (query1, dist1);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.find (query2, dist2);', ' result2 = hisTree.find (query2, dist2);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimTopKQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, querySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.findKClosest (query1, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.findKClosest (query2, querySize);', ' result2 = hisTree.findKClosest (query2, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' ', ' /**', ' * "TIER 1" TESTS', ' * NONE OF THESE REQUIRE ANY SPLITS', ' */', ' public void testEasy1() {', ' testOneDimRangeQuery (true, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy2() {', ' testOneDimRangeQuery (false, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy3() {', ' testOneDimRangeQuery (true, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy4() {', ' testOneDimRangeQuery (false, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy5() {', ' testMultiDimRangeQuery (true, 1, 5, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy6() {', ' testMultiDimRangeQuery (false, 1, 10, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy7() {', ' testMultiDimRangeQuery (true, 1, 5, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy8() {', ' testMultiDimRangeQuery (false, 1, 15, 10000, 10000, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 2" TESTS', ' * NONE OF THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testMod1() {', ' testOneDimRangeQuery (true, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod2() {', ' testOneDimRangeQuery (false, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod3() {', ' testOneDimRangeQuery (true, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod4() {', ' testOneDimRangeQuery (false, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod5() {', ' testMultiDimRangeQuery (true, 2, 5, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod6() {', ' testMultiDimRangeQuery (false, 2, 10, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod7() {', ' testMultiDimRangeQuery (true, 2, 5, 10000, 100, 1000, 10);', ' }', ' ', ' public void testMod8() {', ' testMultiDimRangeQuery (false, 2, 15, 10000, 100, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 3" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testHard1() {', ' testOneDimRangeQuery (true, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard2() {', ' testOneDimRangeQuery (false, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard3() {', ' testOneDimRangeQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard4() {', ' testOneDimRangeQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard5() {', ' testMultiDimRangeQuery (true, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard6() {', ' testMultiDimRangeQuery (false, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard7() {', ' testMultiDimRangeQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard8() {', ' testMultiDimRangeQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', ' ', ' /**', ' * "TIER 4" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE AND THEY TEST THE TOPK FUNCTIONALITY', ' */', ' ', ' public void testTopK1() {', ' testOneDimTopKQuery (true, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK2() {', ' testOneDimTopKQuery (false, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK3() {', ' testOneDimTopKQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK4() {', ' testOneDimTopKQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK5() {', ' testMultiDimTopKQuery (true, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK6() {', ' testMultiDimTopKQuery (false, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK7() {', ' testMultiDimTopKQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK8() {', ' testMultiDimTopKQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', '}'] | [] | Variable 'toMe' used at line 543 is defined at line 542 and has a Short-Range dependency.
Global_Variable 'maxSize' used at line 543 is defined at line 539 and has a Short-Range dependency. | {} | {'Variable Short-Range': 1, 'Global_Variable Short-Range': 1} |
infilling_java | MTreeTester | 546 | 547 | ['import junit.framework.TestCase;', 'import java.util.ArrayList;', 'import java.util.Random;', 'import java.util.Collections;', '', '// this is a map from a set of keys of type PointInMetricSpace to a', '// set of data of type DataType', 'interface IMTree <Key extends IPointInMetricSpace <Key>, Data> {', ' ', ' // insert a new key/data pair into the map', ' void insert (Key keyToAdd, Data dataToAdd);', ' ', ' // find all of the key/data pairs in the map that fall within a', ' // particular distance of query point if no results are found, then', ' // an empty array is returned (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> find (Key query, double distance);', ' ', ' // find the k closest key/data pairs in the map to a particular', ' // query point ', ' //', ' // if the number of points in the map is less than k, then the', ' // returned list will have less than k pairs in it', ' //', ' // if the number of points is zero, then an empty array is returned', ' // (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> findKClosest (Key query, int k);', ' ', ' // returns the number of nodes that exist on a path from root to leaf in the tree...', ' // whtever the details of the implementation are, a tree with a single leaf node should return 1, and a tree', ' // with more than one lead node should return at least two (since it must have at least one internal node).', ' public int depth ();', ' ', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', '', 'interface IDoubleVector {', '', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '', '// this correponds to some geometric object in a metric space; the object is built out of', '// one or more points of type PointInMetricSpace', 'interface IObjectInMetricSpaceABCD <PointInMetricSpace extends IPointInMetricSpace<PointInMetricSpace>> {', ' ', ' // get the maximum distance from some point on the shape to a particular point in the metric space', ' double maxDistanceTo (PointInMetricSpace checkMe);', ' ', ' // return some arbitrary point on the interior of the geometric object', ' PointInMetricSpace getPointInInterior ();', '}', '', '', '// this interface corresponds to a point in some metric space', 'interface IPointInMetricSpace <PointInMetricSpace> {', ' ', ' // get the distance to another point', ' // ', ' // for this to work in an M-Tree, distances should be "metric" and', ' // obey the triangle inequality', ' double getDistance (PointInMetricSpace toMe);', '}', '', '// this is the basic node type in the structure', 'interface IMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> {', ' ', ' // insert a new key/data pair into the structure. The return value is a new MTreeNode if there was', ' // a split in response to the insertion, or a null if there was no split', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd);', ' ', ' // find all of the key/data pairs in the structure that fall within a particular query sphere', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query); ', ' ', ' // find the set of items closest to the given query point', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ);', ' ', ' // returns a sphere that totally encompasses everything in the node and its subtree', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', ' ', ' // returns the depth', ' public int depth ();', '}', '', '// this is a point in a particular metric space', 'class PointABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the point', ' private PointInMetricSpace me;', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return me; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return checkMe.getDistance (me); ', ' }', ' ', ' // contruct a point', ' public PointABCD (PointInMetricSpace useMe) {', ' me = useMe; ', ' }', '}', '', 'class PQueueABCD <PointInMetricSpace, DataType> {', ' ', ' // this is an object in the queue', ' private class Wrapper {', ' DataWrapper <PointInMetricSpace, DataType> myData;', ' double distance;', ' }', ' ', ' // this is the actual queue', ' ArrayList <Wrapper> myList;', ' ', ' // this is the largest distance value currently in the queue', ' double large;', ' ', ' // this is the max number of objects', ' int maxCount;', ' ', ' // create a priority queue with the speced number of slots', ' PQueueABCD (int maxCountIn) {', ' maxCount = maxCountIn;', ' myList = new ArrayList <Wrapper> ();', ' large = 9e99;', ' }', ' ', ' // get the largest distance in the queue', ' double getDist () {', ' return large;', ' }', ' ', ' // add a new object to the queue... the insertion is ignored if the distance value', ' // exceeds the largest that is in the queue and the queue is already full', ' void insert (PointInMetricSpace key, DataType data, double distance) {', ' ', ' // if we are full, remove the one with the largest distance', ' if (myList.size () == maxCount && distance < large) {', ' ', ' int badIndex = 0;', ' double maxDist = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > maxDist) {', ' maxDist = myList.get (i).distance;', ' badIndex = i;', ' }', ' }', ' ', ' myList.remove (badIndex);', ' }', ' ', ' // see if there is room', ' if (myList.size () < maxCount) {', ' ', ' // add it ', ' Wrapper newOne = new Wrapper ();', ' newOne.myData = new DataWrapper <PointInMetricSpace, DataType> (key, data);', ' newOne.distance = distance;', ' myList.add (newOne); ', ' }', ' ', ' // if we are full, reset the max distance', ' if (myList.size () == maxCount) {', ' large = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > large) {', ' large = myList.get (i).distance;', ' }', ' }', ' }', ' ', ' }', ' ', ' // extracts the contents of the queue', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> done () {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' for (int i = 0; i < myList.size (); i++) {', ' returnVal.add (myList.get (i).myData); ', ' }', ' ', ' return returnVal;', ' }', ' ', '}', '', '// this is a sphere in a particular metric space', 'class SphereABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the center of the sphere and its radius', ' private PointInMetricSpace center;', ' private double radius;', ' ', ' // build a sphere out of its center and its radius', ' public SphereABCD (PointInMetricSpace centerIn, double radiusIn) {', ' center = centerIn;', ' radius = radiusIn;', ' }', ' ', ' // increase the size of the sphere so it contains the object swallowMe', ' public void swallow (IObjectInMetricSpaceABCD <PointInMetricSpace> swallowMe) {', ' ', ' // see if we need to increase the radius to swallow this guy', ' double dist = swallowMe.maxDistanceTo (center);', ' if (dist > radius)', ' radius = dist;', ' }', ' ', ' // check to see if a sphere intersects another sphere', ' public boolean intersects (SphereABCD <PointInMetricSpace> me) {', ' return (me.center.getDistance (center) <= me.radius + radius);', ' }', ' ', ' // check to see if the sphere contains a point', ' public boolean contains (PointInMetricSpace checkMe) {', ' return (checkMe.getDistance (center) <= radius);', ' }', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return center; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return radius + checkMe.getDistance (center); ', ' }', '}', '', '', '', 'class OneDimPoint implements IPointInMetricSpace <OneDimPoint> {', ' ', ' // this is the actual double', ' Double value;', ' ', ' // construct this out of a double value', ' public OneDimPoint (double makeFromMe) {', ' value = new Double (makeFromMe);', ' }', ' ', ' // get the distance to another point', ' public double getDistance (OneDimPoint toMe) {', ' if (value > toMe.value)', ' return value - toMe.value;', ' else', ' return toMe.value - value;', ' }', ' ', '}', '', 'class MultiDimPoint implements IPointInMetricSpace <MultiDimPoint> {', ' ', ' // this is the point in a multidimensional space', ' IDoubleVector me;', ' ', ' // make this out of an IDoubleVector', ' public MultiDimPoint (IDoubleVector useMe) {', ' me = useMe;', ' }', ' ', ' // get the Euclidean distance to another point', ' public double getDistance (MultiDimPoint toMe) {', ' double distance = 0.0;', ' try {', ' for (int i = 0; i < me.getLength (); i++) {', ' double diff = me.getItem (i) - toMe.me.getItem (i);', ' diff *= diff;', ' distance += diff;', ' }', ' } catch (OutOfBoundsException e) {', ' throw new IndexOutOfBoundsException ("Can\'t compare two MultiDimPoint objects with different dimensionality!"); ', ' }', ' return Math.sqrt(distance);', ' }', ' ', '}', '// this is a leaf node', 'class LeafMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements ', ' IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myData;', ' ', ' // contructor that takes a data list and builds a node out of it', ' private LeafMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myDataIn) {', ' myData = myDataIn; ', ' }', ' ', ' // constructor that creates an empty node', ' public LeafMTreeNodeABCD () {', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> (); ', ' }', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // just add in the new data', ' myData.add (new PointABCD <PointInMetricSpace> (keyToAdd), dataToAdd);', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> newOne = myData.splitInTwo ();', ' LeafMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' myQ.insert (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData (), ', ' query.getDistance (myData.get (i).getKey ().getPointInInterior ()));', ' }', ' }', ' }', ' ', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' returnVal.add (new DataWrapper <PointInMetricSpace, DataType> (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData ()));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return 1; ', ' }', '', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', '// this silly little class is just a wrapper for a key, data pair', 'class DataWrapper <Key, Data> {', ' ', ' Key key;', ' Data data;', ' ', ' public DataWrapper (Key keyIn, Data dataIn) {', ' key = keyIn;', ' data = dataIn;', ' }', ' ', ' public Key getKey () {', ' return key;', ' }', ' ', ' public Data getData () {', ' return data;', ' }', '}', '', '', '// this is an internal node', 'class InternalMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType>', ' implements IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> myData;', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' // this constructs a new internal node that holds precisely the two nodes that are passed in', ' public InternalMTreeNodeABCD (IMTreeNodeABCD <PointInMetricSpace, DataType> refOne,', ' IMTreeNodeABCD <PointInMetricSpace, DataType> refTwo) {', ' ', ' // create a necw list and add the two guys in', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> ();', ' myData.add (refOne.getBoundingSphere (), refOne);', ' myData.add (refTwo.getBoundingSphere (), refTwo);', ' }', ' ', ' // this constructs a new node that holds the list of data that we were passed in', ' public InternalMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> useMe) {', ' myData = useMe; ', ' }', ' ', ' // from the interface', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // find the best child; this is the one we are closest to', ' double bestDist = 9e99;', ' int bestIndex = 0;', ' for (int i = 0; i < myData.size (); i++) {', ' ', ' double newDist = myData.get (i).getKey ().getPointInInterior ().getDistance (keyToAdd);', ' if (newDist < bestDist) {', ' bestDist = newDist;', ' bestIndex = i;', ' }', ' }', ' ', ' // do the recursive insert', ' IMTreeNodeABCD <PointInMetricSpace, DataType> newRef = myData.get (bestIndex).getData ().insert (keyToAdd, dataToAdd);', ' ', ' // if we got something back, then there was a split, so add the new node into our list', ' if (newRef != null) {', ' myData.add (newRef.getBoundingSphere (), newRef);', ' }', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> newOne = myData.splitInTwo ();', ' InternalMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.intersects (myData.get (i).getKey ())) {', ' myData.get (i).getData ().findKClosest (query, myQ);', ' }', ' }', ' }', ' ', ' // from the interface', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.intersects (myData.get (i).getKey ())) {', ' returnVal.addAll (myData.get (i).getData ().find (query));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return myData.get (0).getData ().depth () + 1; ', ' }', ' ', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {'] | [' return maxSize;', ' }'] | ['}', '', 'abstract class AMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> implements IMetricDataListABCD <PointInMetricSpace,KeyType, DataType> {', '', ' // this is the data that is actually stored in the list', ' private ArrayList <DataWrapper <KeyType, DataType>> myData;', ' ', ' // this is the sphere that bounds everything in the list', ' private SphereABCD <PointInMetricSpace> myBoundingSphere;', ' ', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myBoundingSphere; ', ' }', ' ', ' public int size () {', ' if (myData != null)', ' return myData.size (); ', ' else', ' return 0;', ' }', ' ', ' public DataWrapper <KeyType, DataType> get (int pos) {', ' return myData.get (pos);', ' }', ' ', ' public void replaceKey (int pos, KeyType keyToAdd) {', ' DataWrapper <KeyType, DataType> temp = myData.remove (pos);', ' DataWrapper <KeyType, DataType> newOne = new DataWrapper <KeyType, DataType> (keyToAdd, temp.getData ());', ' myData.add (pos, newOne);', ' }', ' ', ' public void add (KeyType keyToAdd, DataType dataToAdd) {', ' ', ' // if this is the first add, then set everyone up', ' if (myData == null) {', ' PointInMetricSpace myCentroid = keyToAdd.getPointInInterior ();', ' myBoundingSphere = new SphereABCD <PointInMetricSpace> (myCentroid, keyToAdd.maxDistanceTo (myCentroid));', ' myData = new ArrayList <DataWrapper <KeyType, DataType>> ();', ' ', ' // otherwise, extend the sphere if needed', ' } else {', ' myBoundingSphere.swallow (keyToAdd);', ' }', ' ', ' // add the data', ' myData.add (new DataWrapper <KeyType, DataType> (keyToAdd, dataToAdd));', ' }', ' ', ' // we want to potentially allow many implementations of the splitting lalgorithm', ' abstract public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // this is here so the actual splitting algorithn can access the list and change the sphere', ' protected ArrayList <DataWrapper <KeyType, DataType>> getList () {', ' return myData;', ' }', ' ', ' // this is here so the splitting algorithm can modify the list and the sphere', ' protected void replaceGuts (AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> withMe) {', ' myData = withMe.myData;', ' myBoundingSphere = withMe.myBoundingSphere;', ' }', ' ', '}', '', '// this is a particular implementation of the metric data list that uses a simple quadratic clustering', '// algorithm to perform a list split. It picks two "seeds" (the most distant objects) and then repeatedly', '// adds to the two new lists by choosing the objects closest to the seeds', 'class ChrisMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> extends AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> {', '', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo () {', ' ', ' // first, we need to find the two most distant points in the list', ' ArrayList <DataWrapper <KeyType, DataType>> myData = getList ();', ' int bestI = 0, bestJ = 0;', ' double maxDist = -1.0;', ' for (int i = 0; i < myData.size (); i++) {', ' for (int j = i + 1; j < myData.size (); j++) {', ' ', ' // get the two keys', ' DataWrapper <KeyType, DataType> pointOne = myData.get (i);', ' DataWrapper <KeyType, DataType> pointTwo = myData.get (j);', ' ', ' // find the difference between them', ' double curDist = pointOne.getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', '', ' // see if it is the biggest', ' if (curDist > maxDist) {', ' maxDist = curDist;', ' bestI = i;', ' bestJ = j;', ' }', ' }', ' }', ' ', ' // now, we have the best two points; those are seeds for the clustering', ' DataWrapper <KeyType, DataType> pointOne = myData.remove (bestI);', ' DataWrapper <KeyType, DataType> pointTwo = myData.remove (bestJ - 1);', ' ', ' // these are the two new lists', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listOne = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listTwo = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' ', ' // put the two seeds in', ' listOne.add (pointOne.getKey (), pointOne.getData ());', ' listTwo.add (pointTwo.getKey (), pointTwo.getData ());', ' ', ' // and add everyone else in', ' while (myData.size () != 0) {', ' ', ' // find the one closest to the first seed', ' int bestIndex = 0;', ' double bestDist = 9e99;', ' ', ' // loop thru all of the candidate data objects', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listOne.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' ', ' // break if no more data', ' if (myData.size () == 0)', ' break;', ' ', ' // loop thru all of the candidate data objects', ' bestDist = 9e99;', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listTwo.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' }', ' ', ' // now we replace our own guts with the first list', ' replaceGuts (listOne);', ' ', ' // and return the other list', ' return listTwo;', ' }', '}', '', 'interface IMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> {', ' ', ' // add a new pair to the list', ' public void add (KeyType keyToAdd, DataType dataToAdd);', ' ', ' // replace a key at the indicated position', ' public void replaceKey (int pos, KeyType keyToAdd);', ' ', ' // get the key, data pair that resides at a particular position', ' public DataWrapper <KeyType, DataType> get (int pos);', ' ', ' // return the number of items in the list', ' public int size ();', ' ', ' // split the list in two, using some clutering algorithm', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // get a sphere that totally bounds all of the objects in the list', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class MTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public MTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class SCMTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public SCMTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', '', 'public class MTreeTester extends TestCase {', ' ', ' // compare two lists of strings to see if the contents are the same', ' private boolean compareStringSets (ArrayList <String> setOne, ArrayList <String> setTwo) {', ' ', ' // sort the sets and make sure they are the same', ' boolean returnVal = true;', ' if (setOne.size () == setTwo.size ()) {', ' Collections.sort (setOne);', ' Collections.sort (setTwo);', ' for (int i = 0; i < setOne.size (); i++) {', ' if (!setOne.get (i).equals (setTwo.get (i))) {', ' returnVal = false;', ' break; ', ' }', ' }', ' } else {', ' returnVal = false;', ' }', ' ', ' // print out the result', ' System.out.println ("**** Expected:");', ' for (int i = 0; i < setOne.size (); i++) {', ' System.out.format (setOne.get (i) + " ");', ' }', ' System.out.println ("\\n**** Got:");', ' for (int i = 0; i < setTwo.size (); i++) {', ' System.out.format (setTwo.get (i) + " ");', ' }', ' System.out.println ("");', ' ', ' return returnVal;', ' }', ' ', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST SIMPLE ONE DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testOneDimRangeQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.find (query, expectedQuerySize / 2);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.find (query, expectedQuerySize / 2);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (numPoints);', ' result1 = myTree.find (query, expectedQuerySize);', ' result2 = hisTree.find (query, expectedQuerySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // like the last one, but runs a top k', ' private void testOneDimTopKQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (167);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.findKClosest (query, querySize);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (0);', ' result1 = myTree.findKClosest (query, querySize);', ' result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST MULTI-DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimRangeQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' double dist1 = 0;', ' double dist2 = 0;', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' dist1 = Math.sqrt (numDims) * expectedQuerySize / 2.0;', ' dist2 = Math.sqrt (numDims) * expectedQuerySize;', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' // do a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, (int) expectedQuerySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = myTree.findKClosest (query2, (int) expectedQuerySize);', ' ', ' // find the distance to the furthest point in both cases', ' for (int i = 0; i < (int) expectedQuerySize; i++) {', ' double newDist = result1.get (i).getKey ().getDistance (query1);', ' if (newDist > dist1)', ' dist1 = newDist;', ' newDist = result2.get (i).getKey ().getDistance (query2);', ' if (newDist > dist2)', ' dist2 = newDist;', ' }', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.find (query1, dist1);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.find (query1, dist1);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.find (query2, dist2);', ' result2 = hisTree.find (query2, dist2);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimTopKQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, querySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.findKClosest (query1, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.findKClosest (query2, querySize);', ' result2 = hisTree.findKClosest (query2, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' ', ' /**', ' * "TIER 1" TESTS', ' * NONE OF THESE REQUIRE ANY SPLITS', ' */', ' public void testEasy1() {', ' testOneDimRangeQuery (true, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy2() {', ' testOneDimRangeQuery (false, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy3() {', ' testOneDimRangeQuery (true, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy4() {', ' testOneDimRangeQuery (false, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy5() {', ' testMultiDimRangeQuery (true, 1, 5, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy6() {', ' testMultiDimRangeQuery (false, 1, 10, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy7() {', ' testMultiDimRangeQuery (true, 1, 5, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy8() {', ' testMultiDimRangeQuery (false, 1, 15, 10000, 10000, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 2" TESTS', ' * NONE OF THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testMod1() {', ' testOneDimRangeQuery (true, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod2() {', ' testOneDimRangeQuery (false, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod3() {', ' testOneDimRangeQuery (true, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod4() {', ' testOneDimRangeQuery (false, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod5() {', ' testMultiDimRangeQuery (true, 2, 5, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod6() {', ' testMultiDimRangeQuery (false, 2, 10, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod7() {', ' testMultiDimRangeQuery (true, 2, 5, 10000, 100, 1000, 10);', ' }', ' ', ' public void testMod8() {', ' testMultiDimRangeQuery (false, 2, 15, 10000, 100, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 3" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testHard1() {', ' testOneDimRangeQuery (true, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard2() {', ' testOneDimRangeQuery (false, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard3() {', ' testOneDimRangeQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard4() {', ' testOneDimRangeQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard5() {', ' testMultiDimRangeQuery (true, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard6() {', ' testMultiDimRangeQuery (false, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard7() {', ' testMultiDimRangeQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard8() {', ' testMultiDimRangeQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', ' ', ' /**', ' * "TIER 4" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE AND THEY TEST THE TOPK FUNCTIONALITY', ' */', ' ', ' public void testTopK1() {', ' testOneDimTopKQuery (true, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK2() {', ' testOneDimTopKQuery (false, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK3() {', ' testOneDimTopKQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK4() {', ' testOneDimTopKQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK5() {', ' testMultiDimTopKQuery (true, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK6() {', ' testMultiDimTopKQuery (false, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK7() {', ' testMultiDimTopKQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK8() {', ' testMultiDimTopKQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', '}'] | [] | Global_Variable 'maxSize' used at line 546 is defined at line 539 and has a Short-Range dependency. | {} | {'Global_Variable Short-Range': 1} |
infilling_java | MTreeTester | 565 | 565 | ['import junit.framework.TestCase;', 'import java.util.ArrayList;', 'import java.util.Random;', 'import java.util.Collections;', '', '// this is a map from a set of keys of type PointInMetricSpace to a', '// set of data of type DataType', 'interface IMTree <Key extends IPointInMetricSpace <Key>, Data> {', ' ', ' // insert a new key/data pair into the map', ' void insert (Key keyToAdd, Data dataToAdd);', ' ', ' // find all of the key/data pairs in the map that fall within a', ' // particular distance of query point if no results are found, then', ' // an empty array is returned (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> find (Key query, double distance);', ' ', ' // find the k closest key/data pairs in the map to a particular', ' // query point ', ' //', ' // if the number of points in the map is less than k, then the', ' // returned list will have less than k pairs in it', ' //', ' // if the number of points is zero, then an empty array is returned', ' // (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> findKClosest (Key query, int k);', ' ', ' // returns the number of nodes that exist on a path from root to leaf in the tree...', ' // whtever the details of the implementation are, a tree with a single leaf node should return 1, and a tree', ' // with more than one lead node should return at least two (since it must have at least one internal node).', ' public int depth ();', ' ', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', '', 'interface IDoubleVector {', '', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '', '// this correponds to some geometric object in a metric space; the object is built out of', '// one or more points of type PointInMetricSpace', 'interface IObjectInMetricSpaceABCD <PointInMetricSpace extends IPointInMetricSpace<PointInMetricSpace>> {', ' ', ' // get the maximum distance from some point on the shape to a particular point in the metric space', ' double maxDistanceTo (PointInMetricSpace checkMe);', ' ', ' // return some arbitrary point on the interior of the geometric object', ' PointInMetricSpace getPointInInterior ();', '}', '', '', '// this interface corresponds to a point in some metric space', 'interface IPointInMetricSpace <PointInMetricSpace> {', ' ', ' // get the distance to another point', ' // ', ' // for this to work in an M-Tree, distances should be "metric" and', ' // obey the triangle inequality', ' double getDistance (PointInMetricSpace toMe);', '}', '', '// this is the basic node type in the structure', 'interface IMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> {', ' ', ' // insert a new key/data pair into the structure. The return value is a new MTreeNode if there was', ' // a split in response to the insertion, or a null if there was no split', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd);', ' ', ' // find all of the key/data pairs in the structure that fall within a particular query sphere', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query); ', ' ', ' // find the set of items closest to the given query point', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ);', ' ', ' // returns a sphere that totally encompasses everything in the node and its subtree', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', ' ', ' // returns the depth', ' public int depth ();', '}', '', '// this is a point in a particular metric space', 'class PointABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the point', ' private PointInMetricSpace me;', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return me; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return checkMe.getDistance (me); ', ' }', ' ', ' // contruct a point', ' public PointABCD (PointInMetricSpace useMe) {', ' me = useMe; ', ' }', '}', '', 'class PQueueABCD <PointInMetricSpace, DataType> {', ' ', ' // this is an object in the queue', ' private class Wrapper {', ' DataWrapper <PointInMetricSpace, DataType> myData;', ' double distance;', ' }', ' ', ' // this is the actual queue', ' ArrayList <Wrapper> myList;', ' ', ' // this is the largest distance value currently in the queue', ' double large;', ' ', ' // this is the max number of objects', ' int maxCount;', ' ', ' // create a priority queue with the speced number of slots', ' PQueueABCD (int maxCountIn) {', ' maxCount = maxCountIn;', ' myList = new ArrayList <Wrapper> ();', ' large = 9e99;', ' }', ' ', ' // get the largest distance in the queue', ' double getDist () {', ' return large;', ' }', ' ', ' // add a new object to the queue... the insertion is ignored if the distance value', ' // exceeds the largest that is in the queue and the queue is already full', ' void insert (PointInMetricSpace key, DataType data, double distance) {', ' ', ' // if we are full, remove the one with the largest distance', ' if (myList.size () == maxCount && distance < large) {', ' ', ' int badIndex = 0;', ' double maxDist = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > maxDist) {', ' maxDist = myList.get (i).distance;', ' badIndex = i;', ' }', ' }', ' ', ' myList.remove (badIndex);', ' }', ' ', ' // see if there is room', ' if (myList.size () < maxCount) {', ' ', ' // add it ', ' Wrapper newOne = new Wrapper ();', ' newOne.myData = new DataWrapper <PointInMetricSpace, DataType> (key, data);', ' newOne.distance = distance;', ' myList.add (newOne); ', ' }', ' ', ' // if we are full, reset the max distance', ' if (myList.size () == maxCount) {', ' large = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > large) {', ' large = myList.get (i).distance;', ' }', ' }', ' }', ' ', ' }', ' ', ' // extracts the contents of the queue', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> done () {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' for (int i = 0; i < myList.size (); i++) {', ' returnVal.add (myList.get (i).myData); ', ' }', ' ', ' return returnVal;', ' }', ' ', '}', '', '// this is a sphere in a particular metric space', 'class SphereABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the center of the sphere and its radius', ' private PointInMetricSpace center;', ' private double radius;', ' ', ' // build a sphere out of its center and its radius', ' public SphereABCD (PointInMetricSpace centerIn, double radiusIn) {', ' center = centerIn;', ' radius = radiusIn;', ' }', ' ', ' // increase the size of the sphere so it contains the object swallowMe', ' public void swallow (IObjectInMetricSpaceABCD <PointInMetricSpace> swallowMe) {', ' ', ' // see if we need to increase the radius to swallow this guy', ' double dist = swallowMe.maxDistanceTo (center);', ' if (dist > radius)', ' radius = dist;', ' }', ' ', ' // check to see if a sphere intersects another sphere', ' public boolean intersects (SphereABCD <PointInMetricSpace> me) {', ' return (me.center.getDistance (center) <= me.radius + radius);', ' }', ' ', ' // check to see if the sphere contains a point', ' public boolean contains (PointInMetricSpace checkMe) {', ' return (checkMe.getDistance (center) <= radius);', ' }', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return center; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return radius + checkMe.getDistance (center); ', ' }', '}', '', '', '', 'class OneDimPoint implements IPointInMetricSpace <OneDimPoint> {', ' ', ' // this is the actual double', ' Double value;', ' ', ' // construct this out of a double value', ' public OneDimPoint (double makeFromMe) {', ' value = new Double (makeFromMe);', ' }', ' ', ' // get the distance to another point', ' public double getDistance (OneDimPoint toMe) {', ' if (value > toMe.value)', ' return value - toMe.value;', ' else', ' return toMe.value - value;', ' }', ' ', '}', '', 'class MultiDimPoint implements IPointInMetricSpace <MultiDimPoint> {', ' ', ' // this is the point in a multidimensional space', ' IDoubleVector me;', ' ', ' // make this out of an IDoubleVector', ' public MultiDimPoint (IDoubleVector useMe) {', ' me = useMe;', ' }', ' ', ' // get the Euclidean distance to another point', ' public double getDistance (MultiDimPoint toMe) {', ' double distance = 0.0;', ' try {', ' for (int i = 0; i < me.getLength (); i++) {', ' double diff = me.getItem (i) - toMe.me.getItem (i);', ' diff *= diff;', ' distance += diff;', ' }', ' } catch (OutOfBoundsException e) {', ' throw new IndexOutOfBoundsException ("Can\'t compare two MultiDimPoint objects with different dimensionality!"); ', ' }', ' return Math.sqrt(distance);', ' }', ' ', '}', '// this is a leaf node', 'class LeafMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements ', ' IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myData;', ' ', ' // contructor that takes a data list and builds a node out of it', ' private LeafMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myDataIn) {', ' myData = myDataIn; ', ' }', ' ', ' // constructor that creates an empty node', ' public LeafMTreeNodeABCD () {', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> (); ', ' }', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // just add in the new data', ' myData.add (new PointABCD <PointInMetricSpace> (keyToAdd), dataToAdd);', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> newOne = myData.splitInTwo ();', ' LeafMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' myQ.insert (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData (), ', ' query.getDistance (myData.get (i).getKey ().getPointInInterior ()));', ' }', ' }', ' }', ' ', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' returnVal.add (new DataWrapper <PointInMetricSpace, DataType> (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData ()));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return 1; ', ' }', '', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', '// this silly little class is just a wrapper for a key, data pair', 'class DataWrapper <Key, Data> {', ' ', ' Key key;', ' Data data;', ' ', ' public DataWrapper (Key keyIn, Data dataIn) {', ' key = keyIn;', ' data = dataIn;', ' }', ' ', ' public Key getKey () {', ' return key;', ' }', ' ', ' public Data getData () {', ' return data;', ' }', '}', '', '', '// this is an internal node', 'class InternalMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType>', ' implements IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> myData;', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' // this constructs a new internal node that holds precisely the two nodes that are passed in', ' public InternalMTreeNodeABCD (IMTreeNodeABCD <PointInMetricSpace, DataType> refOne,', ' IMTreeNodeABCD <PointInMetricSpace, DataType> refTwo) {', ' ', ' // create a necw list and add the two guys in', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> ();', ' myData.add (refOne.getBoundingSphere (), refOne);', ' myData.add (refTwo.getBoundingSphere (), refTwo);', ' }', ' ', ' // this constructs a new node that holds the list of data that we were passed in', ' public InternalMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> useMe) {', ' myData = useMe; ', ' }', ' ', ' // from the interface', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // find the best child; this is the one we are closest to', ' double bestDist = 9e99;', ' int bestIndex = 0;', ' for (int i = 0; i < myData.size (); i++) {', ' ', ' double newDist = myData.get (i).getKey ().getPointInInterior ().getDistance (keyToAdd);', ' if (newDist < bestDist) {', ' bestDist = newDist;', ' bestIndex = i;', ' }', ' }', ' ', ' // do the recursive insert', ' IMTreeNodeABCD <PointInMetricSpace, DataType> newRef = myData.get (bestIndex).getData ().insert (keyToAdd, dataToAdd);', ' ', ' // if we got something back, then there was a split, so add the new node into our list', ' if (newRef != null) {', ' myData.add (newRef.getBoundingSphere (), newRef);', ' }', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> newOne = myData.splitInTwo ();', ' InternalMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.intersects (myData.get (i).getKey ())) {', ' myData.get (i).getData ().findKClosest (query, myQ);', ' }', ' }', ' }', ' ', ' // from the interface', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.intersects (myData.get (i).getKey ())) {', ' returnVal.addAll (myData.get (i).getData ().find (query));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return myData.get (0).getData ().depth () + 1; ', ' }', ' ', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', 'abstract class AMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> implements IMetricDataListABCD <PointInMetricSpace,KeyType, DataType> {', '', ' // this is the data that is actually stored in the list', ' private ArrayList <DataWrapper <KeyType, DataType>> myData;', ' ', ' // this is the sphere that bounds everything in the list', ' private SphereABCD <PointInMetricSpace> myBoundingSphere;', ' ', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myBoundingSphere; ', ' }', ' ', ' public int size () {', ' if (myData != null)'] | [' return myData.size (); '] | [' else', ' return 0;', ' }', ' ', ' public DataWrapper <KeyType, DataType> get (int pos) {', ' return myData.get (pos);', ' }', ' ', ' public void replaceKey (int pos, KeyType keyToAdd) {', ' DataWrapper <KeyType, DataType> temp = myData.remove (pos);', ' DataWrapper <KeyType, DataType> newOne = new DataWrapper <KeyType, DataType> (keyToAdd, temp.getData ());', ' myData.add (pos, newOne);', ' }', ' ', ' public void add (KeyType keyToAdd, DataType dataToAdd) {', ' ', ' // if this is the first add, then set everyone up', ' if (myData == null) {', ' PointInMetricSpace myCentroid = keyToAdd.getPointInInterior ();', ' myBoundingSphere = new SphereABCD <PointInMetricSpace> (myCentroid, keyToAdd.maxDistanceTo (myCentroid));', ' myData = new ArrayList <DataWrapper <KeyType, DataType>> ();', ' ', ' // otherwise, extend the sphere if needed', ' } else {', ' myBoundingSphere.swallow (keyToAdd);', ' }', ' ', ' // add the data', ' myData.add (new DataWrapper <KeyType, DataType> (keyToAdd, dataToAdd));', ' }', ' ', ' // we want to potentially allow many implementations of the splitting lalgorithm', ' abstract public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // this is here so the actual splitting algorithn can access the list and change the sphere', ' protected ArrayList <DataWrapper <KeyType, DataType>> getList () {', ' return myData;', ' }', ' ', ' // this is here so the splitting algorithm can modify the list and the sphere', ' protected void replaceGuts (AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> withMe) {', ' myData = withMe.myData;', ' myBoundingSphere = withMe.myBoundingSphere;', ' }', ' ', '}', '', '// this is a particular implementation of the metric data list that uses a simple quadratic clustering', '// algorithm to perform a list split. It picks two "seeds" (the most distant objects) and then repeatedly', '// adds to the two new lists by choosing the objects closest to the seeds', 'class ChrisMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> extends AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> {', '', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo () {', ' ', ' // first, we need to find the two most distant points in the list', ' ArrayList <DataWrapper <KeyType, DataType>> myData = getList ();', ' int bestI = 0, bestJ = 0;', ' double maxDist = -1.0;', ' for (int i = 0; i < myData.size (); i++) {', ' for (int j = i + 1; j < myData.size (); j++) {', ' ', ' // get the two keys', ' DataWrapper <KeyType, DataType> pointOne = myData.get (i);', ' DataWrapper <KeyType, DataType> pointTwo = myData.get (j);', ' ', ' // find the difference between them', ' double curDist = pointOne.getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', '', ' // see if it is the biggest', ' if (curDist > maxDist) {', ' maxDist = curDist;', ' bestI = i;', ' bestJ = j;', ' }', ' }', ' }', ' ', ' // now, we have the best two points; those are seeds for the clustering', ' DataWrapper <KeyType, DataType> pointOne = myData.remove (bestI);', ' DataWrapper <KeyType, DataType> pointTwo = myData.remove (bestJ - 1);', ' ', ' // these are the two new lists', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listOne = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listTwo = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' ', ' // put the two seeds in', ' listOne.add (pointOne.getKey (), pointOne.getData ());', ' listTwo.add (pointTwo.getKey (), pointTwo.getData ());', ' ', ' // and add everyone else in', ' while (myData.size () != 0) {', ' ', ' // find the one closest to the first seed', ' int bestIndex = 0;', ' double bestDist = 9e99;', ' ', ' // loop thru all of the candidate data objects', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listOne.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' ', ' // break if no more data', ' if (myData.size () == 0)', ' break;', ' ', ' // loop thru all of the candidate data objects', ' bestDist = 9e99;', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listTwo.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' }', ' ', ' // now we replace our own guts with the first list', ' replaceGuts (listOne);', ' ', ' // and return the other list', ' return listTwo;', ' }', '}', '', 'interface IMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> {', ' ', ' // add a new pair to the list', ' public void add (KeyType keyToAdd, DataType dataToAdd);', ' ', ' // replace a key at the indicated position', ' public void replaceKey (int pos, KeyType keyToAdd);', ' ', ' // get the key, data pair that resides at a particular position', ' public DataWrapper <KeyType, DataType> get (int pos);', ' ', ' // return the number of items in the list', ' public int size ();', ' ', ' // split the list in two, using some clutering algorithm', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // get a sphere that totally bounds all of the objects in the list', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class MTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public MTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class SCMTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public SCMTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', '', 'public class MTreeTester extends TestCase {', ' ', ' // compare two lists of strings to see if the contents are the same', ' private boolean compareStringSets (ArrayList <String> setOne, ArrayList <String> setTwo) {', ' ', ' // sort the sets and make sure they are the same', ' boolean returnVal = true;', ' if (setOne.size () == setTwo.size ()) {', ' Collections.sort (setOne);', ' Collections.sort (setTwo);', ' for (int i = 0; i < setOne.size (); i++) {', ' if (!setOne.get (i).equals (setTwo.get (i))) {', ' returnVal = false;', ' break; ', ' }', ' }', ' } else {', ' returnVal = false;', ' }', ' ', ' // print out the result', ' System.out.println ("**** Expected:");', ' for (int i = 0; i < setOne.size (); i++) {', ' System.out.format (setOne.get (i) + " ");', ' }', ' System.out.println ("\\n**** Got:");', ' for (int i = 0; i < setTwo.size (); i++) {', ' System.out.format (setTwo.get (i) + " ");', ' }', ' System.out.println ("");', ' ', ' return returnVal;', ' }', ' ', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST SIMPLE ONE DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testOneDimRangeQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.find (query, expectedQuerySize / 2);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.find (query, expectedQuerySize / 2);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (numPoints);', ' result1 = myTree.find (query, expectedQuerySize);', ' result2 = hisTree.find (query, expectedQuerySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // like the last one, but runs a top k', ' private void testOneDimTopKQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (167);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.findKClosest (query, querySize);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (0);', ' result1 = myTree.findKClosest (query, querySize);', ' result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST MULTI-DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimRangeQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' double dist1 = 0;', ' double dist2 = 0;', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' dist1 = Math.sqrt (numDims) * expectedQuerySize / 2.0;', ' dist2 = Math.sqrt (numDims) * expectedQuerySize;', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' // do a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, (int) expectedQuerySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = myTree.findKClosest (query2, (int) expectedQuerySize);', ' ', ' // find the distance to the furthest point in both cases', ' for (int i = 0; i < (int) expectedQuerySize; i++) {', ' double newDist = result1.get (i).getKey ().getDistance (query1);', ' if (newDist > dist1)', ' dist1 = newDist;', ' newDist = result2.get (i).getKey ().getDistance (query2);', ' if (newDist > dist2)', ' dist2 = newDist;', ' }', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.find (query1, dist1);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.find (query1, dist1);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.find (query2, dist2);', ' result2 = hisTree.find (query2, dist2);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimTopKQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, querySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.findKClosest (query1, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.findKClosest (query2, querySize);', ' result2 = hisTree.findKClosest (query2, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' ', ' /**', ' * "TIER 1" TESTS', ' * NONE OF THESE REQUIRE ANY SPLITS', ' */', ' public void testEasy1() {', ' testOneDimRangeQuery (true, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy2() {', ' testOneDimRangeQuery (false, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy3() {', ' testOneDimRangeQuery (true, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy4() {', ' testOneDimRangeQuery (false, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy5() {', ' testMultiDimRangeQuery (true, 1, 5, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy6() {', ' testMultiDimRangeQuery (false, 1, 10, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy7() {', ' testMultiDimRangeQuery (true, 1, 5, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy8() {', ' testMultiDimRangeQuery (false, 1, 15, 10000, 10000, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 2" TESTS', ' * NONE OF THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testMod1() {', ' testOneDimRangeQuery (true, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod2() {', ' testOneDimRangeQuery (false, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod3() {', ' testOneDimRangeQuery (true, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod4() {', ' testOneDimRangeQuery (false, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod5() {', ' testMultiDimRangeQuery (true, 2, 5, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod6() {', ' testMultiDimRangeQuery (false, 2, 10, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod7() {', ' testMultiDimRangeQuery (true, 2, 5, 10000, 100, 1000, 10);', ' }', ' ', ' public void testMod8() {', ' testMultiDimRangeQuery (false, 2, 15, 10000, 100, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 3" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testHard1() {', ' testOneDimRangeQuery (true, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard2() {', ' testOneDimRangeQuery (false, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard3() {', ' testOneDimRangeQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard4() {', ' testOneDimRangeQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard5() {', ' testMultiDimRangeQuery (true, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard6() {', ' testMultiDimRangeQuery (false, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard7() {', ' testMultiDimRangeQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard8() {', ' testMultiDimRangeQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', ' ', ' /**', ' * "TIER 4" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE AND THEY TEST THE TOPK FUNCTIONALITY', ' */', ' ', ' public void testTopK1() {', ' testOneDimTopKQuery (true, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK2() {', ' testOneDimTopKQuery (false, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK3() {', ' testOneDimTopKQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK4() {', ' testOneDimTopKQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK5() {', ' testMultiDimTopKQuery (true, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK6() {', ' testMultiDimTopKQuery (false, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK7() {', ' testMultiDimTopKQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK8() {', ' testMultiDimTopKQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', '}'] | [{'reason_category': 'If Body', 'usage_line': 565}] | Global_Variable 'myData' used at line 565 is defined at line 554 and has a Medium-Range dependency. | {'If Body': 1} | {'Global_Variable Medium-Range': 1} |
infilling_java | MTreeTester | 567 | 567 | ['import junit.framework.TestCase;', 'import java.util.ArrayList;', 'import java.util.Random;', 'import java.util.Collections;', '', '// this is a map from a set of keys of type PointInMetricSpace to a', '// set of data of type DataType', 'interface IMTree <Key extends IPointInMetricSpace <Key>, Data> {', ' ', ' // insert a new key/data pair into the map', ' void insert (Key keyToAdd, Data dataToAdd);', ' ', ' // find all of the key/data pairs in the map that fall within a', ' // particular distance of query point if no results are found, then', ' // an empty array is returned (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> find (Key query, double distance);', ' ', ' // find the k closest key/data pairs in the map to a particular', ' // query point ', ' //', ' // if the number of points in the map is less than k, then the', ' // returned list will have less than k pairs in it', ' //', ' // if the number of points is zero, then an empty array is returned', ' // (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> findKClosest (Key query, int k);', ' ', ' // returns the number of nodes that exist on a path from root to leaf in the tree...', ' // whtever the details of the implementation are, a tree with a single leaf node should return 1, and a tree', ' // with more than one lead node should return at least two (since it must have at least one internal node).', ' public int depth ();', ' ', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', '', 'interface IDoubleVector {', '', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '', '// this correponds to some geometric object in a metric space; the object is built out of', '// one or more points of type PointInMetricSpace', 'interface IObjectInMetricSpaceABCD <PointInMetricSpace extends IPointInMetricSpace<PointInMetricSpace>> {', ' ', ' // get the maximum distance from some point on the shape to a particular point in the metric space', ' double maxDistanceTo (PointInMetricSpace checkMe);', ' ', ' // return some arbitrary point on the interior of the geometric object', ' PointInMetricSpace getPointInInterior ();', '}', '', '', '// this interface corresponds to a point in some metric space', 'interface IPointInMetricSpace <PointInMetricSpace> {', ' ', ' // get the distance to another point', ' // ', ' // for this to work in an M-Tree, distances should be "metric" and', ' // obey the triangle inequality', ' double getDistance (PointInMetricSpace toMe);', '}', '', '// this is the basic node type in the structure', 'interface IMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> {', ' ', ' // insert a new key/data pair into the structure. The return value is a new MTreeNode if there was', ' // a split in response to the insertion, or a null if there was no split', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd);', ' ', ' // find all of the key/data pairs in the structure that fall within a particular query sphere', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query); ', ' ', ' // find the set of items closest to the given query point', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ);', ' ', ' // returns a sphere that totally encompasses everything in the node and its subtree', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', ' ', ' // returns the depth', ' public int depth ();', '}', '', '// this is a point in a particular metric space', 'class PointABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the point', ' private PointInMetricSpace me;', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return me; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return checkMe.getDistance (me); ', ' }', ' ', ' // contruct a point', ' public PointABCD (PointInMetricSpace useMe) {', ' me = useMe; ', ' }', '}', '', 'class PQueueABCD <PointInMetricSpace, DataType> {', ' ', ' // this is an object in the queue', ' private class Wrapper {', ' DataWrapper <PointInMetricSpace, DataType> myData;', ' double distance;', ' }', ' ', ' // this is the actual queue', ' ArrayList <Wrapper> myList;', ' ', ' // this is the largest distance value currently in the queue', ' double large;', ' ', ' // this is the max number of objects', ' int maxCount;', ' ', ' // create a priority queue with the speced number of slots', ' PQueueABCD (int maxCountIn) {', ' maxCount = maxCountIn;', ' myList = new ArrayList <Wrapper> ();', ' large = 9e99;', ' }', ' ', ' // get the largest distance in the queue', ' double getDist () {', ' return large;', ' }', ' ', ' // add a new object to the queue... the insertion is ignored if the distance value', ' // exceeds the largest that is in the queue and the queue is already full', ' void insert (PointInMetricSpace key, DataType data, double distance) {', ' ', ' // if we are full, remove the one with the largest distance', ' if (myList.size () == maxCount && distance < large) {', ' ', ' int badIndex = 0;', ' double maxDist = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > maxDist) {', ' maxDist = myList.get (i).distance;', ' badIndex = i;', ' }', ' }', ' ', ' myList.remove (badIndex);', ' }', ' ', ' // see if there is room', ' if (myList.size () < maxCount) {', ' ', ' // add it ', ' Wrapper newOne = new Wrapper ();', ' newOne.myData = new DataWrapper <PointInMetricSpace, DataType> (key, data);', ' newOne.distance = distance;', ' myList.add (newOne); ', ' }', ' ', ' // if we are full, reset the max distance', ' if (myList.size () == maxCount) {', ' large = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > large) {', ' large = myList.get (i).distance;', ' }', ' }', ' }', ' ', ' }', ' ', ' // extracts the contents of the queue', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> done () {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' for (int i = 0; i < myList.size (); i++) {', ' returnVal.add (myList.get (i).myData); ', ' }', ' ', ' return returnVal;', ' }', ' ', '}', '', '// this is a sphere in a particular metric space', 'class SphereABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the center of the sphere and its radius', ' private PointInMetricSpace center;', ' private double radius;', ' ', ' // build a sphere out of its center and its radius', ' public SphereABCD (PointInMetricSpace centerIn, double radiusIn) {', ' center = centerIn;', ' radius = radiusIn;', ' }', ' ', ' // increase the size of the sphere so it contains the object swallowMe', ' public void swallow (IObjectInMetricSpaceABCD <PointInMetricSpace> swallowMe) {', ' ', ' // see if we need to increase the radius to swallow this guy', ' double dist = swallowMe.maxDistanceTo (center);', ' if (dist > radius)', ' radius = dist;', ' }', ' ', ' // check to see if a sphere intersects another sphere', ' public boolean intersects (SphereABCD <PointInMetricSpace> me) {', ' return (me.center.getDistance (center) <= me.radius + radius);', ' }', ' ', ' // check to see if the sphere contains a point', ' public boolean contains (PointInMetricSpace checkMe) {', ' return (checkMe.getDistance (center) <= radius);', ' }', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return center; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return radius + checkMe.getDistance (center); ', ' }', '}', '', '', '', 'class OneDimPoint implements IPointInMetricSpace <OneDimPoint> {', ' ', ' // this is the actual double', ' Double value;', ' ', ' // construct this out of a double value', ' public OneDimPoint (double makeFromMe) {', ' value = new Double (makeFromMe);', ' }', ' ', ' // get the distance to another point', ' public double getDistance (OneDimPoint toMe) {', ' if (value > toMe.value)', ' return value - toMe.value;', ' else', ' return toMe.value - value;', ' }', ' ', '}', '', 'class MultiDimPoint implements IPointInMetricSpace <MultiDimPoint> {', ' ', ' // this is the point in a multidimensional space', ' IDoubleVector me;', ' ', ' // make this out of an IDoubleVector', ' public MultiDimPoint (IDoubleVector useMe) {', ' me = useMe;', ' }', ' ', ' // get the Euclidean distance to another point', ' public double getDistance (MultiDimPoint toMe) {', ' double distance = 0.0;', ' try {', ' for (int i = 0; i < me.getLength (); i++) {', ' double diff = me.getItem (i) - toMe.me.getItem (i);', ' diff *= diff;', ' distance += diff;', ' }', ' } catch (OutOfBoundsException e) {', ' throw new IndexOutOfBoundsException ("Can\'t compare two MultiDimPoint objects with different dimensionality!"); ', ' }', ' return Math.sqrt(distance);', ' }', ' ', '}', '// this is a leaf node', 'class LeafMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements ', ' IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myData;', ' ', ' // contructor that takes a data list and builds a node out of it', ' private LeafMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myDataIn) {', ' myData = myDataIn; ', ' }', ' ', ' // constructor that creates an empty node', ' public LeafMTreeNodeABCD () {', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> (); ', ' }', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // just add in the new data', ' myData.add (new PointABCD <PointInMetricSpace> (keyToAdd), dataToAdd);', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> newOne = myData.splitInTwo ();', ' LeafMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' myQ.insert (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData (), ', ' query.getDistance (myData.get (i).getKey ().getPointInInterior ()));', ' }', ' }', ' }', ' ', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' returnVal.add (new DataWrapper <PointInMetricSpace, DataType> (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData ()));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return 1; ', ' }', '', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', '// this silly little class is just a wrapper for a key, data pair', 'class DataWrapper <Key, Data> {', ' ', ' Key key;', ' Data data;', ' ', ' public DataWrapper (Key keyIn, Data dataIn) {', ' key = keyIn;', ' data = dataIn;', ' }', ' ', ' public Key getKey () {', ' return key;', ' }', ' ', ' public Data getData () {', ' return data;', ' }', '}', '', '', '// this is an internal node', 'class InternalMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType>', ' implements IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> myData;', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' // this constructs a new internal node that holds precisely the two nodes that are passed in', ' public InternalMTreeNodeABCD (IMTreeNodeABCD <PointInMetricSpace, DataType> refOne,', ' IMTreeNodeABCD <PointInMetricSpace, DataType> refTwo) {', ' ', ' // create a necw list and add the two guys in', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> ();', ' myData.add (refOne.getBoundingSphere (), refOne);', ' myData.add (refTwo.getBoundingSphere (), refTwo);', ' }', ' ', ' // this constructs a new node that holds the list of data that we were passed in', ' public InternalMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> useMe) {', ' myData = useMe; ', ' }', ' ', ' // from the interface', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // find the best child; this is the one we are closest to', ' double bestDist = 9e99;', ' int bestIndex = 0;', ' for (int i = 0; i < myData.size (); i++) {', ' ', ' double newDist = myData.get (i).getKey ().getPointInInterior ().getDistance (keyToAdd);', ' if (newDist < bestDist) {', ' bestDist = newDist;', ' bestIndex = i;', ' }', ' }', ' ', ' // do the recursive insert', ' IMTreeNodeABCD <PointInMetricSpace, DataType> newRef = myData.get (bestIndex).getData ().insert (keyToAdd, dataToAdd);', ' ', ' // if we got something back, then there was a split, so add the new node into our list', ' if (newRef != null) {', ' myData.add (newRef.getBoundingSphere (), newRef);', ' }', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> newOne = myData.splitInTwo ();', ' InternalMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.intersects (myData.get (i).getKey ())) {', ' myData.get (i).getData ().findKClosest (query, myQ);', ' }', ' }', ' }', ' ', ' // from the interface', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.intersects (myData.get (i).getKey ())) {', ' returnVal.addAll (myData.get (i).getData ().find (query));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return myData.get (0).getData ().depth () + 1; ', ' }', ' ', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', 'abstract class AMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> implements IMetricDataListABCD <PointInMetricSpace,KeyType, DataType> {', '', ' // this is the data that is actually stored in the list', ' private ArrayList <DataWrapper <KeyType, DataType>> myData;', ' ', ' // this is the sphere that bounds everything in the list', ' private SphereABCD <PointInMetricSpace> myBoundingSphere;', ' ', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myBoundingSphere; ', ' }', ' ', ' public int size () {', ' if (myData != null)', ' return myData.size (); ', ' else'] | [' return 0;'] | [' }', ' ', ' public DataWrapper <KeyType, DataType> get (int pos) {', ' return myData.get (pos);', ' }', ' ', ' public void replaceKey (int pos, KeyType keyToAdd) {', ' DataWrapper <KeyType, DataType> temp = myData.remove (pos);', ' DataWrapper <KeyType, DataType> newOne = new DataWrapper <KeyType, DataType> (keyToAdd, temp.getData ());', ' myData.add (pos, newOne);', ' }', ' ', ' public void add (KeyType keyToAdd, DataType dataToAdd) {', ' ', ' // if this is the first add, then set everyone up', ' if (myData == null) {', ' PointInMetricSpace myCentroid = keyToAdd.getPointInInterior ();', ' myBoundingSphere = new SphereABCD <PointInMetricSpace> (myCentroid, keyToAdd.maxDistanceTo (myCentroid));', ' myData = new ArrayList <DataWrapper <KeyType, DataType>> ();', ' ', ' // otherwise, extend the sphere if needed', ' } else {', ' myBoundingSphere.swallow (keyToAdd);', ' }', ' ', ' // add the data', ' myData.add (new DataWrapper <KeyType, DataType> (keyToAdd, dataToAdd));', ' }', ' ', ' // we want to potentially allow many implementations of the splitting lalgorithm', ' abstract public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // this is here so the actual splitting algorithn can access the list and change the sphere', ' protected ArrayList <DataWrapper <KeyType, DataType>> getList () {', ' return myData;', ' }', ' ', ' // this is here so the splitting algorithm can modify the list and the sphere', ' protected void replaceGuts (AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> withMe) {', ' myData = withMe.myData;', ' myBoundingSphere = withMe.myBoundingSphere;', ' }', ' ', '}', '', '// this is a particular implementation of the metric data list that uses a simple quadratic clustering', '// algorithm to perform a list split. It picks two "seeds" (the most distant objects) and then repeatedly', '// adds to the two new lists by choosing the objects closest to the seeds', 'class ChrisMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> extends AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> {', '', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo () {', ' ', ' // first, we need to find the two most distant points in the list', ' ArrayList <DataWrapper <KeyType, DataType>> myData = getList ();', ' int bestI = 0, bestJ = 0;', ' double maxDist = -1.0;', ' for (int i = 0; i < myData.size (); i++) {', ' for (int j = i + 1; j < myData.size (); j++) {', ' ', ' // get the two keys', ' DataWrapper <KeyType, DataType> pointOne = myData.get (i);', ' DataWrapper <KeyType, DataType> pointTwo = myData.get (j);', ' ', ' // find the difference between them', ' double curDist = pointOne.getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', '', ' // see if it is the biggest', ' if (curDist > maxDist) {', ' maxDist = curDist;', ' bestI = i;', ' bestJ = j;', ' }', ' }', ' }', ' ', ' // now, we have the best two points; those are seeds for the clustering', ' DataWrapper <KeyType, DataType> pointOne = myData.remove (bestI);', ' DataWrapper <KeyType, DataType> pointTwo = myData.remove (bestJ - 1);', ' ', ' // these are the two new lists', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listOne = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listTwo = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' ', ' // put the two seeds in', ' listOne.add (pointOne.getKey (), pointOne.getData ());', ' listTwo.add (pointTwo.getKey (), pointTwo.getData ());', ' ', ' // and add everyone else in', ' while (myData.size () != 0) {', ' ', ' // find the one closest to the first seed', ' int bestIndex = 0;', ' double bestDist = 9e99;', ' ', ' // loop thru all of the candidate data objects', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listOne.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' ', ' // break if no more data', ' if (myData.size () == 0)', ' break;', ' ', ' // loop thru all of the candidate data objects', ' bestDist = 9e99;', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listTwo.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' }', ' ', ' // now we replace our own guts with the first list', ' replaceGuts (listOne);', ' ', ' // and return the other list', ' return listTwo;', ' }', '}', '', 'interface IMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> {', ' ', ' // add a new pair to the list', ' public void add (KeyType keyToAdd, DataType dataToAdd);', ' ', ' // replace a key at the indicated position', ' public void replaceKey (int pos, KeyType keyToAdd);', ' ', ' // get the key, data pair that resides at a particular position', ' public DataWrapper <KeyType, DataType> get (int pos);', ' ', ' // return the number of items in the list', ' public int size ();', ' ', ' // split the list in two, using some clutering algorithm', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // get a sphere that totally bounds all of the objects in the list', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class MTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public MTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class SCMTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public SCMTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', '', 'public class MTreeTester extends TestCase {', ' ', ' // compare two lists of strings to see if the contents are the same', ' private boolean compareStringSets (ArrayList <String> setOne, ArrayList <String> setTwo) {', ' ', ' // sort the sets and make sure they are the same', ' boolean returnVal = true;', ' if (setOne.size () == setTwo.size ()) {', ' Collections.sort (setOne);', ' Collections.sort (setTwo);', ' for (int i = 0; i < setOne.size (); i++) {', ' if (!setOne.get (i).equals (setTwo.get (i))) {', ' returnVal = false;', ' break; ', ' }', ' }', ' } else {', ' returnVal = false;', ' }', ' ', ' // print out the result', ' System.out.println ("**** Expected:");', ' for (int i = 0; i < setOne.size (); i++) {', ' System.out.format (setOne.get (i) + " ");', ' }', ' System.out.println ("\\n**** Got:");', ' for (int i = 0; i < setTwo.size (); i++) {', ' System.out.format (setTwo.get (i) + " ");', ' }', ' System.out.println ("");', ' ', ' return returnVal;', ' }', ' ', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST SIMPLE ONE DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testOneDimRangeQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.find (query, expectedQuerySize / 2);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.find (query, expectedQuerySize / 2);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (numPoints);', ' result1 = myTree.find (query, expectedQuerySize);', ' result2 = hisTree.find (query, expectedQuerySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // like the last one, but runs a top k', ' private void testOneDimTopKQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (167);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.findKClosest (query, querySize);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (0);', ' result1 = myTree.findKClosest (query, querySize);', ' result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST MULTI-DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimRangeQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' double dist1 = 0;', ' double dist2 = 0;', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' dist1 = Math.sqrt (numDims) * expectedQuerySize / 2.0;', ' dist2 = Math.sqrt (numDims) * expectedQuerySize;', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' // do a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, (int) expectedQuerySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = myTree.findKClosest (query2, (int) expectedQuerySize);', ' ', ' // find the distance to the furthest point in both cases', ' for (int i = 0; i < (int) expectedQuerySize; i++) {', ' double newDist = result1.get (i).getKey ().getDistance (query1);', ' if (newDist > dist1)', ' dist1 = newDist;', ' newDist = result2.get (i).getKey ().getDistance (query2);', ' if (newDist > dist2)', ' dist2 = newDist;', ' }', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.find (query1, dist1);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.find (query1, dist1);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.find (query2, dist2);', ' result2 = hisTree.find (query2, dist2);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimTopKQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, querySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.findKClosest (query1, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.findKClosest (query2, querySize);', ' result2 = hisTree.findKClosest (query2, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' ', ' /**', ' * "TIER 1" TESTS', ' * NONE OF THESE REQUIRE ANY SPLITS', ' */', ' public void testEasy1() {', ' testOneDimRangeQuery (true, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy2() {', ' testOneDimRangeQuery (false, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy3() {', ' testOneDimRangeQuery (true, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy4() {', ' testOneDimRangeQuery (false, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy5() {', ' testMultiDimRangeQuery (true, 1, 5, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy6() {', ' testMultiDimRangeQuery (false, 1, 10, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy7() {', ' testMultiDimRangeQuery (true, 1, 5, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy8() {', ' testMultiDimRangeQuery (false, 1, 15, 10000, 10000, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 2" TESTS', ' * NONE OF THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testMod1() {', ' testOneDimRangeQuery (true, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod2() {', ' testOneDimRangeQuery (false, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod3() {', ' testOneDimRangeQuery (true, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod4() {', ' testOneDimRangeQuery (false, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod5() {', ' testMultiDimRangeQuery (true, 2, 5, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod6() {', ' testMultiDimRangeQuery (false, 2, 10, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod7() {', ' testMultiDimRangeQuery (true, 2, 5, 10000, 100, 1000, 10);', ' }', ' ', ' public void testMod8() {', ' testMultiDimRangeQuery (false, 2, 15, 10000, 100, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 3" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testHard1() {', ' testOneDimRangeQuery (true, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard2() {', ' testOneDimRangeQuery (false, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard3() {', ' testOneDimRangeQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard4() {', ' testOneDimRangeQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard5() {', ' testMultiDimRangeQuery (true, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard6() {', ' testMultiDimRangeQuery (false, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard7() {', ' testMultiDimRangeQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard8() {', ' testMultiDimRangeQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', ' ', ' /**', ' * "TIER 4" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE AND THEY TEST THE TOPK FUNCTIONALITY', ' */', ' ', ' public void testTopK1() {', ' testOneDimTopKQuery (true, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK2() {', ' testOneDimTopKQuery (false, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK3() {', ' testOneDimTopKQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK4() {', ' testOneDimTopKQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK5() {', ' testMultiDimTopKQuery (true, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK6() {', ' testMultiDimTopKQuery (false, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK7() {', ' testMultiDimTopKQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK8() {', ' testMultiDimTopKQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', '}'] | [{'reason_category': 'Else Reasoning', 'usage_line': 567}] | null | {'Else Reasoning': 1} | null |
infilling_java | MTreeTester | 571 | 572 | ['import junit.framework.TestCase;', 'import java.util.ArrayList;', 'import java.util.Random;', 'import java.util.Collections;', '', '// this is a map from a set of keys of type PointInMetricSpace to a', '// set of data of type DataType', 'interface IMTree <Key extends IPointInMetricSpace <Key>, Data> {', ' ', ' // insert a new key/data pair into the map', ' void insert (Key keyToAdd, Data dataToAdd);', ' ', ' // find all of the key/data pairs in the map that fall within a', ' // particular distance of query point if no results are found, then', ' // an empty array is returned (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> find (Key query, double distance);', ' ', ' // find the k closest key/data pairs in the map to a particular', ' // query point ', ' //', ' // if the number of points in the map is less than k, then the', ' // returned list will have less than k pairs in it', ' //', ' // if the number of points is zero, then an empty array is returned', ' // (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> findKClosest (Key query, int k);', ' ', ' // returns the number of nodes that exist on a path from root to leaf in the tree...', ' // whtever the details of the implementation are, a tree with a single leaf node should return 1, and a tree', ' // with more than one lead node should return at least two (since it must have at least one internal node).', ' public int depth ();', ' ', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', '', 'interface IDoubleVector {', '', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '', '// this correponds to some geometric object in a metric space; the object is built out of', '// one or more points of type PointInMetricSpace', 'interface IObjectInMetricSpaceABCD <PointInMetricSpace extends IPointInMetricSpace<PointInMetricSpace>> {', ' ', ' // get the maximum distance from some point on the shape to a particular point in the metric space', ' double maxDistanceTo (PointInMetricSpace checkMe);', ' ', ' // return some arbitrary point on the interior of the geometric object', ' PointInMetricSpace getPointInInterior ();', '}', '', '', '// this interface corresponds to a point in some metric space', 'interface IPointInMetricSpace <PointInMetricSpace> {', ' ', ' // get the distance to another point', ' // ', ' // for this to work in an M-Tree, distances should be "metric" and', ' // obey the triangle inequality', ' double getDistance (PointInMetricSpace toMe);', '}', '', '// this is the basic node type in the structure', 'interface IMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> {', ' ', ' // insert a new key/data pair into the structure. The return value is a new MTreeNode if there was', ' // a split in response to the insertion, or a null if there was no split', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd);', ' ', ' // find all of the key/data pairs in the structure that fall within a particular query sphere', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query); ', ' ', ' // find the set of items closest to the given query point', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ);', ' ', ' // returns a sphere that totally encompasses everything in the node and its subtree', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', ' ', ' // returns the depth', ' public int depth ();', '}', '', '// this is a point in a particular metric space', 'class PointABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the point', ' private PointInMetricSpace me;', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return me; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return checkMe.getDistance (me); ', ' }', ' ', ' // contruct a point', ' public PointABCD (PointInMetricSpace useMe) {', ' me = useMe; ', ' }', '}', '', 'class PQueueABCD <PointInMetricSpace, DataType> {', ' ', ' // this is an object in the queue', ' private class Wrapper {', ' DataWrapper <PointInMetricSpace, DataType> myData;', ' double distance;', ' }', ' ', ' // this is the actual queue', ' ArrayList <Wrapper> myList;', ' ', ' // this is the largest distance value currently in the queue', ' double large;', ' ', ' // this is the max number of objects', ' int maxCount;', ' ', ' // create a priority queue with the speced number of slots', ' PQueueABCD (int maxCountIn) {', ' maxCount = maxCountIn;', ' myList = new ArrayList <Wrapper> ();', ' large = 9e99;', ' }', ' ', ' // get the largest distance in the queue', ' double getDist () {', ' return large;', ' }', ' ', ' // add a new object to the queue... the insertion is ignored if the distance value', ' // exceeds the largest that is in the queue and the queue is already full', ' void insert (PointInMetricSpace key, DataType data, double distance) {', ' ', ' // if we are full, remove the one with the largest distance', ' if (myList.size () == maxCount && distance < large) {', ' ', ' int badIndex = 0;', ' double maxDist = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > maxDist) {', ' maxDist = myList.get (i).distance;', ' badIndex = i;', ' }', ' }', ' ', ' myList.remove (badIndex);', ' }', ' ', ' // see if there is room', ' if (myList.size () < maxCount) {', ' ', ' // add it ', ' Wrapper newOne = new Wrapper ();', ' newOne.myData = new DataWrapper <PointInMetricSpace, DataType> (key, data);', ' newOne.distance = distance;', ' myList.add (newOne); ', ' }', ' ', ' // if we are full, reset the max distance', ' if (myList.size () == maxCount) {', ' large = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > large) {', ' large = myList.get (i).distance;', ' }', ' }', ' }', ' ', ' }', ' ', ' // extracts the contents of the queue', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> done () {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' for (int i = 0; i < myList.size (); i++) {', ' returnVal.add (myList.get (i).myData); ', ' }', ' ', ' return returnVal;', ' }', ' ', '}', '', '// this is a sphere in a particular metric space', 'class SphereABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the center of the sphere and its radius', ' private PointInMetricSpace center;', ' private double radius;', ' ', ' // build a sphere out of its center and its radius', ' public SphereABCD (PointInMetricSpace centerIn, double radiusIn) {', ' center = centerIn;', ' radius = radiusIn;', ' }', ' ', ' // increase the size of the sphere so it contains the object swallowMe', ' public void swallow (IObjectInMetricSpaceABCD <PointInMetricSpace> swallowMe) {', ' ', ' // see if we need to increase the radius to swallow this guy', ' double dist = swallowMe.maxDistanceTo (center);', ' if (dist > radius)', ' radius = dist;', ' }', ' ', ' // check to see if a sphere intersects another sphere', ' public boolean intersects (SphereABCD <PointInMetricSpace> me) {', ' return (me.center.getDistance (center) <= me.radius + radius);', ' }', ' ', ' // check to see if the sphere contains a point', ' public boolean contains (PointInMetricSpace checkMe) {', ' return (checkMe.getDistance (center) <= radius);', ' }', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return center; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return radius + checkMe.getDistance (center); ', ' }', '}', '', '', '', 'class OneDimPoint implements IPointInMetricSpace <OneDimPoint> {', ' ', ' // this is the actual double', ' Double value;', ' ', ' // construct this out of a double value', ' public OneDimPoint (double makeFromMe) {', ' value = new Double (makeFromMe);', ' }', ' ', ' // get the distance to another point', ' public double getDistance (OneDimPoint toMe) {', ' if (value > toMe.value)', ' return value - toMe.value;', ' else', ' return toMe.value - value;', ' }', ' ', '}', '', 'class MultiDimPoint implements IPointInMetricSpace <MultiDimPoint> {', ' ', ' // this is the point in a multidimensional space', ' IDoubleVector me;', ' ', ' // make this out of an IDoubleVector', ' public MultiDimPoint (IDoubleVector useMe) {', ' me = useMe;', ' }', ' ', ' // get the Euclidean distance to another point', ' public double getDistance (MultiDimPoint toMe) {', ' double distance = 0.0;', ' try {', ' for (int i = 0; i < me.getLength (); i++) {', ' double diff = me.getItem (i) - toMe.me.getItem (i);', ' diff *= diff;', ' distance += diff;', ' }', ' } catch (OutOfBoundsException e) {', ' throw new IndexOutOfBoundsException ("Can\'t compare two MultiDimPoint objects with different dimensionality!"); ', ' }', ' return Math.sqrt(distance);', ' }', ' ', '}', '// this is a leaf node', 'class LeafMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements ', ' IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myData;', ' ', ' // contructor that takes a data list and builds a node out of it', ' private LeafMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myDataIn) {', ' myData = myDataIn; ', ' }', ' ', ' // constructor that creates an empty node', ' public LeafMTreeNodeABCD () {', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> (); ', ' }', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // just add in the new data', ' myData.add (new PointABCD <PointInMetricSpace> (keyToAdd), dataToAdd);', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> newOne = myData.splitInTwo ();', ' LeafMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' myQ.insert (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData (), ', ' query.getDistance (myData.get (i).getKey ().getPointInInterior ()));', ' }', ' }', ' }', ' ', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' returnVal.add (new DataWrapper <PointInMetricSpace, DataType> (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData ()));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return 1; ', ' }', '', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', '// this silly little class is just a wrapper for a key, data pair', 'class DataWrapper <Key, Data> {', ' ', ' Key key;', ' Data data;', ' ', ' public DataWrapper (Key keyIn, Data dataIn) {', ' key = keyIn;', ' data = dataIn;', ' }', ' ', ' public Key getKey () {', ' return key;', ' }', ' ', ' public Data getData () {', ' return data;', ' }', '}', '', '', '// this is an internal node', 'class InternalMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType>', ' implements IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> myData;', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' // this constructs a new internal node that holds precisely the two nodes that are passed in', ' public InternalMTreeNodeABCD (IMTreeNodeABCD <PointInMetricSpace, DataType> refOne,', ' IMTreeNodeABCD <PointInMetricSpace, DataType> refTwo) {', ' ', ' // create a necw list and add the two guys in', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> ();', ' myData.add (refOne.getBoundingSphere (), refOne);', ' myData.add (refTwo.getBoundingSphere (), refTwo);', ' }', ' ', ' // this constructs a new node that holds the list of data that we were passed in', ' public InternalMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> useMe) {', ' myData = useMe; ', ' }', ' ', ' // from the interface', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // find the best child; this is the one we are closest to', ' double bestDist = 9e99;', ' int bestIndex = 0;', ' for (int i = 0; i < myData.size (); i++) {', ' ', ' double newDist = myData.get (i).getKey ().getPointInInterior ().getDistance (keyToAdd);', ' if (newDist < bestDist) {', ' bestDist = newDist;', ' bestIndex = i;', ' }', ' }', ' ', ' // do the recursive insert', ' IMTreeNodeABCD <PointInMetricSpace, DataType> newRef = myData.get (bestIndex).getData ().insert (keyToAdd, dataToAdd);', ' ', ' // if we got something back, then there was a split, so add the new node into our list', ' if (newRef != null) {', ' myData.add (newRef.getBoundingSphere (), newRef);', ' }', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> newOne = myData.splitInTwo ();', ' InternalMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.intersects (myData.get (i).getKey ())) {', ' myData.get (i).getData ().findKClosest (query, myQ);', ' }', ' }', ' }', ' ', ' // from the interface', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.intersects (myData.get (i).getKey ())) {', ' returnVal.addAll (myData.get (i).getData ().find (query));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return myData.get (0).getData ().depth () + 1; ', ' }', ' ', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', 'abstract class AMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> implements IMetricDataListABCD <PointInMetricSpace,KeyType, DataType> {', '', ' // this is the data that is actually stored in the list', ' private ArrayList <DataWrapper <KeyType, DataType>> myData;', ' ', ' // this is the sphere that bounds everything in the list', ' private SphereABCD <PointInMetricSpace> myBoundingSphere;', ' ', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myBoundingSphere; ', ' }', ' ', ' public int size () {', ' if (myData != null)', ' return myData.size (); ', ' else', ' return 0;', ' }', ' ', ' public DataWrapper <KeyType, DataType> get (int pos) {'] | [' return myData.get (pos);', ' }'] | [' ', ' public void replaceKey (int pos, KeyType keyToAdd) {', ' DataWrapper <KeyType, DataType> temp = myData.remove (pos);', ' DataWrapper <KeyType, DataType> newOne = new DataWrapper <KeyType, DataType> (keyToAdd, temp.getData ());', ' myData.add (pos, newOne);', ' }', ' ', ' public void add (KeyType keyToAdd, DataType dataToAdd) {', ' ', ' // if this is the first add, then set everyone up', ' if (myData == null) {', ' PointInMetricSpace myCentroid = keyToAdd.getPointInInterior ();', ' myBoundingSphere = new SphereABCD <PointInMetricSpace> (myCentroid, keyToAdd.maxDistanceTo (myCentroid));', ' myData = new ArrayList <DataWrapper <KeyType, DataType>> ();', ' ', ' // otherwise, extend the sphere if needed', ' } else {', ' myBoundingSphere.swallow (keyToAdd);', ' }', ' ', ' // add the data', ' myData.add (new DataWrapper <KeyType, DataType> (keyToAdd, dataToAdd));', ' }', ' ', ' // we want to potentially allow many implementations of the splitting lalgorithm', ' abstract public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // this is here so the actual splitting algorithn can access the list and change the sphere', ' protected ArrayList <DataWrapper <KeyType, DataType>> getList () {', ' return myData;', ' }', ' ', ' // this is here so the splitting algorithm can modify the list and the sphere', ' protected void replaceGuts (AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> withMe) {', ' myData = withMe.myData;', ' myBoundingSphere = withMe.myBoundingSphere;', ' }', ' ', '}', '', '// this is a particular implementation of the metric data list that uses a simple quadratic clustering', '// algorithm to perform a list split. It picks two "seeds" (the most distant objects) and then repeatedly', '// adds to the two new lists by choosing the objects closest to the seeds', 'class ChrisMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> extends AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> {', '', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo () {', ' ', ' // first, we need to find the two most distant points in the list', ' ArrayList <DataWrapper <KeyType, DataType>> myData = getList ();', ' int bestI = 0, bestJ = 0;', ' double maxDist = -1.0;', ' for (int i = 0; i < myData.size (); i++) {', ' for (int j = i + 1; j < myData.size (); j++) {', ' ', ' // get the two keys', ' DataWrapper <KeyType, DataType> pointOne = myData.get (i);', ' DataWrapper <KeyType, DataType> pointTwo = myData.get (j);', ' ', ' // find the difference between them', ' double curDist = pointOne.getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', '', ' // see if it is the biggest', ' if (curDist > maxDist) {', ' maxDist = curDist;', ' bestI = i;', ' bestJ = j;', ' }', ' }', ' }', ' ', ' // now, we have the best two points; those are seeds for the clustering', ' DataWrapper <KeyType, DataType> pointOne = myData.remove (bestI);', ' DataWrapper <KeyType, DataType> pointTwo = myData.remove (bestJ - 1);', ' ', ' // these are the two new lists', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listOne = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listTwo = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' ', ' // put the two seeds in', ' listOne.add (pointOne.getKey (), pointOne.getData ());', ' listTwo.add (pointTwo.getKey (), pointTwo.getData ());', ' ', ' // and add everyone else in', ' while (myData.size () != 0) {', ' ', ' // find the one closest to the first seed', ' int bestIndex = 0;', ' double bestDist = 9e99;', ' ', ' // loop thru all of the candidate data objects', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listOne.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' ', ' // break if no more data', ' if (myData.size () == 0)', ' break;', ' ', ' // loop thru all of the candidate data objects', ' bestDist = 9e99;', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listTwo.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' }', ' ', ' // now we replace our own guts with the first list', ' replaceGuts (listOne);', ' ', ' // and return the other list', ' return listTwo;', ' }', '}', '', 'interface IMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> {', ' ', ' // add a new pair to the list', ' public void add (KeyType keyToAdd, DataType dataToAdd);', ' ', ' // replace a key at the indicated position', ' public void replaceKey (int pos, KeyType keyToAdd);', ' ', ' // get the key, data pair that resides at a particular position', ' public DataWrapper <KeyType, DataType> get (int pos);', ' ', ' // return the number of items in the list', ' public int size ();', ' ', ' // split the list in two, using some clutering algorithm', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // get a sphere that totally bounds all of the objects in the list', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class MTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public MTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class SCMTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public SCMTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', '', 'public class MTreeTester extends TestCase {', ' ', ' // compare two lists of strings to see if the contents are the same', ' private boolean compareStringSets (ArrayList <String> setOne, ArrayList <String> setTwo) {', ' ', ' // sort the sets and make sure they are the same', ' boolean returnVal = true;', ' if (setOne.size () == setTwo.size ()) {', ' Collections.sort (setOne);', ' Collections.sort (setTwo);', ' for (int i = 0; i < setOne.size (); i++) {', ' if (!setOne.get (i).equals (setTwo.get (i))) {', ' returnVal = false;', ' break; ', ' }', ' }', ' } else {', ' returnVal = false;', ' }', ' ', ' // print out the result', ' System.out.println ("**** Expected:");', ' for (int i = 0; i < setOne.size (); i++) {', ' System.out.format (setOne.get (i) + " ");', ' }', ' System.out.println ("\\n**** Got:");', ' for (int i = 0; i < setTwo.size (); i++) {', ' System.out.format (setTwo.get (i) + " ");', ' }', ' System.out.println ("");', ' ', ' return returnVal;', ' }', ' ', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST SIMPLE ONE DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testOneDimRangeQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.find (query, expectedQuerySize / 2);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.find (query, expectedQuerySize / 2);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (numPoints);', ' result1 = myTree.find (query, expectedQuerySize);', ' result2 = hisTree.find (query, expectedQuerySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // like the last one, but runs a top k', ' private void testOneDimTopKQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (167);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.findKClosest (query, querySize);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (0);', ' result1 = myTree.findKClosest (query, querySize);', ' result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST MULTI-DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimRangeQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' double dist1 = 0;', ' double dist2 = 0;', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' dist1 = Math.sqrt (numDims) * expectedQuerySize / 2.0;', ' dist2 = Math.sqrt (numDims) * expectedQuerySize;', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' // do a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, (int) expectedQuerySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = myTree.findKClosest (query2, (int) expectedQuerySize);', ' ', ' // find the distance to the furthest point in both cases', ' for (int i = 0; i < (int) expectedQuerySize; i++) {', ' double newDist = result1.get (i).getKey ().getDistance (query1);', ' if (newDist > dist1)', ' dist1 = newDist;', ' newDist = result2.get (i).getKey ().getDistance (query2);', ' if (newDist > dist2)', ' dist2 = newDist;', ' }', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.find (query1, dist1);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.find (query1, dist1);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.find (query2, dist2);', ' result2 = hisTree.find (query2, dist2);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimTopKQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, querySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.findKClosest (query1, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.findKClosest (query2, querySize);', ' result2 = hisTree.findKClosest (query2, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' ', ' /**', ' * "TIER 1" TESTS', ' * NONE OF THESE REQUIRE ANY SPLITS', ' */', ' public void testEasy1() {', ' testOneDimRangeQuery (true, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy2() {', ' testOneDimRangeQuery (false, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy3() {', ' testOneDimRangeQuery (true, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy4() {', ' testOneDimRangeQuery (false, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy5() {', ' testMultiDimRangeQuery (true, 1, 5, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy6() {', ' testMultiDimRangeQuery (false, 1, 10, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy7() {', ' testMultiDimRangeQuery (true, 1, 5, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy8() {', ' testMultiDimRangeQuery (false, 1, 15, 10000, 10000, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 2" TESTS', ' * NONE OF THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testMod1() {', ' testOneDimRangeQuery (true, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod2() {', ' testOneDimRangeQuery (false, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod3() {', ' testOneDimRangeQuery (true, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod4() {', ' testOneDimRangeQuery (false, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod5() {', ' testMultiDimRangeQuery (true, 2, 5, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod6() {', ' testMultiDimRangeQuery (false, 2, 10, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod7() {', ' testMultiDimRangeQuery (true, 2, 5, 10000, 100, 1000, 10);', ' }', ' ', ' public void testMod8() {', ' testMultiDimRangeQuery (false, 2, 15, 10000, 100, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 3" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testHard1() {', ' testOneDimRangeQuery (true, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard2() {', ' testOneDimRangeQuery (false, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard3() {', ' testOneDimRangeQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard4() {', ' testOneDimRangeQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard5() {', ' testMultiDimRangeQuery (true, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard6() {', ' testMultiDimRangeQuery (false, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard7() {', ' testMultiDimRangeQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard8() {', ' testMultiDimRangeQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', ' ', ' /**', ' * "TIER 4" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE AND THEY TEST THE TOPK FUNCTIONALITY', ' */', ' ', ' public void testTopK1() {', ' testOneDimTopKQuery (true, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK2() {', ' testOneDimTopKQuery (false, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK3() {', ' testOneDimTopKQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK4() {', ' testOneDimTopKQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK5() {', ' testMultiDimTopKQuery (true, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK6() {', ' testMultiDimTopKQuery (false, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK7() {', ' testMultiDimTopKQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK8() {', ' testMultiDimTopKQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', '}'] | [] | Global_Variable 'myData' used at line 571 is defined at line 554 and has a Medium-Range dependency.
Variable 'pos' used at line 571 is defined at line 570 and has a Short-Range dependency. | {} | {'Global_Variable Medium-Range': 1, 'Variable Short-Range': 1} |
infilling_java | MTreeTester | 584 | 587 | ['import junit.framework.TestCase;', 'import java.util.ArrayList;', 'import java.util.Random;', 'import java.util.Collections;', '', '// this is a map from a set of keys of type PointInMetricSpace to a', '// set of data of type DataType', 'interface IMTree <Key extends IPointInMetricSpace <Key>, Data> {', ' ', ' // insert a new key/data pair into the map', ' void insert (Key keyToAdd, Data dataToAdd);', ' ', ' // find all of the key/data pairs in the map that fall within a', ' // particular distance of query point if no results are found, then', ' // an empty array is returned (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> find (Key query, double distance);', ' ', ' // find the k closest key/data pairs in the map to a particular', ' // query point ', ' //', ' // if the number of points in the map is less than k, then the', ' // returned list will have less than k pairs in it', ' //', ' // if the number of points is zero, then an empty array is returned', ' // (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> findKClosest (Key query, int k);', ' ', ' // returns the number of nodes that exist on a path from root to leaf in the tree...', ' // whtever the details of the implementation are, a tree with a single leaf node should return 1, and a tree', ' // with more than one lead node should return at least two (since it must have at least one internal node).', ' public int depth ();', ' ', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', '', 'interface IDoubleVector {', '', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '', '// this correponds to some geometric object in a metric space; the object is built out of', '// one or more points of type PointInMetricSpace', 'interface IObjectInMetricSpaceABCD <PointInMetricSpace extends IPointInMetricSpace<PointInMetricSpace>> {', ' ', ' // get the maximum distance from some point on the shape to a particular point in the metric space', ' double maxDistanceTo (PointInMetricSpace checkMe);', ' ', ' // return some arbitrary point on the interior of the geometric object', ' PointInMetricSpace getPointInInterior ();', '}', '', '', '// this interface corresponds to a point in some metric space', 'interface IPointInMetricSpace <PointInMetricSpace> {', ' ', ' // get the distance to another point', ' // ', ' // for this to work in an M-Tree, distances should be "metric" and', ' // obey the triangle inequality', ' double getDistance (PointInMetricSpace toMe);', '}', '', '// this is the basic node type in the structure', 'interface IMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> {', ' ', ' // insert a new key/data pair into the structure. The return value is a new MTreeNode if there was', ' // a split in response to the insertion, or a null if there was no split', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd);', ' ', ' // find all of the key/data pairs in the structure that fall within a particular query sphere', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query); ', ' ', ' // find the set of items closest to the given query point', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ);', ' ', ' // returns a sphere that totally encompasses everything in the node and its subtree', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', ' ', ' // returns the depth', ' public int depth ();', '}', '', '// this is a point in a particular metric space', 'class PointABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the point', ' private PointInMetricSpace me;', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return me; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return checkMe.getDistance (me); ', ' }', ' ', ' // contruct a point', ' public PointABCD (PointInMetricSpace useMe) {', ' me = useMe; ', ' }', '}', '', 'class PQueueABCD <PointInMetricSpace, DataType> {', ' ', ' // this is an object in the queue', ' private class Wrapper {', ' DataWrapper <PointInMetricSpace, DataType> myData;', ' double distance;', ' }', ' ', ' // this is the actual queue', ' ArrayList <Wrapper> myList;', ' ', ' // this is the largest distance value currently in the queue', ' double large;', ' ', ' // this is the max number of objects', ' int maxCount;', ' ', ' // create a priority queue with the speced number of slots', ' PQueueABCD (int maxCountIn) {', ' maxCount = maxCountIn;', ' myList = new ArrayList <Wrapper> ();', ' large = 9e99;', ' }', ' ', ' // get the largest distance in the queue', ' double getDist () {', ' return large;', ' }', ' ', ' // add a new object to the queue... the insertion is ignored if the distance value', ' // exceeds the largest that is in the queue and the queue is already full', ' void insert (PointInMetricSpace key, DataType data, double distance) {', ' ', ' // if we are full, remove the one with the largest distance', ' if (myList.size () == maxCount && distance < large) {', ' ', ' int badIndex = 0;', ' double maxDist = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > maxDist) {', ' maxDist = myList.get (i).distance;', ' badIndex = i;', ' }', ' }', ' ', ' myList.remove (badIndex);', ' }', ' ', ' // see if there is room', ' if (myList.size () < maxCount) {', ' ', ' // add it ', ' Wrapper newOne = new Wrapper ();', ' newOne.myData = new DataWrapper <PointInMetricSpace, DataType> (key, data);', ' newOne.distance = distance;', ' myList.add (newOne); ', ' }', ' ', ' // if we are full, reset the max distance', ' if (myList.size () == maxCount) {', ' large = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > large) {', ' large = myList.get (i).distance;', ' }', ' }', ' }', ' ', ' }', ' ', ' // extracts the contents of the queue', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> done () {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' for (int i = 0; i < myList.size (); i++) {', ' returnVal.add (myList.get (i).myData); ', ' }', ' ', ' return returnVal;', ' }', ' ', '}', '', '// this is a sphere in a particular metric space', 'class SphereABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the center of the sphere and its radius', ' private PointInMetricSpace center;', ' private double radius;', ' ', ' // build a sphere out of its center and its radius', ' public SphereABCD (PointInMetricSpace centerIn, double radiusIn) {', ' center = centerIn;', ' radius = radiusIn;', ' }', ' ', ' // increase the size of the sphere so it contains the object swallowMe', ' public void swallow (IObjectInMetricSpaceABCD <PointInMetricSpace> swallowMe) {', ' ', ' // see if we need to increase the radius to swallow this guy', ' double dist = swallowMe.maxDistanceTo (center);', ' if (dist > radius)', ' radius = dist;', ' }', ' ', ' // check to see if a sphere intersects another sphere', ' public boolean intersects (SphereABCD <PointInMetricSpace> me) {', ' return (me.center.getDistance (center) <= me.radius + radius);', ' }', ' ', ' // check to see if the sphere contains a point', ' public boolean contains (PointInMetricSpace checkMe) {', ' return (checkMe.getDistance (center) <= radius);', ' }', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return center; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return radius + checkMe.getDistance (center); ', ' }', '}', '', '', '', 'class OneDimPoint implements IPointInMetricSpace <OneDimPoint> {', ' ', ' // this is the actual double', ' Double value;', ' ', ' // construct this out of a double value', ' public OneDimPoint (double makeFromMe) {', ' value = new Double (makeFromMe);', ' }', ' ', ' // get the distance to another point', ' public double getDistance (OneDimPoint toMe) {', ' if (value > toMe.value)', ' return value - toMe.value;', ' else', ' return toMe.value - value;', ' }', ' ', '}', '', 'class MultiDimPoint implements IPointInMetricSpace <MultiDimPoint> {', ' ', ' // this is the point in a multidimensional space', ' IDoubleVector me;', ' ', ' // make this out of an IDoubleVector', ' public MultiDimPoint (IDoubleVector useMe) {', ' me = useMe;', ' }', ' ', ' // get the Euclidean distance to another point', ' public double getDistance (MultiDimPoint toMe) {', ' double distance = 0.0;', ' try {', ' for (int i = 0; i < me.getLength (); i++) {', ' double diff = me.getItem (i) - toMe.me.getItem (i);', ' diff *= diff;', ' distance += diff;', ' }', ' } catch (OutOfBoundsException e) {', ' throw new IndexOutOfBoundsException ("Can\'t compare two MultiDimPoint objects with different dimensionality!"); ', ' }', ' return Math.sqrt(distance);', ' }', ' ', '}', '// this is a leaf node', 'class LeafMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements ', ' IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myData;', ' ', ' // contructor that takes a data list and builds a node out of it', ' private LeafMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myDataIn) {', ' myData = myDataIn; ', ' }', ' ', ' // constructor that creates an empty node', ' public LeafMTreeNodeABCD () {', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> (); ', ' }', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // just add in the new data', ' myData.add (new PointABCD <PointInMetricSpace> (keyToAdd), dataToAdd);', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> newOne = myData.splitInTwo ();', ' LeafMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' myQ.insert (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData (), ', ' query.getDistance (myData.get (i).getKey ().getPointInInterior ()));', ' }', ' }', ' }', ' ', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' returnVal.add (new DataWrapper <PointInMetricSpace, DataType> (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData ()));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return 1; ', ' }', '', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', '// this silly little class is just a wrapper for a key, data pair', 'class DataWrapper <Key, Data> {', ' ', ' Key key;', ' Data data;', ' ', ' public DataWrapper (Key keyIn, Data dataIn) {', ' key = keyIn;', ' data = dataIn;', ' }', ' ', ' public Key getKey () {', ' return key;', ' }', ' ', ' public Data getData () {', ' return data;', ' }', '}', '', '', '// this is an internal node', 'class InternalMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType>', ' implements IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> myData;', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' // this constructs a new internal node that holds precisely the two nodes that are passed in', ' public InternalMTreeNodeABCD (IMTreeNodeABCD <PointInMetricSpace, DataType> refOne,', ' IMTreeNodeABCD <PointInMetricSpace, DataType> refTwo) {', ' ', ' // create a necw list and add the two guys in', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> ();', ' myData.add (refOne.getBoundingSphere (), refOne);', ' myData.add (refTwo.getBoundingSphere (), refTwo);', ' }', ' ', ' // this constructs a new node that holds the list of data that we were passed in', ' public InternalMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> useMe) {', ' myData = useMe; ', ' }', ' ', ' // from the interface', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // find the best child; this is the one we are closest to', ' double bestDist = 9e99;', ' int bestIndex = 0;', ' for (int i = 0; i < myData.size (); i++) {', ' ', ' double newDist = myData.get (i).getKey ().getPointInInterior ().getDistance (keyToAdd);', ' if (newDist < bestDist) {', ' bestDist = newDist;', ' bestIndex = i;', ' }', ' }', ' ', ' // do the recursive insert', ' IMTreeNodeABCD <PointInMetricSpace, DataType> newRef = myData.get (bestIndex).getData ().insert (keyToAdd, dataToAdd);', ' ', ' // if we got something back, then there was a split, so add the new node into our list', ' if (newRef != null) {', ' myData.add (newRef.getBoundingSphere (), newRef);', ' }', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> newOne = myData.splitInTwo ();', ' InternalMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.intersects (myData.get (i).getKey ())) {', ' myData.get (i).getData ().findKClosest (query, myQ);', ' }', ' }', ' }', ' ', ' // from the interface', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.intersects (myData.get (i).getKey ())) {', ' returnVal.addAll (myData.get (i).getData ().find (query));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return myData.get (0).getData ().depth () + 1; ', ' }', ' ', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', 'abstract class AMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> implements IMetricDataListABCD <PointInMetricSpace,KeyType, DataType> {', '', ' // this is the data that is actually stored in the list', ' private ArrayList <DataWrapper <KeyType, DataType>> myData;', ' ', ' // this is the sphere that bounds everything in the list', ' private SphereABCD <PointInMetricSpace> myBoundingSphere;', ' ', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myBoundingSphere; ', ' }', ' ', ' public int size () {', ' if (myData != null)', ' return myData.size (); ', ' else', ' return 0;', ' }', ' ', ' public DataWrapper <KeyType, DataType> get (int pos) {', ' return myData.get (pos);', ' }', ' ', ' public void replaceKey (int pos, KeyType keyToAdd) {', ' DataWrapper <KeyType, DataType> temp = myData.remove (pos);', ' DataWrapper <KeyType, DataType> newOne = new DataWrapper <KeyType, DataType> (keyToAdd, temp.getData ());', ' myData.add (pos, newOne);', ' }', ' ', ' public void add (KeyType keyToAdd, DataType dataToAdd) {', ' ', ' // if this is the first add, then set everyone up', ' if (myData == null) {'] | [' PointInMetricSpace myCentroid = keyToAdd.getPointInInterior ();', ' myBoundingSphere = new SphereABCD <PointInMetricSpace> (myCentroid, keyToAdd.maxDistanceTo (myCentroid));', ' myData = new ArrayList <DataWrapper <KeyType, DataType>> ();', ' '] | [' // otherwise, extend the sphere if needed', ' } else {', ' myBoundingSphere.swallow (keyToAdd);', ' }', ' ', ' // add the data', ' myData.add (new DataWrapper <KeyType, DataType> (keyToAdd, dataToAdd));', ' }', ' ', ' // we want to potentially allow many implementations of the splitting lalgorithm', ' abstract public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // this is here so the actual splitting algorithn can access the list and change the sphere', ' protected ArrayList <DataWrapper <KeyType, DataType>> getList () {', ' return myData;', ' }', ' ', ' // this is here so the splitting algorithm can modify the list and the sphere', ' protected void replaceGuts (AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> withMe) {', ' myData = withMe.myData;', ' myBoundingSphere = withMe.myBoundingSphere;', ' }', ' ', '}', '', '// this is a particular implementation of the metric data list that uses a simple quadratic clustering', '// algorithm to perform a list split. It picks two "seeds" (the most distant objects) and then repeatedly', '// adds to the two new lists by choosing the objects closest to the seeds', 'class ChrisMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> extends AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> {', '', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo () {', ' ', ' // first, we need to find the two most distant points in the list', ' ArrayList <DataWrapper <KeyType, DataType>> myData = getList ();', ' int bestI = 0, bestJ = 0;', ' double maxDist = -1.0;', ' for (int i = 0; i < myData.size (); i++) {', ' for (int j = i + 1; j < myData.size (); j++) {', ' ', ' // get the two keys', ' DataWrapper <KeyType, DataType> pointOne = myData.get (i);', ' DataWrapper <KeyType, DataType> pointTwo = myData.get (j);', ' ', ' // find the difference between them', ' double curDist = pointOne.getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', '', ' // see if it is the biggest', ' if (curDist > maxDist) {', ' maxDist = curDist;', ' bestI = i;', ' bestJ = j;', ' }', ' }', ' }', ' ', ' // now, we have the best two points; those are seeds for the clustering', ' DataWrapper <KeyType, DataType> pointOne = myData.remove (bestI);', ' DataWrapper <KeyType, DataType> pointTwo = myData.remove (bestJ - 1);', ' ', ' // these are the two new lists', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listOne = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listTwo = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' ', ' // put the two seeds in', ' listOne.add (pointOne.getKey (), pointOne.getData ());', ' listTwo.add (pointTwo.getKey (), pointTwo.getData ());', ' ', ' // and add everyone else in', ' while (myData.size () != 0) {', ' ', ' // find the one closest to the first seed', ' int bestIndex = 0;', ' double bestDist = 9e99;', ' ', ' // loop thru all of the candidate data objects', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listOne.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' ', ' // break if no more data', ' if (myData.size () == 0)', ' break;', ' ', ' // loop thru all of the candidate data objects', ' bestDist = 9e99;', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listTwo.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' }', ' ', ' // now we replace our own guts with the first list', ' replaceGuts (listOne);', ' ', ' // and return the other list', ' return listTwo;', ' }', '}', '', 'interface IMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> {', ' ', ' // add a new pair to the list', ' public void add (KeyType keyToAdd, DataType dataToAdd);', ' ', ' // replace a key at the indicated position', ' public void replaceKey (int pos, KeyType keyToAdd);', ' ', ' // get the key, data pair that resides at a particular position', ' public DataWrapper <KeyType, DataType> get (int pos);', ' ', ' // return the number of items in the list', ' public int size ();', ' ', ' // split the list in two, using some clutering algorithm', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // get a sphere that totally bounds all of the objects in the list', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class MTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public MTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class SCMTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public SCMTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', '', 'public class MTreeTester extends TestCase {', ' ', ' // compare two lists of strings to see if the contents are the same', ' private boolean compareStringSets (ArrayList <String> setOne, ArrayList <String> setTwo) {', ' ', ' // sort the sets and make sure they are the same', ' boolean returnVal = true;', ' if (setOne.size () == setTwo.size ()) {', ' Collections.sort (setOne);', ' Collections.sort (setTwo);', ' for (int i = 0; i < setOne.size (); i++) {', ' if (!setOne.get (i).equals (setTwo.get (i))) {', ' returnVal = false;', ' break; ', ' }', ' }', ' } else {', ' returnVal = false;', ' }', ' ', ' // print out the result', ' System.out.println ("**** Expected:");', ' for (int i = 0; i < setOne.size (); i++) {', ' System.out.format (setOne.get (i) + " ");', ' }', ' System.out.println ("\\n**** Got:");', ' for (int i = 0; i < setTwo.size (); i++) {', ' System.out.format (setTwo.get (i) + " ");', ' }', ' System.out.println ("");', ' ', ' return returnVal;', ' }', ' ', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST SIMPLE ONE DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testOneDimRangeQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.find (query, expectedQuerySize / 2);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.find (query, expectedQuerySize / 2);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (numPoints);', ' result1 = myTree.find (query, expectedQuerySize);', ' result2 = hisTree.find (query, expectedQuerySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // like the last one, but runs a top k', ' private void testOneDimTopKQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (167);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.findKClosest (query, querySize);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (0);', ' result1 = myTree.findKClosest (query, querySize);', ' result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST MULTI-DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimRangeQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' double dist1 = 0;', ' double dist2 = 0;', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' dist1 = Math.sqrt (numDims) * expectedQuerySize / 2.0;', ' dist2 = Math.sqrt (numDims) * expectedQuerySize;', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' // do a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, (int) expectedQuerySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = myTree.findKClosest (query2, (int) expectedQuerySize);', ' ', ' // find the distance to the furthest point in both cases', ' for (int i = 0; i < (int) expectedQuerySize; i++) {', ' double newDist = result1.get (i).getKey ().getDistance (query1);', ' if (newDist > dist1)', ' dist1 = newDist;', ' newDist = result2.get (i).getKey ().getDistance (query2);', ' if (newDist > dist2)', ' dist2 = newDist;', ' }', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.find (query1, dist1);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.find (query1, dist1);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.find (query2, dist2);', ' result2 = hisTree.find (query2, dist2);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimTopKQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, querySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.findKClosest (query1, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.findKClosest (query2, querySize);', ' result2 = hisTree.findKClosest (query2, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' ', ' /**', ' * "TIER 1" TESTS', ' * NONE OF THESE REQUIRE ANY SPLITS', ' */', ' public void testEasy1() {', ' testOneDimRangeQuery (true, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy2() {', ' testOneDimRangeQuery (false, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy3() {', ' testOneDimRangeQuery (true, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy4() {', ' testOneDimRangeQuery (false, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy5() {', ' testMultiDimRangeQuery (true, 1, 5, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy6() {', ' testMultiDimRangeQuery (false, 1, 10, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy7() {', ' testMultiDimRangeQuery (true, 1, 5, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy8() {', ' testMultiDimRangeQuery (false, 1, 15, 10000, 10000, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 2" TESTS', ' * NONE OF THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testMod1() {', ' testOneDimRangeQuery (true, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod2() {', ' testOneDimRangeQuery (false, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod3() {', ' testOneDimRangeQuery (true, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod4() {', ' testOneDimRangeQuery (false, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod5() {', ' testMultiDimRangeQuery (true, 2, 5, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod6() {', ' testMultiDimRangeQuery (false, 2, 10, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod7() {', ' testMultiDimRangeQuery (true, 2, 5, 10000, 100, 1000, 10);', ' }', ' ', ' public void testMod8() {', ' testMultiDimRangeQuery (false, 2, 15, 10000, 100, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 3" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testHard1() {', ' testOneDimRangeQuery (true, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard2() {', ' testOneDimRangeQuery (false, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard3() {', ' testOneDimRangeQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard4() {', ' testOneDimRangeQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard5() {', ' testMultiDimRangeQuery (true, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard6() {', ' testMultiDimRangeQuery (false, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard7() {', ' testMultiDimRangeQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard8() {', ' testMultiDimRangeQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', ' ', ' /**', ' * "TIER 4" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE AND THEY TEST THE TOPK FUNCTIONALITY', ' */', ' ', ' public void testTopK1() {', ' testOneDimTopKQuery (true, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK2() {', ' testOneDimTopKQuery (false, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK3() {', ' testOneDimTopKQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK4() {', ' testOneDimTopKQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK5() {', ' testMultiDimTopKQuery (true, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK6() {', ' testMultiDimTopKQuery (false, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK7() {', ' testMultiDimTopKQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK8() {', ' testMultiDimTopKQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', '}'] | [{'reason_category': 'If Body', 'usage_line': 584}, {'reason_category': 'If Body', 'usage_line': 585}, {'reason_category': 'If Body', 'usage_line': 586}, {'reason_category': 'If Body', 'usage_line': 587}] | Variable 'keyToAdd' used at line 584 is defined at line 580 and has a Short-Range dependency.
Class 'SphereABCD' used at line 585 is defined at line 261 and has a Long-Range dependency.
Variable 'myCentroid' used at line 585 is defined at line 584 and has a Short-Range dependency.
Variable 'keyToAdd' used at line 585 is defined at line 580 and has a Short-Range dependency.
Global_Variable 'myBoundingSphere' used at line 585 is defined at line 557 and has a Medium-Range dependency.
Global_Variable 'myData' used at line 586 is defined at line 554 and has a Long-Range dependency. | {'If Body': 4} | {'Variable Short-Range': 3, 'Class Long-Range': 1, 'Global_Variable Medium-Range': 1, 'Global_Variable Long-Range': 1} |
infilling_java | MTreeTester | 590 | 591 | ['import junit.framework.TestCase;', 'import java.util.ArrayList;', 'import java.util.Random;', 'import java.util.Collections;', '', '// this is a map from a set of keys of type PointInMetricSpace to a', '// set of data of type DataType', 'interface IMTree <Key extends IPointInMetricSpace <Key>, Data> {', ' ', ' // insert a new key/data pair into the map', ' void insert (Key keyToAdd, Data dataToAdd);', ' ', ' // find all of the key/data pairs in the map that fall within a', ' // particular distance of query point if no results are found, then', ' // an empty array is returned (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> find (Key query, double distance);', ' ', ' // find the k closest key/data pairs in the map to a particular', ' // query point ', ' //', ' // if the number of points in the map is less than k, then the', ' // returned list will have less than k pairs in it', ' //', ' // if the number of points is zero, then an empty array is returned', ' // (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> findKClosest (Key query, int k);', ' ', ' // returns the number of nodes that exist on a path from root to leaf in the tree...', ' // whtever the details of the implementation are, a tree with a single leaf node should return 1, and a tree', ' // with more than one lead node should return at least two (since it must have at least one internal node).', ' public int depth ();', ' ', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', '', 'interface IDoubleVector {', '', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '', '// this correponds to some geometric object in a metric space; the object is built out of', '// one or more points of type PointInMetricSpace', 'interface IObjectInMetricSpaceABCD <PointInMetricSpace extends IPointInMetricSpace<PointInMetricSpace>> {', ' ', ' // get the maximum distance from some point on the shape to a particular point in the metric space', ' double maxDistanceTo (PointInMetricSpace checkMe);', ' ', ' // return some arbitrary point on the interior of the geometric object', ' PointInMetricSpace getPointInInterior ();', '}', '', '', '// this interface corresponds to a point in some metric space', 'interface IPointInMetricSpace <PointInMetricSpace> {', ' ', ' // get the distance to another point', ' // ', ' // for this to work in an M-Tree, distances should be "metric" and', ' // obey the triangle inequality', ' double getDistance (PointInMetricSpace toMe);', '}', '', '// this is the basic node type in the structure', 'interface IMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> {', ' ', ' // insert a new key/data pair into the structure. The return value is a new MTreeNode if there was', ' // a split in response to the insertion, or a null if there was no split', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd);', ' ', ' // find all of the key/data pairs in the structure that fall within a particular query sphere', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query); ', ' ', ' // find the set of items closest to the given query point', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ);', ' ', ' // returns a sphere that totally encompasses everything in the node and its subtree', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', ' ', ' // returns the depth', ' public int depth ();', '}', '', '// this is a point in a particular metric space', 'class PointABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the point', ' private PointInMetricSpace me;', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return me; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return checkMe.getDistance (me); ', ' }', ' ', ' // contruct a point', ' public PointABCD (PointInMetricSpace useMe) {', ' me = useMe; ', ' }', '}', '', 'class PQueueABCD <PointInMetricSpace, DataType> {', ' ', ' // this is an object in the queue', ' private class Wrapper {', ' DataWrapper <PointInMetricSpace, DataType> myData;', ' double distance;', ' }', ' ', ' // this is the actual queue', ' ArrayList <Wrapper> myList;', ' ', ' // this is the largest distance value currently in the queue', ' double large;', ' ', ' // this is the max number of objects', ' int maxCount;', ' ', ' // create a priority queue with the speced number of slots', ' PQueueABCD (int maxCountIn) {', ' maxCount = maxCountIn;', ' myList = new ArrayList <Wrapper> ();', ' large = 9e99;', ' }', ' ', ' // get the largest distance in the queue', ' double getDist () {', ' return large;', ' }', ' ', ' // add a new object to the queue... the insertion is ignored if the distance value', ' // exceeds the largest that is in the queue and the queue is already full', ' void insert (PointInMetricSpace key, DataType data, double distance) {', ' ', ' // if we are full, remove the one with the largest distance', ' if (myList.size () == maxCount && distance < large) {', ' ', ' int badIndex = 0;', ' double maxDist = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > maxDist) {', ' maxDist = myList.get (i).distance;', ' badIndex = i;', ' }', ' }', ' ', ' myList.remove (badIndex);', ' }', ' ', ' // see if there is room', ' if (myList.size () < maxCount) {', ' ', ' // add it ', ' Wrapper newOne = new Wrapper ();', ' newOne.myData = new DataWrapper <PointInMetricSpace, DataType> (key, data);', ' newOne.distance = distance;', ' myList.add (newOne); ', ' }', ' ', ' // if we are full, reset the max distance', ' if (myList.size () == maxCount) {', ' large = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > large) {', ' large = myList.get (i).distance;', ' }', ' }', ' }', ' ', ' }', ' ', ' // extracts the contents of the queue', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> done () {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' for (int i = 0; i < myList.size (); i++) {', ' returnVal.add (myList.get (i).myData); ', ' }', ' ', ' return returnVal;', ' }', ' ', '}', '', '// this is a sphere in a particular metric space', 'class SphereABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the center of the sphere and its radius', ' private PointInMetricSpace center;', ' private double radius;', ' ', ' // build a sphere out of its center and its radius', ' public SphereABCD (PointInMetricSpace centerIn, double radiusIn) {', ' center = centerIn;', ' radius = radiusIn;', ' }', ' ', ' // increase the size of the sphere so it contains the object swallowMe', ' public void swallow (IObjectInMetricSpaceABCD <PointInMetricSpace> swallowMe) {', ' ', ' // see if we need to increase the radius to swallow this guy', ' double dist = swallowMe.maxDistanceTo (center);', ' if (dist > radius)', ' radius = dist;', ' }', ' ', ' // check to see if a sphere intersects another sphere', ' public boolean intersects (SphereABCD <PointInMetricSpace> me) {', ' return (me.center.getDistance (center) <= me.radius + radius);', ' }', ' ', ' // check to see if the sphere contains a point', ' public boolean contains (PointInMetricSpace checkMe) {', ' return (checkMe.getDistance (center) <= radius);', ' }', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return center; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return radius + checkMe.getDistance (center); ', ' }', '}', '', '', '', 'class OneDimPoint implements IPointInMetricSpace <OneDimPoint> {', ' ', ' // this is the actual double', ' Double value;', ' ', ' // construct this out of a double value', ' public OneDimPoint (double makeFromMe) {', ' value = new Double (makeFromMe);', ' }', ' ', ' // get the distance to another point', ' public double getDistance (OneDimPoint toMe) {', ' if (value > toMe.value)', ' return value - toMe.value;', ' else', ' return toMe.value - value;', ' }', ' ', '}', '', 'class MultiDimPoint implements IPointInMetricSpace <MultiDimPoint> {', ' ', ' // this is the point in a multidimensional space', ' IDoubleVector me;', ' ', ' // make this out of an IDoubleVector', ' public MultiDimPoint (IDoubleVector useMe) {', ' me = useMe;', ' }', ' ', ' // get the Euclidean distance to another point', ' public double getDistance (MultiDimPoint toMe) {', ' double distance = 0.0;', ' try {', ' for (int i = 0; i < me.getLength (); i++) {', ' double diff = me.getItem (i) - toMe.me.getItem (i);', ' diff *= diff;', ' distance += diff;', ' }', ' } catch (OutOfBoundsException e) {', ' throw new IndexOutOfBoundsException ("Can\'t compare two MultiDimPoint objects with different dimensionality!"); ', ' }', ' return Math.sqrt(distance);', ' }', ' ', '}', '// this is a leaf node', 'class LeafMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements ', ' IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myData;', ' ', ' // contructor that takes a data list and builds a node out of it', ' private LeafMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myDataIn) {', ' myData = myDataIn; ', ' }', ' ', ' // constructor that creates an empty node', ' public LeafMTreeNodeABCD () {', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> (); ', ' }', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // just add in the new data', ' myData.add (new PointABCD <PointInMetricSpace> (keyToAdd), dataToAdd);', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> newOne = myData.splitInTwo ();', ' LeafMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' myQ.insert (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData (), ', ' query.getDistance (myData.get (i).getKey ().getPointInInterior ()));', ' }', ' }', ' }', ' ', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' returnVal.add (new DataWrapper <PointInMetricSpace, DataType> (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData ()));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return 1; ', ' }', '', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', '// this silly little class is just a wrapper for a key, data pair', 'class DataWrapper <Key, Data> {', ' ', ' Key key;', ' Data data;', ' ', ' public DataWrapper (Key keyIn, Data dataIn) {', ' key = keyIn;', ' data = dataIn;', ' }', ' ', ' public Key getKey () {', ' return key;', ' }', ' ', ' public Data getData () {', ' return data;', ' }', '}', '', '', '// this is an internal node', 'class InternalMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType>', ' implements IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> myData;', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' // this constructs a new internal node that holds precisely the two nodes that are passed in', ' public InternalMTreeNodeABCD (IMTreeNodeABCD <PointInMetricSpace, DataType> refOne,', ' IMTreeNodeABCD <PointInMetricSpace, DataType> refTwo) {', ' ', ' // create a necw list and add the two guys in', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> ();', ' myData.add (refOne.getBoundingSphere (), refOne);', ' myData.add (refTwo.getBoundingSphere (), refTwo);', ' }', ' ', ' // this constructs a new node that holds the list of data that we were passed in', ' public InternalMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> useMe) {', ' myData = useMe; ', ' }', ' ', ' // from the interface', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // find the best child; this is the one we are closest to', ' double bestDist = 9e99;', ' int bestIndex = 0;', ' for (int i = 0; i < myData.size (); i++) {', ' ', ' double newDist = myData.get (i).getKey ().getPointInInterior ().getDistance (keyToAdd);', ' if (newDist < bestDist) {', ' bestDist = newDist;', ' bestIndex = i;', ' }', ' }', ' ', ' // do the recursive insert', ' IMTreeNodeABCD <PointInMetricSpace, DataType> newRef = myData.get (bestIndex).getData ().insert (keyToAdd, dataToAdd);', ' ', ' // if we got something back, then there was a split, so add the new node into our list', ' if (newRef != null) {', ' myData.add (newRef.getBoundingSphere (), newRef);', ' }', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> newOne = myData.splitInTwo ();', ' InternalMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.intersects (myData.get (i).getKey ())) {', ' myData.get (i).getData ().findKClosest (query, myQ);', ' }', ' }', ' }', ' ', ' // from the interface', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.intersects (myData.get (i).getKey ())) {', ' returnVal.addAll (myData.get (i).getData ().find (query));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return myData.get (0).getData ().depth () + 1; ', ' }', ' ', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', 'abstract class AMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> implements IMetricDataListABCD <PointInMetricSpace,KeyType, DataType> {', '', ' // this is the data that is actually stored in the list', ' private ArrayList <DataWrapper <KeyType, DataType>> myData;', ' ', ' // this is the sphere that bounds everything in the list', ' private SphereABCD <PointInMetricSpace> myBoundingSphere;', ' ', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myBoundingSphere; ', ' }', ' ', ' public int size () {', ' if (myData != null)', ' return myData.size (); ', ' else', ' return 0;', ' }', ' ', ' public DataWrapper <KeyType, DataType> get (int pos) {', ' return myData.get (pos);', ' }', ' ', ' public void replaceKey (int pos, KeyType keyToAdd) {', ' DataWrapper <KeyType, DataType> temp = myData.remove (pos);', ' DataWrapper <KeyType, DataType> newOne = new DataWrapper <KeyType, DataType> (keyToAdd, temp.getData ());', ' myData.add (pos, newOne);', ' }', ' ', ' public void add (KeyType keyToAdd, DataType dataToAdd) {', ' ', ' // if this is the first add, then set everyone up', ' if (myData == null) {', ' PointInMetricSpace myCentroid = keyToAdd.getPointInInterior ();', ' myBoundingSphere = new SphereABCD <PointInMetricSpace> (myCentroid, keyToAdd.maxDistanceTo (myCentroid));', ' myData = new ArrayList <DataWrapper <KeyType, DataType>> ();', ' ', ' // otherwise, extend the sphere if needed', ' } else {'] | [' myBoundingSphere.swallow (keyToAdd);', ' }'] | [' ', ' // add the data', ' myData.add (new DataWrapper <KeyType, DataType> (keyToAdd, dataToAdd));', ' }', ' ', ' // we want to potentially allow many implementations of the splitting lalgorithm', ' abstract public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // this is here so the actual splitting algorithn can access the list and change the sphere', ' protected ArrayList <DataWrapper <KeyType, DataType>> getList () {', ' return myData;', ' }', ' ', ' // this is here so the splitting algorithm can modify the list and the sphere', ' protected void replaceGuts (AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> withMe) {', ' myData = withMe.myData;', ' myBoundingSphere = withMe.myBoundingSphere;', ' }', ' ', '}', '', '// this is a particular implementation of the metric data list that uses a simple quadratic clustering', '// algorithm to perform a list split. It picks two "seeds" (the most distant objects) and then repeatedly', '// adds to the two new lists by choosing the objects closest to the seeds', 'class ChrisMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> extends AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> {', '', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo () {', ' ', ' // first, we need to find the two most distant points in the list', ' ArrayList <DataWrapper <KeyType, DataType>> myData = getList ();', ' int bestI = 0, bestJ = 0;', ' double maxDist = -1.0;', ' for (int i = 0; i < myData.size (); i++) {', ' for (int j = i + 1; j < myData.size (); j++) {', ' ', ' // get the two keys', ' DataWrapper <KeyType, DataType> pointOne = myData.get (i);', ' DataWrapper <KeyType, DataType> pointTwo = myData.get (j);', ' ', ' // find the difference between them', ' double curDist = pointOne.getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', '', ' // see if it is the biggest', ' if (curDist > maxDist) {', ' maxDist = curDist;', ' bestI = i;', ' bestJ = j;', ' }', ' }', ' }', ' ', ' // now, we have the best two points; those are seeds for the clustering', ' DataWrapper <KeyType, DataType> pointOne = myData.remove (bestI);', ' DataWrapper <KeyType, DataType> pointTwo = myData.remove (bestJ - 1);', ' ', ' // these are the two new lists', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listOne = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listTwo = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' ', ' // put the two seeds in', ' listOne.add (pointOne.getKey (), pointOne.getData ());', ' listTwo.add (pointTwo.getKey (), pointTwo.getData ());', ' ', ' // and add everyone else in', ' while (myData.size () != 0) {', ' ', ' // find the one closest to the first seed', ' int bestIndex = 0;', ' double bestDist = 9e99;', ' ', ' // loop thru all of the candidate data objects', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listOne.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' ', ' // break if no more data', ' if (myData.size () == 0)', ' break;', ' ', ' // loop thru all of the candidate data objects', ' bestDist = 9e99;', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listTwo.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' }', ' ', ' // now we replace our own guts with the first list', ' replaceGuts (listOne);', ' ', ' // and return the other list', ' return listTwo;', ' }', '}', '', 'interface IMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> {', ' ', ' // add a new pair to the list', ' public void add (KeyType keyToAdd, DataType dataToAdd);', ' ', ' // replace a key at the indicated position', ' public void replaceKey (int pos, KeyType keyToAdd);', ' ', ' // get the key, data pair that resides at a particular position', ' public DataWrapper <KeyType, DataType> get (int pos);', ' ', ' // return the number of items in the list', ' public int size ();', ' ', ' // split the list in two, using some clutering algorithm', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // get a sphere that totally bounds all of the objects in the list', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class MTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public MTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class SCMTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public SCMTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', '', 'public class MTreeTester extends TestCase {', ' ', ' // compare two lists of strings to see if the contents are the same', ' private boolean compareStringSets (ArrayList <String> setOne, ArrayList <String> setTwo) {', ' ', ' // sort the sets and make sure they are the same', ' boolean returnVal = true;', ' if (setOne.size () == setTwo.size ()) {', ' Collections.sort (setOne);', ' Collections.sort (setTwo);', ' for (int i = 0; i < setOne.size (); i++) {', ' if (!setOne.get (i).equals (setTwo.get (i))) {', ' returnVal = false;', ' break; ', ' }', ' }', ' } else {', ' returnVal = false;', ' }', ' ', ' // print out the result', ' System.out.println ("**** Expected:");', ' for (int i = 0; i < setOne.size (); i++) {', ' System.out.format (setOne.get (i) + " ");', ' }', ' System.out.println ("\\n**** Got:");', ' for (int i = 0; i < setTwo.size (); i++) {', ' System.out.format (setTwo.get (i) + " ");', ' }', ' System.out.println ("");', ' ', ' return returnVal;', ' }', ' ', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST SIMPLE ONE DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testOneDimRangeQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.find (query, expectedQuerySize / 2);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.find (query, expectedQuerySize / 2);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (numPoints);', ' result1 = myTree.find (query, expectedQuerySize);', ' result2 = hisTree.find (query, expectedQuerySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // like the last one, but runs a top k', ' private void testOneDimTopKQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (167);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.findKClosest (query, querySize);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (0);', ' result1 = myTree.findKClosest (query, querySize);', ' result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST MULTI-DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimRangeQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' double dist1 = 0;', ' double dist2 = 0;', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' dist1 = Math.sqrt (numDims) * expectedQuerySize / 2.0;', ' dist2 = Math.sqrt (numDims) * expectedQuerySize;', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' // do a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, (int) expectedQuerySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = myTree.findKClosest (query2, (int) expectedQuerySize);', ' ', ' // find the distance to the furthest point in both cases', ' for (int i = 0; i < (int) expectedQuerySize; i++) {', ' double newDist = result1.get (i).getKey ().getDistance (query1);', ' if (newDist > dist1)', ' dist1 = newDist;', ' newDist = result2.get (i).getKey ().getDistance (query2);', ' if (newDist > dist2)', ' dist2 = newDist;', ' }', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.find (query1, dist1);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.find (query1, dist1);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.find (query2, dist2);', ' result2 = hisTree.find (query2, dist2);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimTopKQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, querySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.findKClosest (query1, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.findKClosest (query2, querySize);', ' result2 = hisTree.findKClosest (query2, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' ', ' /**', ' * "TIER 1" TESTS', ' * NONE OF THESE REQUIRE ANY SPLITS', ' */', ' public void testEasy1() {', ' testOneDimRangeQuery (true, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy2() {', ' testOneDimRangeQuery (false, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy3() {', ' testOneDimRangeQuery (true, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy4() {', ' testOneDimRangeQuery (false, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy5() {', ' testMultiDimRangeQuery (true, 1, 5, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy6() {', ' testMultiDimRangeQuery (false, 1, 10, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy7() {', ' testMultiDimRangeQuery (true, 1, 5, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy8() {', ' testMultiDimRangeQuery (false, 1, 15, 10000, 10000, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 2" TESTS', ' * NONE OF THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testMod1() {', ' testOneDimRangeQuery (true, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod2() {', ' testOneDimRangeQuery (false, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod3() {', ' testOneDimRangeQuery (true, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod4() {', ' testOneDimRangeQuery (false, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod5() {', ' testMultiDimRangeQuery (true, 2, 5, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod6() {', ' testMultiDimRangeQuery (false, 2, 10, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod7() {', ' testMultiDimRangeQuery (true, 2, 5, 10000, 100, 1000, 10);', ' }', ' ', ' public void testMod8() {', ' testMultiDimRangeQuery (false, 2, 15, 10000, 100, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 3" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testHard1() {', ' testOneDimRangeQuery (true, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard2() {', ' testOneDimRangeQuery (false, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard3() {', ' testOneDimRangeQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard4() {', ' testOneDimRangeQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard5() {', ' testMultiDimRangeQuery (true, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard6() {', ' testMultiDimRangeQuery (false, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard7() {', ' testMultiDimRangeQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard8() {', ' testMultiDimRangeQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', ' ', ' /**', ' * "TIER 4" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE AND THEY TEST THE TOPK FUNCTIONALITY', ' */', ' ', ' public void testTopK1() {', ' testOneDimTopKQuery (true, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK2() {', ' testOneDimTopKQuery (false, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK3() {', ' testOneDimTopKQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK4() {', ' testOneDimTopKQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK5() {', ' testMultiDimTopKQuery (true, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK6() {', ' testMultiDimTopKQuery (false, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK7() {', ' testMultiDimTopKQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK8() {', ' testMultiDimTopKQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', '}'] | [{'reason_category': 'Else Reasoning', 'usage_line': 590}, {'reason_category': 'Else Reasoning', 'usage_line': 591}] | Global_Variable 'myBoundingSphere' used at line 590 is defined at line 585 and has a Short-Range dependency.
Variable 'keyToAdd' used at line 590 is defined at line 580 and has a Short-Range dependency. | {'Else Reasoning': 2} | {'Global_Variable Short-Range': 1, 'Variable Short-Range': 1} |
infilling_java | MTreeTester | 602 | 603 | ['import junit.framework.TestCase;', 'import java.util.ArrayList;', 'import java.util.Random;', 'import java.util.Collections;', '', '// this is a map from a set of keys of type PointInMetricSpace to a', '// set of data of type DataType', 'interface IMTree <Key extends IPointInMetricSpace <Key>, Data> {', ' ', ' // insert a new key/data pair into the map', ' void insert (Key keyToAdd, Data dataToAdd);', ' ', ' // find all of the key/data pairs in the map that fall within a', ' // particular distance of query point if no results are found, then', ' // an empty array is returned (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> find (Key query, double distance);', ' ', ' // find the k closest key/data pairs in the map to a particular', ' // query point ', ' //', ' // if the number of points in the map is less than k, then the', ' // returned list will have less than k pairs in it', ' //', ' // if the number of points is zero, then an empty array is returned', ' // (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> findKClosest (Key query, int k);', ' ', ' // returns the number of nodes that exist on a path from root to leaf in the tree...', ' // whtever the details of the implementation are, a tree with a single leaf node should return 1, and a tree', ' // with more than one lead node should return at least two (since it must have at least one internal node).', ' public int depth ();', ' ', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', '', 'interface IDoubleVector {', '', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '', '// this correponds to some geometric object in a metric space; the object is built out of', '// one or more points of type PointInMetricSpace', 'interface IObjectInMetricSpaceABCD <PointInMetricSpace extends IPointInMetricSpace<PointInMetricSpace>> {', ' ', ' // get the maximum distance from some point on the shape to a particular point in the metric space', ' double maxDistanceTo (PointInMetricSpace checkMe);', ' ', ' // return some arbitrary point on the interior of the geometric object', ' PointInMetricSpace getPointInInterior ();', '}', '', '', '// this interface corresponds to a point in some metric space', 'interface IPointInMetricSpace <PointInMetricSpace> {', ' ', ' // get the distance to another point', ' // ', ' // for this to work in an M-Tree, distances should be "metric" and', ' // obey the triangle inequality', ' double getDistance (PointInMetricSpace toMe);', '}', '', '// this is the basic node type in the structure', 'interface IMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> {', ' ', ' // insert a new key/data pair into the structure. The return value is a new MTreeNode if there was', ' // a split in response to the insertion, or a null if there was no split', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd);', ' ', ' // find all of the key/data pairs in the structure that fall within a particular query sphere', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query); ', ' ', ' // find the set of items closest to the given query point', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ);', ' ', ' // returns a sphere that totally encompasses everything in the node and its subtree', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', ' ', ' // returns the depth', ' public int depth ();', '}', '', '// this is a point in a particular metric space', 'class PointABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the point', ' private PointInMetricSpace me;', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return me; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return checkMe.getDistance (me); ', ' }', ' ', ' // contruct a point', ' public PointABCD (PointInMetricSpace useMe) {', ' me = useMe; ', ' }', '}', '', 'class PQueueABCD <PointInMetricSpace, DataType> {', ' ', ' // this is an object in the queue', ' private class Wrapper {', ' DataWrapper <PointInMetricSpace, DataType> myData;', ' double distance;', ' }', ' ', ' // this is the actual queue', ' ArrayList <Wrapper> myList;', ' ', ' // this is the largest distance value currently in the queue', ' double large;', ' ', ' // this is the max number of objects', ' int maxCount;', ' ', ' // create a priority queue with the speced number of slots', ' PQueueABCD (int maxCountIn) {', ' maxCount = maxCountIn;', ' myList = new ArrayList <Wrapper> ();', ' large = 9e99;', ' }', ' ', ' // get the largest distance in the queue', ' double getDist () {', ' return large;', ' }', ' ', ' // add a new object to the queue... the insertion is ignored if the distance value', ' // exceeds the largest that is in the queue and the queue is already full', ' void insert (PointInMetricSpace key, DataType data, double distance) {', ' ', ' // if we are full, remove the one with the largest distance', ' if (myList.size () == maxCount && distance < large) {', ' ', ' int badIndex = 0;', ' double maxDist = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > maxDist) {', ' maxDist = myList.get (i).distance;', ' badIndex = i;', ' }', ' }', ' ', ' myList.remove (badIndex);', ' }', ' ', ' // see if there is room', ' if (myList.size () < maxCount) {', ' ', ' // add it ', ' Wrapper newOne = new Wrapper ();', ' newOne.myData = new DataWrapper <PointInMetricSpace, DataType> (key, data);', ' newOne.distance = distance;', ' myList.add (newOne); ', ' }', ' ', ' // if we are full, reset the max distance', ' if (myList.size () == maxCount) {', ' large = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > large) {', ' large = myList.get (i).distance;', ' }', ' }', ' }', ' ', ' }', ' ', ' // extracts the contents of the queue', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> done () {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' for (int i = 0; i < myList.size (); i++) {', ' returnVal.add (myList.get (i).myData); ', ' }', ' ', ' return returnVal;', ' }', ' ', '}', '', '// this is a sphere in a particular metric space', 'class SphereABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the center of the sphere and its radius', ' private PointInMetricSpace center;', ' private double radius;', ' ', ' // build a sphere out of its center and its radius', ' public SphereABCD (PointInMetricSpace centerIn, double radiusIn) {', ' center = centerIn;', ' radius = radiusIn;', ' }', ' ', ' // increase the size of the sphere so it contains the object swallowMe', ' public void swallow (IObjectInMetricSpaceABCD <PointInMetricSpace> swallowMe) {', ' ', ' // see if we need to increase the radius to swallow this guy', ' double dist = swallowMe.maxDistanceTo (center);', ' if (dist > radius)', ' radius = dist;', ' }', ' ', ' // check to see if a sphere intersects another sphere', ' public boolean intersects (SphereABCD <PointInMetricSpace> me) {', ' return (me.center.getDistance (center) <= me.radius + radius);', ' }', ' ', ' // check to see if the sphere contains a point', ' public boolean contains (PointInMetricSpace checkMe) {', ' return (checkMe.getDistance (center) <= radius);', ' }', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return center; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return radius + checkMe.getDistance (center); ', ' }', '}', '', '', '', 'class OneDimPoint implements IPointInMetricSpace <OneDimPoint> {', ' ', ' // this is the actual double', ' Double value;', ' ', ' // construct this out of a double value', ' public OneDimPoint (double makeFromMe) {', ' value = new Double (makeFromMe);', ' }', ' ', ' // get the distance to another point', ' public double getDistance (OneDimPoint toMe) {', ' if (value > toMe.value)', ' return value - toMe.value;', ' else', ' return toMe.value - value;', ' }', ' ', '}', '', 'class MultiDimPoint implements IPointInMetricSpace <MultiDimPoint> {', ' ', ' // this is the point in a multidimensional space', ' IDoubleVector me;', ' ', ' // make this out of an IDoubleVector', ' public MultiDimPoint (IDoubleVector useMe) {', ' me = useMe;', ' }', ' ', ' // get the Euclidean distance to another point', ' public double getDistance (MultiDimPoint toMe) {', ' double distance = 0.0;', ' try {', ' for (int i = 0; i < me.getLength (); i++) {', ' double diff = me.getItem (i) - toMe.me.getItem (i);', ' diff *= diff;', ' distance += diff;', ' }', ' } catch (OutOfBoundsException e) {', ' throw new IndexOutOfBoundsException ("Can\'t compare two MultiDimPoint objects with different dimensionality!"); ', ' }', ' return Math.sqrt(distance);', ' }', ' ', '}', '// this is a leaf node', 'class LeafMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements ', ' IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myData;', ' ', ' // contructor that takes a data list and builds a node out of it', ' private LeafMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myDataIn) {', ' myData = myDataIn; ', ' }', ' ', ' // constructor that creates an empty node', ' public LeafMTreeNodeABCD () {', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> (); ', ' }', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // just add in the new data', ' myData.add (new PointABCD <PointInMetricSpace> (keyToAdd), dataToAdd);', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> newOne = myData.splitInTwo ();', ' LeafMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' myQ.insert (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData (), ', ' query.getDistance (myData.get (i).getKey ().getPointInInterior ()));', ' }', ' }', ' }', ' ', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' returnVal.add (new DataWrapper <PointInMetricSpace, DataType> (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData ()));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return 1; ', ' }', '', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', '// this silly little class is just a wrapper for a key, data pair', 'class DataWrapper <Key, Data> {', ' ', ' Key key;', ' Data data;', ' ', ' public DataWrapper (Key keyIn, Data dataIn) {', ' key = keyIn;', ' data = dataIn;', ' }', ' ', ' public Key getKey () {', ' return key;', ' }', ' ', ' public Data getData () {', ' return data;', ' }', '}', '', '', '// this is an internal node', 'class InternalMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType>', ' implements IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> myData;', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' // this constructs a new internal node that holds precisely the two nodes that are passed in', ' public InternalMTreeNodeABCD (IMTreeNodeABCD <PointInMetricSpace, DataType> refOne,', ' IMTreeNodeABCD <PointInMetricSpace, DataType> refTwo) {', ' ', ' // create a necw list and add the two guys in', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> ();', ' myData.add (refOne.getBoundingSphere (), refOne);', ' myData.add (refTwo.getBoundingSphere (), refTwo);', ' }', ' ', ' // this constructs a new node that holds the list of data that we were passed in', ' public InternalMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> useMe) {', ' myData = useMe; ', ' }', ' ', ' // from the interface', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // find the best child; this is the one we are closest to', ' double bestDist = 9e99;', ' int bestIndex = 0;', ' for (int i = 0; i < myData.size (); i++) {', ' ', ' double newDist = myData.get (i).getKey ().getPointInInterior ().getDistance (keyToAdd);', ' if (newDist < bestDist) {', ' bestDist = newDist;', ' bestIndex = i;', ' }', ' }', ' ', ' // do the recursive insert', ' IMTreeNodeABCD <PointInMetricSpace, DataType> newRef = myData.get (bestIndex).getData ().insert (keyToAdd, dataToAdd);', ' ', ' // if we got something back, then there was a split, so add the new node into our list', ' if (newRef != null) {', ' myData.add (newRef.getBoundingSphere (), newRef);', ' }', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> newOne = myData.splitInTwo ();', ' InternalMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.intersects (myData.get (i).getKey ())) {', ' myData.get (i).getData ().findKClosest (query, myQ);', ' }', ' }', ' }', ' ', ' // from the interface', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.intersects (myData.get (i).getKey ())) {', ' returnVal.addAll (myData.get (i).getData ().find (query));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return myData.get (0).getData ().depth () + 1; ', ' }', ' ', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', 'abstract class AMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> implements IMetricDataListABCD <PointInMetricSpace,KeyType, DataType> {', '', ' // this is the data that is actually stored in the list', ' private ArrayList <DataWrapper <KeyType, DataType>> myData;', ' ', ' // this is the sphere that bounds everything in the list', ' private SphereABCD <PointInMetricSpace> myBoundingSphere;', ' ', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myBoundingSphere; ', ' }', ' ', ' public int size () {', ' if (myData != null)', ' return myData.size (); ', ' else', ' return 0;', ' }', ' ', ' public DataWrapper <KeyType, DataType> get (int pos) {', ' return myData.get (pos);', ' }', ' ', ' public void replaceKey (int pos, KeyType keyToAdd) {', ' DataWrapper <KeyType, DataType> temp = myData.remove (pos);', ' DataWrapper <KeyType, DataType> newOne = new DataWrapper <KeyType, DataType> (keyToAdd, temp.getData ());', ' myData.add (pos, newOne);', ' }', ' ', ' public void add (KeyType keyToAdd, DataType dataToAdd) {', ' ', ' // if this is the first add, then set everyone up', ' if (myData == null) {', ' PointInMetricSpace myCentroid = keyToAdd.getPointInInterior ();', ' myBoundingSphere = new SphereABCD <PointInMetricSpace> (myCentroid, keyToAdd.maxDistanceTo (myCentroid));', ' myData = new ArrayList <DataWrapper <KeyType, DataType>> ();', ' ', ' // otherwise, extend the sphere if needed', ' } else {', ' myBoundingSphere.swallow (keyToAdd);', ' }', ' ', ' // add the data', ' myData.add (new DataWrapper <KeyType, DataType> (keyToAdd, dataToAdd));', ' }', ' ', ' // we want to potentially allow many implementations of the splitting lalgorithm', ' abstract public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // this is here so the actual splitting algorithn can access the list and change the sphere', ' protected ArrayList <DataWrapper <KeyType, DataType>> getList () {'] | [' return myData;', ' }'] | [' ', ' // this is here so the splitting algorithm can modify the list and the sphere', ' protected void replaceGuts (AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> withMe) {', ' myData = withMe.myData;', ' myBoundingSphere = withMe.myBoundingSphere;', ' }', ' ', '}', '', '// this is a particular implementation of the metric data list that uses a simple quadratic clustering', '// algorithm to perform a list split. It picks two "seeds" (the most distant objects) and then repeatedly', '// adds to the two new lists by choosing the objects closest to the seeds', 'class ChrisMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> extends AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> {', '', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo () {', ' ', ' // first, we need to find the two most distant points in the list', ' ArrayList <DataWrapper <KeyType, DataType>> myData = getList ();', ' int bestI = 0, bestJ = 0;', ' double maxDist = -1.0;', ' for (int i = 0; i < myData.size (); i++) {', ' for (int j = i + 1; j < myData.size (); j++) {', ' ', ' // get the two keys', ' DataWrapper <KeyType, DataType> pointOne = myData.get (i);', ' DataWrapper <KeyType, DataType> pointTwo = myData.get (j);', ' ', ' // find the difference between them', ' double curDist = pointOne.getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', '', ' // see if it is the biggest', ' if (curDist > maxDist) {', ' maxDist = curDist;', ' bestI = i;', ' bestJ = j;', ' }', ' }', ' }', ' ', ' // now, we have the best two points; those are seeds for the clustering', ' DataWrapper <KeyType, DataType> pointOne = myData.remove (bestI);', ' DataWrapper <KeyType, DataType> pointTwo = myData.remove (bestJ - 1);', ' ', ' // these are the two new lists', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listOne = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listTwo = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' ', ' // put the two seeds in', ' listOne.add (pointOne.getKey (), pointOne.getData ());', ' listTwo.add (pointTwo.getKey (), pointTwo.getData ());', ' ', ' // and add everyone else in', ' while (myData.size () != 0) {', ' ', ' // find the one closest to the first seed', ' int bestIndex = 0;', ' double bestDist = 9e99;', ' ', ' // loop thru all of the candidate data objects', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listOne.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' ', ' // break if no more data', ' if (myData.size () == 0)', ' break;', ' ', ' // loop thru all of the candidate data objects', ' bestDist = 9e99;', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listTwo.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' }', ' ', ' // now we replace our own guts with the first list', ' replaceGuts (listOne);', ' ', ' // and return the other list', ' return listTwo;', ' }', '}', '', 'interface IMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> {', ' ', ' // add a new pair to the list', ' public void add (KeyType keyToAdd, DataType dataToAdd);', ' ', ' // replace a key at the indicated position', ' public void replaceKey (int pos, KeyType keyToAdd);', ' ', ' // get the key, data pair that resides at a particular position', ' public DataWrapper <KeyType, DataType> get (int pos);', ' ', ' // return the number of items in the list', ' public int size ();', ' ', ' // split the list in two, using some clutering algorithm', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // get a sphere that totally bounds all of the objects in the list', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class MTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public MTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class SCMTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public SCMTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', '', 'public class MTreeTester extends TestCase {', ' ', ' // compare two lists of strings to see if the contents are the same', ' private boolean compareStringSets (ArrayList <String> setOne, ArrayList <String> setTwo) {', ' ', ' // sort the sets and make sure they are the same', ' boolean returnVal = true;', ' if (setOne.size () == setTwo.size ()) {', ' Collections.sort (setOne);', ' Collections.sort (setTwo);', ' for (int i = 0; i < setOne.size (); i++) {', ' if (!setOne.get (i).equals (setTwo.get (i))) {', ' returnVal = false;', ' break; ', ' }', ' }', ' } else {', ' returnVal = false;', ' }', ' ', ' // print out the result', ' System.out.println ("**** Expected:");', ' for (int i = 0; i < setOne.size (); i++) {', ' System.out.format (setOne.get (i) + " ");', ' }', ' System.out.println ("\\n**** Got:");', ' for (int i = 0; i < setTwo.size (); i++) {', ' System.out.format (setTwo.get (i) + " ");', ' }', ' System.out.println ("");', ' ', ' return returnVal;', ' }', ' ', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST SIMPLE ONE DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testOneDimRangeQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.find (query, expectedQuerySize / 2);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.find (query, expectedQuerySize / 2);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (numPoints);', ' result1 = myTree.find (query, expectedQuerySize);', ' result2 = hisTree.find (query, expectedQuerySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // like the last one, but runs a top k', ' private void testOneDimTopKQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (167);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.findKClosest (query, querySize);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (0);', ' result1 = myTree.findKClosest (query, querySize);', ' result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST MULTI-DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimRangeQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' double dist1 = 0;', ' double dist2 = 0;', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' dist1 = Math.sqrt (numDims) * expectedQuerySize / 2.0;', ' dist2 = Math.sqrt (numDims) * expectedQuerySize;', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' // do a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, (int) expectedQuerySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = myTree.findKClosest (query2, (int) expectedQuerySize);', ' ', ' // find the distance to the furthest point in both cases', ' for (int i = 0; i < (int) expectedQuerySize; i++) {', ' double newDist = result1.get (i).getKey ().getDistance (query1);', ' if (newDist > dist1)', ' dist1 = newDist;', ' newDist = result2.get (i).getKey ().getDistance (query2);', ' if (newDist > dist2)', ' dist2 = newDist;', ' }', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.find (query1, dist1);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.find (query1, dist1);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.find (query2, dist2);', ' result2 = hisTree.find (query2, dist2);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimTopKQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, querySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.findKClosest (query1, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.findKClosest (query2, querySize);', ' result2 = hisTree.findKClosest (query2, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' ', ' /**', ' * "TIER 1" TESTS', ' * NONE OF THESE REQUIRE ANY SPLITS', ' */', ' public void testEasy1() {', ' testOneDimRangeQuery (true, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy2() {', ' testOneDimRangeQuery (false, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy3() {', ' testOneDimRangeQuery (true, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy4() {', ' testOneDimRangeQuery (false, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy5() {', ' testMultiDimRangeQuery (true, 1, 5, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy6() {', ' testMultiDimRangeQuery (false, 1, 10, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy7() {', ' testMultiDimRangeQuery (true, 1, 5, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy8() {', ' testMultiDimRangeQuery (false, 1, 15, 10000, 10000, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 2" TESTS', ' * NONE OF THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testMod1() {', ' testOneDimRangeQuery (true, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod2() {', ' testOneDimRangeQuery (false, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod3() {', ' testOneDimRangeQuery (true, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod4() {', ' testOneDimRangeQuery (false, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod5() {', ' testMultiDimRangeQuery (true, 2, 5, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod6() {', ' testMultiDimRangeQuery (false, 2, 10, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod7() {', ' testMultiDimRangeQuery (true, 2, 5, 10000, 100, 1000, 10);', ' }', ' ', ' public void testMod8() {', ' testMultiDimRangeQuery (false, 2, 15, 10000, 100, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 3" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testHard1() {', ' testOneDimRangeQuery (true, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard2() {', ' testOneDimRangeQuery (false, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard3() {', ' testOneDimRangeQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard4() {', ' testOneDimRangeQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard5() {', ' testMultiDimRangeQuery (true, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard6() {', ' testMultiDimRangeQuery (false, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard7() {', ' testMultiDimRangeQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard8() {', ' testMultiDimRangeQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', ' ', ' /**', ' * "TIER 4" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE AND THEY TEST THE TOPK FUNCTIONALITY', ' */', ' ', ' public void testTopK1() {', ' testOneDimTopKQuery (true, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK2() {', ' testOneDimTopKQuery (false, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK3() {', ' testOneDimTopKQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK4() {', ' testOneDimTopKQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK5() {', ' testMultiDimTopKQuery (true, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK6() {', ' testMultiDimTopKQuery (false, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK7() {', ' testMultiDimTopKQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK8() {', ' testMultiDimTopKQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', '}'] | [] | Global_Variable 'myData' used at line 602 is defined at line 554 and has a Long-Range dependency. | {} | {'Global_Variable Long-Range': 1} |
infilling_java | MTreeTester | 637 | 640 | ['import junit.framework.TestCase;', 'import java.util.ArrayList;', 'import java.util.Random;', 'import java.util.Collections;', '', '// this is a map from a set of keys of type PointInMetricSpace to a', '// set of data of type DataType', 'interface IMTree <Key extends IPointInMetricSpace <Key>, Data> {', ' ', ' // insert a new key/data pair into the map', ' void insert (Key keyToAdd, Data dataToAdd);', ' ', ' // find all of the key/data pairs in the map that fall within a', ' // particular distance of query point if no results are found, then', ' // an empty array is returned (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> find (Key query, double distance);', ' ', ' // find the k closest key/data pairs in the map to a particular', ' // query point ', ' //', ' // if the number of points in the map is less than k, then the', ' // returned list will have less than k pairs in it', ' //', ' // if the number of points is zero, then an empty array is returned', ' // (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> findKClosest (Key query, int k);', ' ', ' // returns the number of nodes that exist on a path from root to leaf in the tree...', ' // whtever the details of the implementation are, a tree with a single leaf node should return 1, and a tree', ' // with more than one lead node should return at least two (since it must have at least one internal node).', ' public int depth ();', ' ', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', '', 'interface IDoubleVector {', '', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '', '// this correponds to some geometric object in a metric space; the object is built out of', '// one or more points of type PointInMetricSpace', 'interface IObjectInMetricSpaceABCD <PointInMetricSpace extends IPointInMetricSpace<PointInMetricSpace>> {', ' ', ' // get the maximum distance from some point on the shape to a particular point in the metric space', ' double maxDistanceTo (PointInMetricSpace checkMe);', ' ', ' // return some arbitrary point on the interior of the geometric object', ' PointInMetricSpace getPointInInterior ();', '}', '', '', '// this interface corresponds to a point in some metric space', 'interface IPointInMetricSpace <PointInMetricSpace> {', ' ', ' // get the distance to another point', ' // ', ' // for this to work in an M-Tree, distances should be "metric" and', ' // obey the triangle inequality', ' double getDistance (PointInMetricSpace toMe);', '}', '', '// this is the basic node type in the structure', 'interface IMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> {', ' ', ' // insert a new key/data pair into the structure. The return value is a new MTreeNode if there was', ' // a split in response to the insertion, or a null if there was no split', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd);', ' ', ' // find all of the key/data pairs in the structure that fall within a particular query sphere', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query); ', ' ', ' // find the set of items closest to the given query point', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ);', ' ', ' // returns a sphere that totally encompasses everything in the node and its subtree', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', ' ', ' // returns the depth', ' public int depth ();', '}', '', '// this is a point in a particular metric space', 'class PointABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the point', ' private PointInMetricSpace me;', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return me; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return checkMe.getDistance (me); ', ' }', ' ', ' // contruct a point', ' public PointABCD (PointInMetricSpace useMe) {', ' me = useMe; ', ' }', '}', '', 'class PQueueABCD <PointInMetricSpace, DataType> {', ' ', ' // this is an object in the queue', ' private class Wrapper {', ' DataWrapper <PointInMetricSpace, DataType> myData;', ' double distance;', ' }', ' ', ' // this is the actual queue', ' ArrayList <Wrapper> myList;', ' ', ' // this is the largest distance value currently in the queue', ' double large;', ' ', ' // this is the max number of objects', ' int maxCount;', ' ', ' // create a priority queue with the speced number of slots', ' PQueueABCD (int maxCountIn) {', ' maxCount = maxCountIn;', ' myList = new ArrayList <Wrapper> ();', ' large = 9e99;', ' }', ' ', ' // get the largest distance in the queue', ' double getDist () {', ' return large;', ' }', ' ', ' // add a new object to the queue... the insertion is ignored if the distance value', ' // exceeds the largest that is in the queue and the queue is already full', ' void insert (PointInMetricSpace key, DataType data, double distance) {', ' ', ' // if we are full, remove the one with the largest distance', ' if (myList.size () == maxCount && distance < large) {', ' ', ' int badIndex = 0;', ' double maxDist = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > maxDist) {', ' maxDist = myList.get (i).distance;', ' badIndex = i;', ' }', ' }', ' ', ' myList.remove (badIndex);', ' }', ' ', ' // see if there is room', ' if (myList.size () < maxCount) {', ' ', ' // add it ', ' Wrapper newOne = new Wrapper ();', ' newOne.myData = new DataWrapper <PointInMetricSpace, DataType> (key, data);', ' newOne.distance = distance;', ' myList.add (newOne); ', ' }', ' ', ' // if we are full, reset the max distance', ' if (myList.size () == maxCount) {', ' large = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > large) {', ' large = myList.get (i).distance;', ' }', ' }', ' }', ' ', ' }', ' ', ' // extracts the contents of the queue', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> done () {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' for (int i = 0; i < myList.size (); i++) {', ' returnVal.add (myList.get (i).myData); ', ' }', ' ', ' return returnVal;', ' }', ' ', '}', '', '// this is a sphere in a particular metric space', 'class SphereABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the center of the sphere and its radius', ' private PointInMetricSpace center;', ' private double radius;', ' ', ' // build a sphere out of its center and its radius', ' public SphereABCD (PointInMetricSpace centerIn, double radiusIn) {', ' center = centerIn;', ' radius = radiusIn;', ' }', ' ', ' // increase the size of the sphere so it contains the object swallowMe', ' public void swallow (IObjectInMetricSpaceABCD <PointInMetricSpace> swallowMe) {', ' ', ' // see if we need to increase the radius to swallow this guy', ' double dist = swallowMe.maxDistanceTo (center);', ' if (dist > radius)', ' radius = dist;', ' }', ' ', ' // check to see if a sphere intersects another sphere', ' public boolean intersects (SphereABCD <PointInMetricSpace> me) {', ' return (me.center.getDistance (center) <= me.radius + radius);', ' }', ' ', ' // check to see if the sphere contains a point', ' public boolean contains (PointInMetricSpace checkMe) {', ' return (checkMe.getDistance (center) <= radius);', ' }', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return center; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return radius + checkMe.getDistance (center); ', ' }', '}', '', '', '', 'class OneDimPoint implements IPointInMetricSpace <OneDimPoint> {', ' ', ' // this is the actual double', ' Double value;', ' ', ' // construct this out of a double value', ' public OneDimPoint (double makeFromMe) {', ' value = new Double (makeFromMe);', ' }', ' ', ' // get the distance to another point', ' public double getDistance (OneDimPoint toMe) {', ' if (value > toMe.value)', ' return value - toMe.value;', ' else', ' return toMe.value - value;', ' }', ' ', '}', '', 'class MultiDimPoint implements IPointInMetricSpace <MultiDimPoint> {', ' ', ' // this is the point in a multidimensional space', ' IDoubleVector me;', ' ', ' // make this out of an IDoubleVector', ' public MultiDimPoint (IDoubleVector useMe) {', ' me = useMe;', ' }', ' ', ' // get the Euclidean distance to another point', ' public double getDistance (MultiDimPoint toMe) {', ' double distance = 0.0;', ' try {', ' for (int i = 0; i < me.getLength (); i++) {', ' double diff = me.getItem (i) - toMe.me.getItem (i);', ' diff *= diff;', ' distance += diff;', ' }', ' } catch (OutOfBoundsException e) {', ' throw new IndexOutOfBoundsException ("Can\'t compare two MultiDimPoint objects with different dimensionality!"); ', ' }', ' return Math.sqrt(distance);', ' }', ' ', '}', '// this is a leaf node', 'class LeafMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements ', ' IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myData;', ' ', ' // contructor that takes a data list and builds a node out of it', ' private LeafMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myDataIn) {', ' myData = myDataIn; ', ' }', ' ', ' // constructor that creates an empty node', ' public LeafMTreeNodeABCD () {', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> (); ', ' }', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // just add in the new data', ' myData.add (new PointABCD <PointInMetricSpace> (keyToAdd), dataToAdd);', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> newOne = myData.splitInTwo ();', ' LeafMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' myQ.insert (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData (), ', ' query.getDistance (myData.get (i).getKey ().getPointInInterior ()));', ' }', ' }', ' }', ' ', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' returnVal.add (new DataWrapper <PointInMetricSpace, DataType> (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData ()));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return 1; ', ' }', '', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', '// this silly little class is just a wrapper for a key, data pair', 'class DataWrapper <Key, Data> {', ' ', ' Key key;', ' Data data;', ' ', ' public DataWrapper (Key keyIn, Data dataIn) {', ' key = keyIn;', ' data = dataIn;', ' }', ' ', ' public Key getKey () {', ' return key;', ' }', ' ', ' public Data getData () {', ' return data;', ' }', '}', '', '', '// this is an internal node', 'class InternalMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType>', ' implements IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> myData;', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' // this constructs a new internal node that holds precisely the two nodes that are passed in', ' public InternalMTreeNodeABCD (IMTreeNodeABCD <PointInMetricSpace, DataType> refOne,', ' IMTreeNodeABCD <PointInMetricSpace, DataType> refTwo) {', ' ', ' // create a necw list and add the two guys in', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> ();', ' myData.add (refOne.getBoundingSphere (), refOne);', ' myData.add (refTwo.getBoundingSphere (), refTwo);', ' }', ' ', ' // this constructs a new node that holds the list of data that we were passed in', ' public InternalMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> useMe) {', ' myData = useMe; ', ' }', ' ', ' // from the interface', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // find the best child; this is the one we are closest to', ' double bestDist = 9e99;', ' int bestIndex = 0;', ' for (int i = 0; i < myData.size (); i++) {', ' ', ' double newDist = myData.get (i).getKey ().getPointInInterior ().getDistance (keyToAdd);', ' if (newDist < bestDist) {', ' bestDist = newDist;', ' bestIndex = i;', ' }', ' }', ' ', ' // do the recursive insert', ' IMTreeNodeABCD <PointInMetricSpace, DataType> newRef = myData.get (bestIndex).getData ().insert (keyToAdd, dataToAdd);', ' ', ' // if we got something back, then there was a split, so add the new node into our list', ' if (newRef != null) {', ' myData.add (newRef.getBoundingSphere (), newRef);', ' }', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> newOne = myData.splitInTwo ();', ' InternalMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.intersects (myData.get (i).getKey ())) {', ' myData.get (i).getData ().findKClosest (query, myQ);', ' }', ' }', ' }', ' ', ' // from the interface', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.intersects (myData.get (i).getKey ())) {', ' returnVal.addAll (myData.get (i).getData ().find (query));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return myData.get (0).getData ().depth () + 1; ', ' }', ' ', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', 'abstract class AMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> implements IMetricDataListABCD <PointInMetricSpace,KeyType, DataType> {', '', ' // this is the data that is actually stored in the list', ' private ArrayList <DataWrapper <KeyType, DataType>> myData;', ' ', ' // this is the sphere that bounds everything in the list', ' private SphereABCD <PointInMetricSpace> myBoundingSphere;', ' ', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myBoundingSphere; ', ' }', ' ', ' public int size () {', ' if (myData != null)', ' return myData.size (); ', ' else', ' return 0;', ' }', ' ', ' public DataWrapper <KeyType, DataType> get (int pos) {', ' return myData.get (pos);', ' }', ' ', ' public void replaceKey (int pos, KeyType keyToAdd) {', ' DataWrapper <KeyType, DataType> temp = myData.remove (pos);', ' DataWrapper <KeyType, DataType> newOne = new DataWrapper <KeyType, DataType> (keyToAdd, temp.getData ());', ' myData.add (pos, newOne);', ' }', ' ', ' public void add (KeyType keyToAdd, DataType dataToAdd) {', ' ', ' // if this is the first add, then set everyone up', ' if (myData == null) {', ' PointInMetricSpace myCentroid = keyToAdd.getPointInInterior ();', ' myBoundingSphere = new SphereABCD <PointInMetricSpace> (myCentroid, keyToAdd.maxDistanceTo (myCentroid));', ' myData = new ArrayList <DataWrapper <KeyType, DataType>> ();', ' ', ' // otherwise, extend the sphere if needed', ' } else {', ' myBoundingSphere.swallow (keyToAdd);', ' }', ' ', ' // add the data', ' myData.add (new DataWrapper <KeyType, DataType> (keyToAdd, dataToAdd));', ' }', ' ', ' // we want to potentially allow many implementations of the splitting lalgorithm', ' abstract public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // this is here so the actual splitting algorithn can access the list and change the sphere', ' protected ArrayList <DataWrapper <KeyType, DataType>> getList () {', ' return myData;', ' }', ' ', ' // this is here so the splitting algorithm can modify the list and the sphere', ' protected void replaceGuts (AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> withMe) {', ' myData = withMe.myData;', ' myBoundingSphere = withMe.myBoundingSphere;', ' }', ' ', '}', '', '// this is a particular implementation of the metric data list that uses a simple quadratic clustering', '// algorithm to perform a list split. It picks two "seeds" (the most distant objects) and then repeatedly', '// adds to the two new lists by choosing the objects closest to the seeds', 'class ChrisMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> extends AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> {', '', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo () {', ' ', ' // first, we need to find the two most distant points in the list', ' ArrayList <DataWrapper <KeyType, DataType>> myData = getList ();', ' int bestI = 0, bestJ = 0;', ' double maxDist = -1.0;', ' for (int i = 0; i < myData.size (); i++) {', ' for (int j = i + 1; j < myData.size (); j++) {', ' ', ' // get the two keys', ' DataWrapper <KeyType, DataType> pointOne = myData.get (i);', ' DataWrapper <KeyType, DataType> pointTwo = myData.get (j);', ' ', ' // find the difference between them', ' double curDist = pointOne.getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', '', ' // see if it is the biggest', ' if (curDist > maxDist) {'] | [' maxDist = curDist;', ' bestI = i;', ' bestJ = j;', ' }'] | [' }', ' }', ' ', ' // now, we have the best two points; those are seeds for the clustering', ' DataWrapper <KeyType, DataType> pointOne = myData.remove (bestI);', ' DataWrapper <KeyType, DataType> pointTwo = myData.remove (bestJ - 1);', ' ', ' // these are the two new lists', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listOne = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listTwo = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' ', ' // put the two seeds in', ' listOne.add (pointOne.getKey (), pointOne.getData ());', ' listTwo.add (pointTwo.getKey (), pointTwo.getData ());', ' ', ' // and add everyone else in', ' while (myData.size () != 0) {', ' ', ' // find the one closest to the first seed', ' int bestIndex = 0;', ' double bestDist = 9e99;', ' ', ' // loop thru all of the candidate data objects', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listOne.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' ', ' // break if no more data', ' if (myData.size () == 0)', ' break;', ' ', ' // loop thru all of the candidate data objects', ' bestDist = 9e99;', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listTwo.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' }', ' ', ' // now we replace our own guts with the first list', ' replaceGuts (listOne);', ' ', ' // and return the other list', ' return listTwo;', ' }', '}', '', 'interface IMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> {', ' ', ' // add a new pair to the list', ' public void add (KeyType keyToAdd, DataType dataToAdd);', ' ', ' // replace a key at the indicated position', ' public void replaceKey (int pos, KeyType keyToAdd);', ' ', ' // get the key, data pair that resides at a particular position', ' public DataWrapper <KeyType, DataType> get (int pos);', ' ', ' // return the number of items in the list', ' public int size ();', ' ', ' // split the list in two, using some clutering algorithm', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // get a sphere that totally bounds all of the objects in the list', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class MTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public MTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class SCMTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public SCMTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', '', 'public class MTreeTester extends TestCase {', ' ', ' // compare two lists of strings to see if the contents are the same', ' private boolean compareStringSets (ArrayList <String> setOne, ArrayList <String> setTwo) {', ' ', ' // sort the sets and make sure they are the same', ' boolean returnVal = true;', ' if (setOne.size () == setTwo.size ()) {', ' Collections.sort (setOne);', ' Collections.sort (setTwo);', ' for (int i = 0; i < setOne.size (); i++) {', ' if (!setOne.get (i).equals (setTwo.get (i))) {', ' returnVal = false;', ' break; ', ' }', ' }', ' } else {', ' returnVal = false;', ' }', ' ', ' // print out the result', ' System.out.println ("**** Expected:");', ' for (int i = 0; i < setOne.size (); i++) {', ' System.out.format (setOne.get (i) + " ");', ' }', ' System.out.println ("\\n**** Got:");', ' for (int i = 0; i < setTwo.size (); i++) {', ' System.out.format (setTwo.get (i) + " ");', ' }', ' System.out.println ("");', ' ', ' return returnVal;', ' }', ' ', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST SIMPLE ONE DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testOneDimRangeQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.find (query, expectedQuerySize / 2);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.find (query, expectedQuerySize / 2);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (numPoints);', ' result1 = myTree.find (query, expectedQuerySize);', ' result2 = hisTree.find (query, expectedQuerySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // like the last one, but runs a top k', ' private void testOneDimTopKQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (167);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.findKClosest (query, querySize);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (0);', ' result1 = myTree.findKClosest (query, querySize);', ' result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST MULTI-DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimRangeQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' double dist1 = 0;', ' double dist2 = 0;', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' dist1 = Math.sqrt (numDims) * expectedQuerySize / 2.0;', ' dist2 = Math.sqrt (numDims) * expectedQuerySize;', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' // do a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, (int) expectedQuerySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = myTree.findKClosest (query2, (int) expectedQuerySize);', ' ', ' // find the distance to the furthest point in both cases', ' for (int i = 0; i < (int) expectedQuerySize; i++) {', ' double newDist = result1.get (i).getKey ().getDistance (query1);', ' if (newDist > dist1)', ' dist1 = newDist;', ' newDist = result2.get (i).getKey ().getDistance (query2);', ' if (newDist > dist2)', ' dist2 = newDist;', ' }', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.find (query1, dist1);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.find (query1, dist1);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.find (query2, dist2);', ' result2 = hisTree.find (query2, dist2);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimTopKQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, querySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.findKClosest (query1, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.findKClosest (query2, querySize);', ' result2 = hisTree.findKClosest (query2, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' ', ' /**', ' * "TIER 1" TESTS', ' * NONE OF THESE REQUIRE ANY SPLITS', ' */', ' public void testEasy1() {', ' testOneDimRangeQuery (true, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy2() {', ' testOneDimRangeQuery (false, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy3() {', ' testOneDimRangeQuery (true, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy4() {', ' testOneDimRangeQuery (false, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy5() {', ' testMultiDimRangeQuery (true, 1, 5, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy6() {', ' testMultiDimRangeQuery (false, 1, 10, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy7() {', ' testMultiDimRangeQuery (true, 1, 5, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy8() {', ' testMultiDimRangeQuery (false, 1, 15, 10000, 10000, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 2" TESTS', ' * NONE OF THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testMod1() {', ' testOneDimRangeQuery (true, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod2() {', ' testOneDimRangeQuery (false, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod3() {', ' testOneDimRangeQuery (true, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod4() {', ' testOneDimRangeQuery (false, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod5() {', ' testMultiDimRangeQuery (true, 2, 5, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod6() {', ' testMultiDimRangeQuery (false, 2, 10, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod7() {', ' testMultiDimRangeQuery (true, 2, 5, 10000, 100, 1000, 10);', ' }', ' ', ' public void testMod8() {', ' testMultiDimRangeQuery (false, 2, 15, 10000, 100, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 3" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testHard1() {', ' testOneDimRangeQuery (true, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard2() {', ' testOneDimRangeQuery (false, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard3() {', ' testOneDimRangeQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard4() {', ' testOneDimRangeQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard5() {', ' testMultiDimRangeQuery (true, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard6() {', ' testMultiDimRangeQuery (false, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard7() {', ' testMultiDimRangeQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard8() {', ' testMultiDimRangeQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', ' ', ' /**', ' * "TIER 4" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE AND THEY TEST THE TOPK FUNCTIONALITY', ' */', ' ', ' public void testTopK1() {', ' testOneDimTopKQuery (true, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK2() {', ' testOneDimTopKQuery (false, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK3() {', ' testOneDimTopKQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK4() {', ' testOneDimTopKQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK5() {', ' testMultiDimTopKQuery (true, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK6() {', ' testMultiDimTopKQuery (false, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK7() {', ' testMultiDimTopKQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK8() {', ' testMultiDimTopKQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', '}'] | [{'reason_category': 'Loop Body', 'usage_line': 637}, {'reason_category': 'If Body', 'usage_line': 637}, {'reason_category': 'Loop Body', 'usage_line': 638}, {'reason_category': 'If Body', 'usage_line': 638}, {'reason_category': 'Loop Body', 'usage_line': 639}, {'reason_category': 'If Body', 'usage_line': 639}, {'reason_category': 'Loop Body', 'usage_line': 640}, {'reason_category': 'If Body', 'usage_line': 640}] | Variable 'curDist' used at line 637 is defined at line 633 and has a Short-Range dependency.
Variable 'maxDist' used at line 637 is defined at line 624 and has a Medium-Range dependency.
Variable 'i' used at line 638 is defined at line 625 and has a Medium-Range dependency.
Variable 'bestI' used at line 638 is defined at line 623 and has a Medium-Range dependency.
Variable 'j' used at line 639 is defined at line 626 and has a Medium-Range dependency.
Variable 'bestJ' used at line 639 is defined at line 623 and has a Medium-Range dependency. | {'Loop Body': 4, 'If Body': 4} | {'Variable Short-Range': 1, 'Variable Medium-Range': 5} |
infilling_java | MTreeTester | 665 | 669 | ['import junit.framework.TestCase;', 'import java.util.ArrayList;', 'import java.util.Random;', 'import java.util.Collections;', '', '// this is a map from a set of keys of type PointInMetricSpace to a', '// set of data of type DataType', 'interface IMTree <Key extends IPointInMetricSpace <Key>, Data> {', ' ', ' // insert a new key/data pair into the map', ' void insert (Key keyToAdd, Data dataToAdd);', ' ', ' // find all of the key/data pairs in the map that fall within a', ' // particular distance of query point if no results are found, then', ' // an empty array is returned (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> find (Key query, double distance);', ' ', ' // find the k closest key/data pairs in the map to a particular', ' // query point ', ' //', ' // if the number of points in the map is less than k, then the', ' // returned list will have less than k pairs in it', ' //', ' // if the number of points is zero, then an empty array is returned', ' // (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> findKClosest (Key query, int k);', ' ', ' // returns the number of nodes that exist on a path from root to leaf in the tree...', ' // whtever the details of the implementation are, a tree with a single leaf node should return 1, and a tree', ' // with more than one lead node should return at least two (since it must have at least one internal node).', ' public int depth ();', ' ', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', '', 'interface IDoubleVector {', '', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '', '// this correponds to some geometric object in a metric space; the object is built out of', '// one or more points of type PointInMetricSpace', 'interface IObjectInMetricSpaceABCD <PointInMetricSpace extends IPointInMetricSpace<PointInMetricSpace>> {', ' ', ' // get the maximum distance from some point on the shape to a particular point in the metric space', ' double maxDistanceTo (PointInMetricSpace checkMe);', ' ', ' // return some arbitrary point on the interior of the geometric object', ' PointInMetricSpace getPointInInterior ();', '}', '', '', '// this interface corresponds to a point in some metric space', 'interface IPointInMetricSpace <PointInMetricSpace> {', ' ', ' // get the distance to another point', ' // ', ' // for this to work in an M-Tree, distances should be "metric" and', ' // obey the triangle inequality', ' double getDistance (PointInMetricSpace toMe);', '}', '', '// this is the basic node type in the structure', 'interface IMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> {', ' ', ' // insert a new key/data pair into the structure. The return value is a new MTreeNode if there was', ' // a split in response to the insertion, or a null if there was no split', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd);', ' ', ' // find all of the key/data pairs in the structure that fall within a particular query sphere', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query); ', ' ', ' // find the set of items closest to the given query point', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ);', ' ', ' // returns a sphere that totally encompasses everything in the node and its subtree', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', ' ', ' // returns the depth', ' public int depth ();', '}', '', '// this is a point in a particular metric space', 'class PointABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the point', ' private PointInMetricSpace me;', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return me; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return checkMe.getDistance (me); ', ' }', ' ', ' // contruct a point', ' public PointABCD (PointInMetricSpace useMe) {', ' me = useMe; ', ' }', '}', '', 'class PQueueABCD <PointInMetricSpace, DataType> {', ' ', ' // this is an object in the queue', ' private class Wrapper {', ' DataWrapper <PointInMetricSpace, DataType> myData;', ' double distance;', ' }', ' ', ' // this is the actual queue', ' ArrayList <Wrapper> myList;', ' ', ' // this is the largest distance value currently in the queue', ' double large;', ' ', ' // this is the max number of objects', ' int maxCount;', ' ', ' // create a priority queue with the speced number of slots', ' PQueueABCD (int maxCountIn) {', ' maxCount = maxCountIn;', ' myList = new ArrayList <Wrapper> ();', ' large = 9e99;', ' }', ' ', ' // get the largest distance in the queue', ' double getDist () {', ' return large;', ' }', ' ', ' // add a new object to the queue... the insertion is ignored if the distance value', ' // exceeds the largest that is in the queue and the queue is already full', ' void insert (PointInMetricSpace key, DataType data, double distance) {', ' ', ' // if we are full, remove the one with the largest distance', ' if (myList.size () == maxCount && distance < large) {', ' ', ' int badIndex = 0;', ' double maxDist = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > maxDist) {', ' maxDist = myList.get (i).distance;', ' badIndex = i;', ' }', ' }', ' ', ' myList.remove (badIndex);', ' }', ' ', ' // see if there is room', ' if (myList.size () < maxCount) {', ' ', ' // add it ', ' Wrapper newOne = new Wrapper ();', ' newOne.myData = new DataWrapper <PointInMetricSpace, DataType> (key, data);', ' newOne.distance = distance;', ' myList.add (newOne); ', ' }', ' ', ' // if we are full, reset the max distance', ' if (myList.size () == maxCount) {', ' large = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > large) {', ' large = myList.get (i).distance;', ' }', ' }', ' }', ' ', ' }', ' ', ' // extracts the contents of the queue', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> done () {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' for (int i = 0; i < myList.size (); i++) {', ' returnVal.add (myList.get (i).myData); ', ' }', ' ', ' return returnVal;', ' }', ' ', '}', '', '// this is a sphere in a particular metric space', 'class SphereABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the center of the sphere and its radius', ' private PointInMetricSpace center;', ' private double radius;', ' ', ' // build a sphere out of its center and its radius', ' public SphereABCD (PointInMetricSpace centerIn, double radiusIn) {', ' center = centerIn;', ' radius = radiusIn;', ' }', ' ', ' // increase the size of the sphere so it contains the object swallowMe', ' public void swallow (IObjectInMetricSpaceABCD <PointInMetricSpace> swallowMe) {', ' ', ' // see if we need to increase the radius to swallow this guy', ' double dist = swallowMe.maxDistanceTo (center);', ' if (dist > radius)', ' radius = dist;', ' }', ' ', ' // check to see if a sphere intersects another sphere', ' public boolean intersects (SphereABCD <PointInMetricSpace> me) {', ' return (me.center.getDistance (center) <= me.radius + radius);', ' }', ' ', ' // check to see if the sphere contains a point', ' public boolean contains (PointInMetricSpace checkMe) {', ' return (checkMe.getDistance (center) <= radius);', ' }', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return center; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return radius + checkMe.getDistance (center); ', ' }', '}', '', '', '', 'class OneDimPoint implements IPointInMetricSpace <OneDimPoint> {', ' ', ' // this is the actual double', ' Double value;', ' ', ' // construct this out of a double value', ' public OneDimPoint (double makeFromMe) {', ' value = new Double (makeFromMe);', ' }', ' ', ' // get the distance to another point', ' public double getDistance (OneDimPoint toMe) {', ' if (value > toMe.value)', ' return value - toMe.value;', ' else', ' return toMe.value - value;', ' }', ' ', '}', '', 'class MultiDimPoint implements IPointInMetricSpace <MultiDimPoint> {', ' ', ' // this is the point in a multidimensional space', ' IDoubleVector me;', ' ', ' // make this out of an IDoubleVector', ' public MultiDimPoint (IDoubleVector useMe) {', ' me = useMe;', ' }', ' ', ' // get the Euclidean distance to another point', ' public double getDistance (MultiDimPoint toMe) {', ' double distance = 0.0;', ' try {', ' for (int i = 0; i < me.getLength (); i++) {', ' double diff = me.getItem (i) - toMe.me.getItem (i);', ' diff *= diff;', ' distance += diff;', ' }', ' } catch (OutOfBoundsException e) {', ' throw new IndexOutOfBoundsException ("Can\'t compare two MultiDimPoint objects with different dimensionality!"); ', ' }', ' return Math.sqrt(distance);', ' }', ' ', '}', '// this is a leaf node', 'class LeafMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements ', ' IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myData;', ' ', ' // contructor that takes a data list and builds a node out of it', ' private LeafMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myDataIn) {', ' myData = myDataIn; ', ' }', ' ', ' // constructor that creates an empty node', ' public LeafMTreeNodeABCD () {', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> (); ', ' }', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // just add in the new data', ' myData.add (new PointABCD <PointInMetricSpace> (keyToAdd), dataToAdd);', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> newOne = myData.splitInTwo ();', ' LeafMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' myQ.insert (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData (), ', ' query.getDistance (myData.get (i).getKey ().getPointInInterior ()));', ' }', ' }', ' }', ' ', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' returnVal.add (new DataWrapper <PointInMetricSpace, DataType> (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData ()));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return 1; ', ' }', '', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', '// this silly little class is just a wrapper for a key, data pair', 'class DataWrapper <Key, Data> {', ' ', ' Key key;', ' Data data;', ' ', ' public DataWrapper (Key keyIn, Data dataIn) {', ' key = keyIn;', ' data = dataIn;', ' }', ' ', ' public Key getKey () {', ' return key;', ' }', ' ', ' public Data getData () {', ' return data;', ' }', '}', '', '', '// this is an internal node', 'class InternalMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType>', ' implements IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> myData;', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' // this constructs a new internal node that holds precisely the two nodes that are passed in', ' public InternalMTreeNodeABCD (IMTreeNodeABCD <PointInMetricSpace, DataType> refOne,', ' IMTreeNodeABCD <PointInMetricSpace, DataType> refTwo) {', ' ', ' // create a necw list and add the two guys in', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> ();', ' myData.add (refOne.getBoundingSphere (), refOne);', ' myData.add (refTwo.getBoundingSphere (), refTwo);', ' }', ' ', ' // this constructs a new node that holds the list of data that we were passed in', ' public InternalMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> useMe) {', ' myData = useMe; ', ' }', ' ', ' // from the interface', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // find the best child; this is the one we are closest to', ' double bestDist = 9e99;', ' int bestIndex = 0;', ' for (int i = 0; i < myData.size (); i++) {', ' ', ' double newDist = myData.get (i).getKey ().getPointInInterior ().getDistance (keyToAdd);', ' if (newDist < bestDist) {', ' bestDist = newDist;', ' bestIndex = i;', ' }', ' }', ' ', ' // do the recursive insert', ' IMTreeNodeABCD <PointInMetricSpace, DataType> newRef = myData.get (bestIndex).getData ().insert (keyToAdd, dataToAdd);', ' ', ' // if we got something back, then there was a split, so add the new node into our list', ' if (newRef != null) {', ' myData.add (newRef.getBoundingSphere (), newRef);', ' }', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> newOne = myData.splitInTwo ();', ' InternalMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.intersects (myData.get (i).getKey ())) {', ' myData.get (i).getData ().findKClosest (query, myQ);', ' }', ' }', ' }', ' ', ' // from the interface', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.intersects (myData.get (i).getKey ())) {', ' returnVal.addAll (myData.get (i).getData ().find (query));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return myData.get (0).getData ().depth () + 1; ', ' }', ' ', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', 'abstract class AMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> implements IMetricDataListABCD <PointInMetricSpace,KeyType, DataType> {', '', ' // this is the data that is actually stored in the list', ' private ArrayList <DataWrapper <KeyType, DataType>> myData;', ' ', ' // this is the sphere that bounds everything in the list', ' private SphereABCD <PointInMetricSpace> myBoundingSphere;', ' ', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myBoundingSphere; ', ' }', ' ', ' public int size () {', ' if (myData != null)', ' return myData.size (); ', ' else', ' return 0;', ' }', ' ', ' public DataWrapper <KeyType, DataType> get (int pos) {', ' return myData.get (pos);', ' }', ' ', ' public void replaceKey (int pos, KeyType keyToAdd) {', ' DataWrapper <KeyType, DataType> temp = myData.remove (pos);', ' DataWrapper <KeyType, DataType> newOne = new DataWrapper <KeyType, DataType> (keyToAdd, temp.getData ());', ' myData.add (pos, newOne);', ' }', ' ', ' public void add (KeyType keyToAdd, DataType dataToAdd) {', ' ', ' // if this is the first add, then set everyone up', ' if (myData == null) {', ' PointInMetricSpace myCentroid = keyToAdd.getPointInInterior ();', ' myBoundingSphere = new SphereABCD <PointInMetricSpace> (myCentroid, keyToAdd.maxDistanceTo (myCentroid));', ' myData = new ArrayList <DataWrapper <KeyType, DataType>> ();', ' ', ' // otherwise, extend the sphere if needed', ' } else {', ' myBoundingSphere.swallow (keyToAdd);', ' }', ' ', ' // add the data', ' myData.add (new DataWrapper <KeyType, DataType> (keyToAdd, dataToAdd));', ' }', ' ', ' // we want to potentially allow many implementations of the splitting lalgorithm', ' abstract public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // this is here so the actual splitting algorithn can access the list and change the sphere', ' protected ArrayList <DataWrapper <KeyType, DataType>> getList () {', ' return myData;', ' }', ' ', ' // this is here so the splitting algorithm can modify the list and the sphere', ' protected void replaceGuts (AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> withMe) {', ' myData = withMe.myData;', ' myBoundingSphere = withMe.myBoundingSphere;', ' }', ' ', '}', '', '// this is a particular implementation of the metric data list that uses a simple quadratic clustering', '// algorithm to perform a list split. It picks two "seeds" (the most distant objects) and then repeatedly', '// adds to the two new lists by choosing the objects closest to the seeds', 'class ChrisMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> extends AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> {', '', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo () {', ' ', ' // first, we need to find the two most distant points in the list', ' ArrayList <DataWrapper <KeyType, DataType>> myData = getList ();', ' int bestI = 0, bestJ = 0;', ' double maxDist = -1.0;', ' for (int i = 0; i < myData.size (); i++) {', ' for (int j = i + 1; j < myData.size (); j++) {', ' ', ' // get the two keys', ' DataWrapper <KeyType, DataType> pointOne = myData.get (i);', ' DataWrapper <KeyType, DataType> pointTwo = myData.get (j);', ' ', ' // find the difference between them', ' double curDist = pointOne.getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', '', ' // see if it is the biggest', ' if (curDist > maxDist) {', ' maxDist = curDist;', ' bestI = i;', ' bestJ = j;', ' }', ' }', ' }', ' ', ' // now, we have the best two points; those are seeds for the clustering', ' DataWrapper <KeyType, DataType> pointOne = myData.remove (bestI);', ' DataWrapper <KeyType, DataType> pointTwo = myData.remove (bestJ - 1);', ' ', ' // these are the two new lists', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listOne = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listTwo = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' ', ' // put the two seeds in', ' listOne.add (pointOne.getKey (), pointOne.getData ());', ' listTwo.add (pointTwo.getKey (), pointTwo.getData ());', ' ', ' // and add everyone else in', ' while (myData.size () != 0) {', ' ', ' // find the one closest to the first seed', ' int bestIndex = 0;', ' double bestDist = 9e99;', ' ', ' // loop thru all of the candidate data objects', ' for (int i = 0; i < myData.size (); i++) {'] | [' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }'] | [' ', ' // and add the best in', ' listOne.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' ', ' // break if no more data', ' if (myData.size () == 0)', ' break;', ' ', ' // loop thru all of the candidate data objects', ' bestDist = 9e99;', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listTwo.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' }', ' ', ' // now we replace our own guts with the first list', ' replaceGuts (listOne);', ' ', ' // and return the other list', ' return listTwo;', ' }', '}', '', 'interface IMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> {', ' ', ' // add a new pair to the list', ' public void add (KeyType keyToAdd, DataType dataToAdd);', ' ', ' // replace a key at the indicated position', ' public void replaceKey (int pos, KeyType keyToAdd);', ' ', ' // get the key, data pair that resides at a particular position', ' public DataWrapper <KeyType, DataType> get (int pos);', ' ', ' // return the number of items in the list', ' public int size ();', ' ', ' // split the list in two, using some clutering algorithm', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // get a sphere that totally bounds all of the objects in the list', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class MTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public MTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class SCMTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public SCMTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', '', 'public class MTreeTester extends TestCase {', ' ', ' // compare two lists of strings to see if the contents are the same', ' private boolean compareStringSets (ArrayList <String> setOne, ArrayList <String> setTwo) {', ' ', ' // sort the sets and make sure they are the same', ' boolean returnVal = true;', ' if (setOne.size () == setTwo.size ()) {', ' Collections.sort (setOne);', ' Collections.sort (setTwo);', ' for (int i = 0; i < setOne.size (); i++) {', ' if (!setOne.get (i).equals (setTwo.get (i))) {', ' returnVal = false;', ' break; ', ' }', ' }', ' } else {', ' returnVal = false;', ' }', ' ', ' // print out the result', ' System.out.println ("**** Expected:");', ' for (int i = 0; i < setOne.size (); i++) {', ' System.out.format (setOne.get (i) + " ");', ' }', ' System.out.println ("\\n**** Got:");', ' for (int i = 0; i < setTwo.size (); i++) {', ' System.out.format (setTwo.get (i) + " ");', ' }', ' System.out.println ("");', ' ', ' return returnVal;', ' }', ' ', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST SIMPLE ONE DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testOneDimRangeQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.find (query, expectedQuerySize / 2);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.find (query, expectedQuerySize / 2);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (numPoints);', ' result1 = myTree.find (query, expectedQuerySize);', ' result2 = hisTree.find (query, expectedQuerySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // like the last one, but runs a top k', ' private void testOneDimTopKQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (167);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.findKClosest (query, querySize);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (0);', ' result1 = myTree.findKClosest (query, querySize);', ' result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST MULTI-DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimRangeQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' double dist1 = 0;', ' double dist2 = 0;', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' dist1 = Math.sqrt (numDims) * expectedQuerySize / 2.0;', ' dist2 = Math.sqrt (numDims) * expectedQuerySize;', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' // do a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, (int) expectedQuerySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = myTree.findKClosest (query2, (int) expectedQuerySize);', ' ', ' // find the distance to the furthest point in both cases', ' for (int i = 0; i < (int) expectedQuerySize; i++) {', ' double newDist = result1.get (i).getKey ().getDistance (query1);', ' if (newDist > dist1)', ' dist1 = newDist;', ' newDist = result2.get (i).getKey ().getDistance (query2);', ' if (newDist > dist2)', ' dist2 = newDist;', ' }', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.find (query1, dist1);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.find (query1, dist1);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.find (query2, dist2);', ' result2 = hisTree.find (query2, dist2);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimTopKQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, querySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.findKClosest (query1, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.findKClosest (query2, querySize);', ' result2 = hisTree.findKClosest (query2, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' ', ' /**', ' * "TIER 1" TESTS', ' * NONE OF THESE REQUIRE ANY SPLITS', ' */', ' public void testEasy1() {', ' testOneDimRangeQuery (true, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy2() {', ' testOneDimRangeQuery (false, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy3() {', ' testOneDimRangeQuery (true, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy4() {', ' testOneDimRangeQuery (false, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy5() {', ' testMultiDimRangeQuery (true, 1, 5, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy6() {', ' testMultiDimRangeQuery (false, 1, 10, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy7() {', ' testMultiDimRangeQuery (true, 1, 5, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy8() {', ' testMultiDimRangeQuery (false, 1, 15, 10000, 10000, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 2" TESTS', ' * NONE OF THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testMod1() {', ' testOneDimRangeQuery (true, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod2() {', ' testOneDimRangeQuery (false, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod3() {', ' testOneDimRangeQuery (true, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod4() {', ' testOneDimRangeQuery (false, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod5() {', ' testMultiDimRangeQuery (true, 2, 5, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod6() {', ' testMultiDimRangeQuery (false, 2, 10, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod7() {', ' testMultiDimRangeQuery (true, 2, 5, 10000, 100, 1000, 10);', ' }', ' ', ' public void testMod8() {', ' testMultiDimRangeQuery (false, 2, 15, 10000, 100, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 3" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testHard1() {', ' testOneDimRangeQuery (true, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard2() {', ' testOneDimRangeQuery (false, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard3() {', ' testOneDimRangeQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard4() {', ' testOneDimRangeQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard5() {', ' testMultiDimRangeQuery (true, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard6() {', ' testMultiDimRangeQuery (false, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard7() {', ' testMultiDimRangeQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard8() {', ' testMultiDimRangeQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', ' ', ' /**', ' * "TIER 4" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE AND THEY TEST THE TOPK FUNCTIONALITY', ' */', ' ', ' public void testTopK1() {', ' testOneDimTopKQuery (true, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK2() {', ' testOneDimTopKQuery (false, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK3() {', ' testOneDimTopKQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK4() {', ' testOneDimTopKQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK5() {', ' testMultiDimTopKQuery (true, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK6() {', ' testMultiDimTopKQuery (false, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK7() {', ' testMultiDimTopKQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK8() {', ' testMultiDimTopKQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', '}'] | [{'reason_category': 'Loop Body', 'usage_line': 665}, {'reason_category': 'If Condition', 'usage_line': 665}, {'reason_category': 'Loop Body', 'usage_line': 666}, {'reason_category': 'If Body', 'usage_line': 666}, {'reason_category': 'Loop Body', 'usage_line': 667}, {'reason_category': 'If Body', 'usage_line': 667}, {'reason_category': 'Loop Body', 'usage_line': 668}, {'reason_category': 'If Body', 'usage_line': 668}, {'reason_category': 'Loop Body', 'usage_line': 669}] | Variable 'myData' used at line 665 is defined at line 622 and has a Long-Range dependency.
Variable 'i' used at line 665 is defined at line 664 and has a Short-Range dependency.
Function 'getKey' used at line 665 is defined at line 439 and has a Long-Range dependency.
Function 'getPointInInterior' used at line 665 is defined at line 122 and has a Long-Range dependency.
Function 'getDistance' used at line 665 is defined at line 133 and has a Long-Range dependency.
Variable 'pointOne' used at line 665 is defined at line 645 and has a Medium-Range dependency.
Variable 'bestDist' used at line 665 is defined at line 661 and has a Short-Range dependency.
Variable 'myData' used at line 666 is defined at line 622 and has a Long-Range dependency.
Variable 'i' used at line 666 is defined at line 664 and has a Short-Range dependency.
Function 'getKey' used at line 666 is defined at line 439 and has a Long-Range dependency.
Function 'getPointInInterior' used at line 666 is defined at line 122 and has a Long-Range dependency.
Function 'getDistance' used at line 666 is defined at line 133 and has a Long-Range dependency.
Variable 'pointOne' used at line 666 is defined at line 645 and has a Medium-Range dependency.
Variable 'bestDist' used at line 666 is defined at line 661 and has a Short-Range dependency.
Variable 'i' used at line 667 is defined at line 664 and has a Short-Range dependency.
Variable 'bestIndex' used at line 667 is defined at line 660 and has a Short-Range dependency. | {'Loop Body': 5, 'If Condition': 1, 'If Body': 3} | {'Variable Long-Range': 2, 'Variable Short-Range': 6, 'Function Long-Range': 6, 'Variable Medium-Range': 2} |
infilling_java | MTreeTester | 683 | 685 | ['import junit.framework.TestCase;', 'import java.util.ArrayList;', 'import java.util.Random;', 'import java.util.Collections;', '', '// this is a map from a set of keys of type PointInMetricSpace to a', '// set of data of type DataType', 'interface IMTree <Key extends IPointInMetricSpace <Key>, Data> {', ' ', ' // insert a new key/data pair into the map', ' void insert (Key keyToAdd, Data dataToAdd);', ' ', ' // find all of the key/data pairs in the map that fall within a', ' // particular distance of query point if no results are found, then', ' // an empty array is returned (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> find (Key query, double distance);', ' ', ' // find the k closest key/data pairs in the map to a particular', ' // query point ', ' //', ' // if the number of points in the map is less than k, then the', ' // returned list will have less than k pairs in it', ' //', ' // if the number of points is zero, then an empty array is returned', ' // (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> findKClosest (Key query, int k);', ' ', ' // returns the number of nodes that exist on a path from root to leaf in the tree...', ' // whtever the details of the implementation are, a tree with a single leaf node should return 1, and a tree', ' // with more than one lead node should return at least two (since it must have at least one internal node).', ' public int depth ();', ' ', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', '', 'interface IDoubleVector {', '', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '', '// this correponds to some geometric object in a metric space; the object is built out of', '// one or more points of type PointInMetricSpace', 'interface IObjectInMetricSpaceABCD <PointInMetricSpace extends IPointInMetricSpace<PointInMetricSpace>> {', ' ', ' // get the maximum distance from some point on the shape to a particular point in the metric space', ' double maxDistanceTo (PointInMetricSpace checkMe);', ' ', ' // return some arbitrary point on the interior of the geometric object', ' PointInMetricSpace getPointInInterior ();', '}', '', '', '// this interface corresponds to a point in some metric space', 'interface IPointInMetricSpace <PointInMetricSpace> {', ' ', ' // get the distance to another point', ' // ', ' // for this to work in an M-Tree, distances should be "metric" and', ' // obey the triangle inequality', ' double getDistance (PointInMetricSpace toMe);', '}', '', '// this is the basic node type in the structure', 'interface IMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> {', ' ', ' // insert a new key/data pair into the structure. The return value is a new MTreeNode if there was', ' // a split in response to the insertion, or a null if there was no split', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd);', ' ', ' // find all of the key/data pairs in the structure that fall within a particular query sphere', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query); ', ' ', ' // find the set of items closest to the given query point', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ);', ' ', ' // returns a sphere that totally encompasses everything in the node and its subtree', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', ' ', ' // returns the depth', ' public int depth ();', '}', '', '// this is a point in a particular metric space', 'class PointABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the point', ' private PointInMetricSpace me;', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return me; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return checkMe.getDistance (me); ', ' }', ' ', ' // contruct a point', ' public PointABCD (PointInMetricSpace useMe) {', ' me = useMe; ', ' }', '}', '', 'class PQueueABCD <PointInMetricSpace, DataType> {', ' ', ' // this is an object in the queue', ' private class Wrapper {', ' DataWrapper <PointInMetricSpace, DataType> myData;', ' double distance;', ' }', ' ', ' // this is the actual queue', ' ArrayList <Wrapper> myList;', ' ', ' // this is the largest distance value currently in the queue', ' double large;', ' ', ' // this is the max number of objects', ' int maxCount;', ' ', ' // create a priority queue with the speced number of slots', ' PQueueABCD (int maxCountIn) {', ' maxCount = maxCountIn;', ' myList = new ArrayList <Wrapper> ();', ' large = 9e99;', ' }', ' ', ' // get the largest distance in the queue', ' double getDist () {', ' return large;', ' }', ' ', ' // add a new object to the queue... the insertion is ignored if the distance value', ' // exceeds the largest that is in the queue and the queue is already full', ' void insert (PointInMetricSpace key, DataType data, double distance) {', ' ', ' // if we are full, remove the one with the largest distance', ' if (myList.size () == maxCount && distance < large) {', ' ', ' int badIndex = 0;', ' double maxDist = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > maxDist) {', ' maxDist = myList.get (i).distance;', ' badIndex = i;', ' }', ' }', ' ', ' myList.remove (badIndex);', ' }', ' ', ' // see if there is room', ' if (myList.size () < maxCount) {', ' ', ' // add it ', ' Wrapper newOne = new Wrapper ();', ' newOne.myData = new DataWrapper <PointInMetricSpace, DataType> (key, data);', ' newOne.distance = distance;', ' myList.add (newOne); ', ' }', ' ', ' // if we are full, reset the max distance', ' if (myList.size () == maxCount) {', ' large = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > large) {', ' large = myList.get (i).distance;', ' }', ' }', ' }', ' ', ' }', ' ', ' // extracts the contents of the queue', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> done () {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' for (int i = 0; i < myList.size (); i++) {', ' returnVal.add (myList.get (i).myData); ', ' }', ' ', ' return returnVal;', ' }', ' ', '}', '', '// this is a sphere in a particular metric space', 'class SphereABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the center of the sphere and its radius', ' private PointInMetricSpace center;', ' private double radius;', ' ', ' // build a sphere out of its center and its radius', ' public SphereABCD (PointInMetricSpace centerIn, double radiusIn) {', ' center = centerIn;', ' radius = radiusIn;', ' }', ' ', ' // increase the size of the sphere so it contains the object swallowMe', ' public void swallow (IObjectInMetricSpaceABCD <PointInMetricSpace> swallowMe) {', ' ', ' // see if we need to increase the radius to swallow this guy', ' double dist = swallowMe.maxDistanceTo (center);', ' if (dist > radius)', ' radius = dist;', ' }', ' ', ' // check to see if a sphere intersects another sphere', ' public boolean intersects (SphereABCD <PointInMetricSpace> me) {', ' return (me.center.getDistance (center) <= me.radius + radius);', ' }', ' ', ' // check to see if the sphere contains a point', ' public boolean contains (PointInMetricSpace checkMe) {', ' return (checkMe.getDistance (center) <= radius);', ' }', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return center; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return radius + checkMe.getDistance (center); ', ' }', '}', '', '', '', 'class OneDimPoint implements IPointInMetricSpace <OneDimPoint> {', ' ', ' // this is the actual double', ' Double value;', ' ', ' // construct this out of a double value', ' public OneDimPoint (double makeFromMe) {', ' value = new Double (makeFromMe);', ' }', ' ', ' // get the distance to another point', ' public double getDistance (OneDimPoint toMe) {', ' if (value > toMe.value)', ' return value - toMe.value;', ' else', ' return toMe.value - value;', ' }', ' ', '}', '', 'class MultiDimPoint implements IPointInMetricSpace <MultiDimPoint> {', ' ', ' // this is the point in a multidimensional space', ' IDoubleVector me;', ' ', ' // make this out of an IDoubleVector', ' public MultiDimPoint (IDoubleVector useMe) {', ' me = useMe;', ' }', ' ', ' // get the Euclidean distance to another point', ' public double getDistance (MultiDimPoint toMe) {', ' double distance = 0.0;', ' try {', ' for (int i = 0; i < me.getLength (); i++) {', ' double diff = me.getItem (i) - toMe.me.getItem (i);', ' diff *= diff;', ' distance += diff;', ' }', ' } catch (OutOfBoundsException e) {', ' throw new IndexOutOfBoundsException ("Can\'t compare two MultiDimPoint objects with different dimensionality!"); ', ' }', ' return Math.sqrt(distance);', ' }', ' ', '}', '// this is a leaf node', 'class LeafMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements ', ' IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myData;', ' ', ' // contructor that takes a data list and builds a node out of it', ' private LeafMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myDataIn) {', ' myData = myDataIn; ', ' }', ' ', ' // constructor that creates an empty node', ' public LeafMTreeNodeABCD () {', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> (); ', ' }', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // just add in the new data', ' myData.add (new PointABCD <PointInMetricSpace> (keyToAdd), dataToAdd);', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> newOne = myData.splitInTwo ();', ' LeafMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' myQ.insert (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData (), ', ' query.getDistance (myData.get (i).getKey ().getPointInInterior ()));', ' }', ' }', ' }', ' ', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' returnVal.add (new DataWrapper <PointInMetricSpace, DataType> (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData ()));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return 1; ', ' }', '', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', '// this silly little class is just a wrapper for a key, data pair', 'class DataWrapper <Key, Data> {', ' ', ' Key key;', ' Data data;', ' ', ' public DataWrapper (Key keyIn, Data dataIn) {', ' key = keyIn;', ' data = dataIn;', ' }', ' ', ' public Key getKey () {', ' return key;', ' }', ' ', ' public Data getData () {', ' return data;', ' }', '}', '', '', '// this is an internal node', 'class InternalMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType>', ' implements IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> myData;', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' // this constructs a new internal node that holds precisely the two nodes that are passed in', ' public InternalMTreeNodeABCD (IMTreeNodeABCD <PointInMetricSpace, DataType> refOne,', ' IMTreeNodeABCD <PointInMetricSpace, DataType> refTwo) {', ' ', ' // create a necw list and add the two guys in', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> ();', ' myData.add (refOne.getBoundingSphere (), refOne);', ' myData.add (refTwo.getBoundingSphere (), refTwo);', ' }', ' ', ' // this constructs a new node that holds the list of data that we were passed in', ' public InternalMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> useMe) {', ' myData = useMe; ', ' }', ' ', ' // from the interface', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // find the best child; this is the one we are closest to', ' double bestDist = 9e99;', ' int bestIndex = 0;', ' for (int i = 0; i < myData.size (); i++) {', ' ', ' double newDist = myData.get (i).getKey ().getPointInInterior ().getDistance (keyToAdd);', ' if (newDist < bestDist) {', ' bestDist = newDist;', ' bestIndex = i;', ' }', ' }', ' ', ' // do the recursive insert', ' IMTreeNodeABCD <PointInMetricSpace, DataType> newRef = myData.get (bestIndex).getData ().insert (keyToAdd, dataToAdd);', ' ', ' // if we got something back, then there was a split, so add the new node into our list', ' if (newRef != null) {', ' myData.add (newRef.getBoundingSphere (), newRef);', ' }', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> newOne = myData.splitInTwo ();', ' InternalMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.intersects (myData.get (i).getKey ())) {', ' myData.get (i).getData ().findKClosest (query, myQ);', ' }', ' }', ' }', ' ', ' // from the interface', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.intersects (myData.get (i).getKey ())) {', ' returnVal.addAll (myData.get (i).getData ().find (query));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return myData.get (0).getData ().depth () + 1; ', ' }', ' ', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', 'abstract class AMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> implements IMetricDataListABCD <PointInMetricSpace,KeyType, DataType> {', '', ' // this is the data that is actually stored in the list', ' private ArrayList <DataWrapper <KeyType, DataType>> myData;', ' ', ' // this is the sphere that bounds everything in the list', ' private SphereABCD <PointInMetricSpace> myBoundingSphere;', ' ', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myBoundingSphere; ', ' }', ' ', ' public int size () {', ' if (myData != null)', ' return myData.size (); ', ' else', ' return 0;', ' }', ' ', ' public DataWrapper <KeyType, DataType> get (int pos) {', ' return myData.get (pos);', ' }', ' ', ' public void replaceKey (int pos, KeyType keyToAdd) {', ' DataWrapper <KeyType, DataType> temp = myData.remove (pos);', ' DataWrapper <KeyType, DataType> newOne = new DataWrapper <KeyType, DataType> (keyToAdd, temp.getData ());', ' myData.add (pos, newOne);', ' }', ' ', ' public void add (KeyType keyToAdd, DataType dataToAdd) {', ' ', ' // if this is the first add, then set everyone up', ' if (myData == null) {', ' PointInMetricSpace myCentroid = keyToAdd.getPointInInterior ();', ' myBoundingSphere = new SphereABCD <PointInMetricSpace> (myCentroid, keyToAdd.maxDistanceTo (myCentroid));', ' myData = new ArrayList <DataWrapper <KeyType, DataType>> ();', ' ', ' // otherwise, extend the sphere if needed', ' } else {', ' myBoundingSphere.swallow (keyToAdd);', ' }', ' ', ' // add the data', ' myData.add (new DataWrapper <KeyType, DataType> (keyToAdd, dataToAdd));', ' }', ' ', ' // we want to potentially allow many implementations of the splitting lalgorithm', ' abstract public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // this is here so the actual splitting algorithn can access the list and change the sphere', ' protected ArrayList <DataWrapper <KeyType, DataType>> getList () {', ' return myData;', ' }', ' ', ' // this is here so the splitting algorithm can modify the list and the sphere', ' protected void replaceGuts (AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> withMe) {', ' myData = withMe.myData;', ' myBoundingSphere = withMe.myBoundingSphere;', ' }', ' ', '}', '', '// this is a particular implementation of the metric data list that uses a simple quadratic clustering', '// algorithm to perform a list split. It picks two "seeds" (the most distant objects) and then repeatedly', '// adds to the two new lists by choosing the objects closest to the seeds', 'class ChrisMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> extends AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> {', '', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo () {', ' ', ' // first, we need to find the two most distant points in the list', ' ArrayList <DataWrapper <KeyType, DataType>> myData = getList ();', ' int bestI = 0, bestJ = 0;', ' double maxDist = -1.0;', ' for (int i = 0; i < myData.size (); i++) {', ' for (int j = i + 1; j < myData.size (); j++) {', ' ', ' // get the two keys', ' DataWrapper <KeyType, DataType> pointOne = myData.get (i);', ' DataWrapper <KeyType, DataType> pointTwo = myData.get (j);', ' ', ' // find the difference between them', ' double curDist = pointOne.getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', '', ' // see if it is the biggest', ' if (curDist > maxDist) {', ' maxDist = curDist;', ' bestI = i;', ' bestJ = j;', ' }', ' }', ' }', ' ', ' // now, we have the best two points; those are seeds for the clustering', ' DataWrapper <KeyType, DataType> pointOne = myData.remove (bestI);', ' DataWrapper <KeyType, DataType> pointTwo = myData.remove (bestJ - 1);', ' ', ' // these are the two new lists', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listOne = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listTwo = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' ', ' // put the two seeds in', ' listOne.add (pointOne.getKey (), pointOne.getData ());', ' listTwo.add (pointTwo.getKey (), pointTwo.getData ());', ' ', ' // and add everyone else in', ' while (myData.size () != 0) {', ' ', ' // find the one closest to the first seed', ' int bestIndex = 0;', ' double bestDist = 9e99;', ' ', ' // loop thru all of the candidate data objects', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listOne.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' ', ' // break if no more data', ' if (myData.size () == 0)', ' break;', ' ', ' // loop thru all of the candidate data objects', ' bestDist = 9e99;', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ()) < bestDist) {'] | [' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }'] | [' }', ' ', ' // and add the best in', ' listTwo.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' }', ' ', ' // now we replace our own guts with the first list', ' replaceGuts (listOne);', ' ', ' // and return the other list', ' return listTwo;', ' }', '}', '', 'interface IMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> {', ' ', ' // add a new pair to the list', ' public void add (KeyType keyToAdd, DataType dataToAdd);', ' ', ' // replace a key at the indicated position', ' public void replaceKey (int pos, KeyType keyToAdd);', ' ', ' // get the key, data pair that resides at a particular position', ' public DataWrapper <KeyType, DataType> get (int pos);', ' ', ' // return the number of items in the list', ' public int size ();', ' ', ' // split the list in two, using some clutering algorithm', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // get a sphere that totally bounds all of the objects in the list', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class MTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public MTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class SCMTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public SCMTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', '', 'public class MTreeTester extends TestCase {', ' ', ' // compare two lists of strings to see if the contents are the same', ' private boolean compareStringSets (ArrayList <String> setOne, ArrayList <String> setTwo) {', ' ', ' // sort the sets and make sure they are the same', ' boolean returnVal = true;', ' if (setOne.size () == setTwo.size ()) {', ' Collections.sort (setOne);', ' Collections.sort (setTwo);', ' for (int i = 0; i < setOne.size (); i++) {', ' if (!setOne.get (i).equals (setTwo.get (i))) {', ' returnVal = false;', ' break; ', ' }', ' }', ' } else {', ' returnVal = false;', ' }', ' ', ' // print out the result', ' System.out.println ("**** Expected:");', ' for (int i = 0; i < setOne.size (); i++) {', ' System.out.format (setOne.get (i) + " ");', ' }', ' System.out.println ("\\n**** Got:");', ' for (int i = 0; i < setTwo.size (); i++) {', ' System.out.format (setTwo.get (i) + " ");', ' }', ' System.out.println ("");', ' ', ' return returnVal;', ' }', ' ', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST SIMPLE ONE DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testOneDimRangeQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.find (query, expectedQuerySize / 2);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.find (query, expectedQuerySize / 2);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (numPoints);', ' result1 = myTree.find (query, expectedQuerySize);', ' result2 = hisTree.find (query, expectedQuerySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // like the last one, but runs a top k', ' private void testOneDimTopKQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (167);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.findKClosest (query, querySize);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (0);', ' result1 = myTree.findKClosest (query, querySize);', ' result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST MULTI-DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimRangeQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' double dist1 = 0;', ' double dist2 = 0;', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' dist1 = Math.sqrt (numDims) * expectedQuerySize / 2.0;', ' dist2 = Math.sqrt (numDims) * expectedQuerySize;', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' // do a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, (int) expectedQuerySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = myTree.findKClosest (query2, (int) expectedQuerySize);', ' ', ' // find the distance to the furthest point in both cases', ' for (int i = 0; i < (int) expectedQuerySize; i++) {', ' double newDist = result1.get (i).getKey ().getDistance (query1);', ' if (newDist > dist1)', ' dist1 = newDist;', ' newDist = result2.get (i).getKey ().getDistance (query2);', ' if (newDist > dist2)', ' dist2 = newDist;', ' }', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.find (query1, dist1);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.find (query1, dist1);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.find (query2, dist2);', ' result2 = hisTree.find (query2, dist2);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimTopKQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, querySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.findKClosest (query1, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.findKClosest (query2, querySize);', ' result2 = hisTree.findKClosest (query2, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' ', ' /**', ' * "TIER 1" TESTS', ' * NONE OF THESE REQUIRE ANY SPLITS', ' */', ' public void testEasy1() {', ' testOneDimRangeQuery (true, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy2() {', ' testOneDimRangeQuery (false, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy3() {', ' testOneDimRangeQuery (true, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy4() {', ' testOneDimRangeQuery (false, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy5() {', ' testMultiDimRangeQuery (true, 1, 5, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy6() {', ' testMultiDimRangeQuery (false, 1, 10, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy7() {', ' testMultiDimRangeQuery (true, 1, 5, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy8() {', ' testMultiDimRangeQuery (false, 1, 15, 10000, 10000, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 2" TESTS', ' * NONE OF THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testMod1() {', ' testOneDimRangeQuery (true, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod2() {', ' testOneDimRangeQuery (false, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod3() {', ' testOneDimRangeQuery (true, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod4() {', ' testOneDimRangeQuery (false, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod5() {', ' testMultiDimRangeQuery (true, 2, 5, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod6() {', ' testMultiDimRangeQuery (false, 2, 10, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod7() {', ' testMultiDimRangeQuery (true, 2, 5, 10000, 100, 1000, 10);', ' }', ' ', ' public void testMod8() {', ' testMultiDimRangeQuery (false, 2, 15, 10000, 100, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 3" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testHard1() {', ' testOneDimRangeQuery (true, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard2() {', ' testOneDimRangeQuery (false, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard3() {', ' testOneDimRangeQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard4() {', ' testOneDimRangeQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard5() {', ' testMultiDimRangeQuery (true, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard6() {', ' testMultiDimRangeQuery (false, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard7() {', ' testMultiDimRangeQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard8() {', ' testMultiDimRangeQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', ' ', ' /**', ' * "TIER 4" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE AND THEY TEST THE TOPK FUNCTIONALITY', ' */', ' ', ' public void testTopK1() {', ' testOneDimTopKQuery (true, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK2() {', ' testOneDimTopKQuery (false, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK3() {', ' testOneDimTopKQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK4() {', ' testOneDimTopKQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK5() {', ' testMultiDimTopKQuery (true, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK6() {', ' testMultiDimTopKQuery (false, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK7() {', ' testMultiDimTopKQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK8() {', ' testMultiDimTopKQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', '}'] | [{'reason_category': 'Loop Body', 'usage_line': 683}, {'reason_category': 'If Body', 'usage_line': 683}, {'reason_category': 'Loop Body', 'usage_line': 684}, {'reason_category': 'If Body', 'usage_line': 684}, {'reason_category': 'Loop Body', 'usage_line': 685}, {'reason_category': 'If Body', 'usage_line': 685}] | Variable 'myData' used at line 683 is defined at line 622 and has a Long-Range dependency.
Variable 'i' used at line 683 is defined at line 681 and has a Short-Range dependency.
Function 'getKey' used at line 683 is defined at line 439 and has a Long-Range dependency.
Function 'getPointInInterior' used at line 683 is defined at line 122 and has a Long-Range dependency.
Function 'getDistance' used at line 683 is defined at line 133 and has a Long-Range dependency.
Variable 'pointTwo' used at line 683 is defined at line 646 and has a Long-Range dependency.
Variable 'bestDist' used at line 683 is defined at line 680 and has a Short-Range dependency.
Variable 'i' used at line 684 is defined at line 681 and has a Short-Range dependency.
Variable 'bestIndex' used at line 684 is defined at line 660 and has a Medium-Range dependency. | {'Loop Body': 3, 'If Body': 3} | {'Variable Long-Range': 2, 'Variable Short-Range': 3, 'Function Long-Range': 3, 'Variable Medium-Range': 1} |
infilling_java | MTreeTester | 682 | 686 | ['import junit.framework.TestCase;', 'import java.util.ArrayList;', 'import java.util.Random;', 'import java.util.Collections;', '', '// this is a map from a set of keys of type PointInMetricSpace to a', '// set of data of type DataType', 'interface IMTree <Key extends IPointInMetricSpace <Key>, Data> {', ' ', ' // insert a new key/data pair into the map', ' void insert (Key keyToAdd, Data dataToAdd);', ' ', ' // find all of the key/data pairs in the map that fall within a', ' // particular distance of query point if no results are found, then', ' // an empty array is returned (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> find (Key query, double distance);', ' ', ' // find the k closest key/data pairs in the map to a particular', ' // query point ', ' //', ' // if the number of points in the map is less than k, then the', ' // returned list will have less than k pairs in it', ' //', ' // if the number of points is zero, then an empty array is returned', ' // (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> findKClosest (Key query, int k);', ' ', ' // returns the number of nodes that exist on a path from root to leaf in the tree...', ' // whtever the details of the implementation are, a tree with a single leaf node should return 1, and a tree', ' // with more than one lead node should return at least two (since it must have at least one internal node).', ' public int depth ();', ' ', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', '', 'interface IDoubleVector {', '', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '', '// this correponds to some geometric object in a metric space; the object is built out of', '// one or more points of type PointInMetricSpace', 'interface IObjectInMetricSpaceABCD <PointInMetricSpace extends IPointInMetricSpace<PointInMetricSpace>> {', ' ', ' // get the maximum distance from some point on the shape to a particular point in the metric space', ' double maxDistanceTo (PointInMetricSpace checkMe);', ' ', ' // return some arbitrary point on the interior of the geometric object', ' PointInMetricSpace getPointInInterior ();', '}', '', '', '// this interface corresponds to a point in some metric space', 'interface IPointInMetricSpace <PointInMetricSpace> {', ' ', ' // get the distance to another point', ' // ', ' // for this to work in an M-Tree, distances should be "metric" and', ' // obey the triangle inequality', ' double getDistance (PointInMetricSpace toMe);', '}', '', '// this is the basic node type in the structure', 'interface IMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> {', ' ', ' // insert a new key/data pair into the structure. The return value is a new MTreeNode if there was', ' // a split in response to the insertion, or a null if there was no split', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd);', ' ', ' // find all of the key/data pairs in the structure that fall within a particular query sphere', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query); ', ' ', ' // find the set of items closest to the given query point', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ);', ' ', ' // returns a sphere that totally encompasses everything in the node and its subtree', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', ' ', ' // returns the depth', ' public int depth ();', '}', '', '// this is a point in a particular metric space', 'class PointABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the point', ' private PointInMetricSpace me;', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return me; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return checkMe.getDistance (me); ', ' }', ' ', ' // contruct a point', ' public PointABCD (PointInMetricSpace useMe) {', ' me = useMe; ', ' }', '}', '', 'class PQueueABCD <PointInMetricSpace, DataType> {', ' ', ' // this is an object in the queue', ' private class Wrapper {', ' DataWrapper <PointInMetricSpace, DataType> myData;', ' double distance;', ' }', ' ', ' // this is the actual queue', ' ArrayList <Wrapper> myList;', ' ', ' // this is the largest distance value currently in the queue', ' double large;', ' ', ' // this is the max number of objects', ' int maxCount;', ' ', ' // create a priority queue with the speced number of slots', ' PQueueABCD (int maxCountIn) {', ' maxCount = maxCountIn;', ' myList = new ArrayList <Wrapper> ();', ' large = 9e99;', ' }', ' ', ' // get the largest distance in the queue', ' double getDist () {', ' return large;', ' }', ' ', ' // add a new object to the queue... the insertion is ignored if the distance value', ' // exceeds the largest that is in the queue and the queue is already full', ' void insert (PointInMetricSpace key, DataType data, double distance) {', ' ', ' // if we are full, remove the one with the largest distance', ' if (myList.size () == maxCount && distance < large) {', ' ', ' int badIndex = 0;', ' double maxDist = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > maxDist) {', ' maxDist = myList.get (i).distance;', ' badIndex = i;', ' }', ' }', ' ', ' myList.remove (badIndex);', ' }', ' ', ' // see if there is room', ' if (myList.size () < maxCount) {', ' ', ' // add it ', ' Wrapper newOne = new Wrapper ();', ' newOne.myData = new DataWrapper <PointInMetricSpace, DataType> (key, data);', ' newOne.distance = distance;', ' myList.add (newOne); ', ' }', ' ', ' // if we are full, reset the max distance', ' if (myList.size () == maxCount) {', ' large = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > large) {', ' large = myList.get (i).distance;', ' }', ' }', ' }', ' ', ' }', ' ', ' // extracts the contents of the queue', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> done () {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' for (int i = 0; i < myList.size (); i++) {', ' returnVal.add (myList.get (i).myData); ', ' }', ' ', ' return returnVal;', ' }', ' ', '}', '', '// this is a sphere in a particular metric space', 'class SphereABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the center of the sphere and its radius', ' private PointInMetricSpace center;', ' private double radius;', ' ', ' // build a sphere out of its center and its radius', ' public SphereABCD (PointInMetricSpace centerIn, double radiusIn) {', ' center = centerIn;', ' radius = radiusIn;', ' }', ' ', ' // increase the size of the sphere so it contains the object swallowMe', ' public void swallow (IObjectInMetricSpaceABCD <PointInMetricSpace> swallowMe) {', ' ', ' // see if we need to increase the radius to swallow this guy', ' double dist = swallowMe.maxDistanceTo (center);', ' if (dist > radius)', ' radius = dist;', ' }', ' ', ' // check to see if a sphere intersects another sphere', ' public boolean intersects (SphereABCD <PointInMetricSpace> me) {', ' return (me.center.getDistance (center) <= me.radius + radius);', ' }', ' ', ' // check to see if the sphere contains a point', ' public boolean contains (PointInMetricSpace checkMe) {', ' return (checkMe.getDistance (center) <= radius);', ' }', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return center; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return radius + checkMe.getDistance (center); ', ' }', '}', '', '', '', 'class OneDimPoint implements IPointInMetricSpace <OneDimPoint> {', ' ', ' // this is the actual double', ' Double value;', ' ', ' // construct this out of a double value', ' public OneDimPoint (double makeFromMe) {', ' value = new Double (makeFromMe);', ' }', ' ', ' // get the distance to another point', ' public double getDistance (OneDimPoint toMe) {', ' if (value > toMe.value)', ' return value - toMe.value;', ' else', ' return toMe.value - value;', ' }', ' ', '}', '', 'class MultiDimPoint implements IPointInMetricSpace <MultiDimPoint> {', ' ', ' // this is the point in a multidimensional space', ' IDoubleVector me;', ' ', ' // make this out of an IDoubleVector', ' public MultiDimPoint (IDoubleVector useMe) {', ' me = useMe;', ' }', ' ', ' // get the Euclidean distance to another point', ' public double getDistance (MultiDimPoint toMe) {', ' double distance = 0.0;', ' try {', ' for (int i = 0; i < me.getLength (); i++) {', ' double diff = me.getItem (i) - toMe.me.getItem (i);', ' diff *= diff;', ' distance += diff;', ' }', ' } catch (OutOfBoundsException e) {', ' throw new IndexOutOfBoundsException ("Can\'t compare two MultiDimPoint objects with different dimensionality!"); ', ' }', ' return Math.sqrt(distance);', ' }', ' ', '}', '// this is a leaf node', 'class LeafMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements ', ' IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myData;', ' ', ' // contructor that takes a data list and builds a node out of it', ' private LeafMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myDataIn) {', ' myData = myDataIn; ', ' }', ' ', ' // constructor that creates an empty node', ' public LeafMTreeNodeABCD () {', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> (); ', ' }', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // just add in the new data', ' myData.add (new PointABCD <PointInMetricSpace> (keyToAdd), dataToAdd);', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> newOne = myData.splitInTwo ();', ' LeafMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' myQ.insert (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData (), ', ' query.getDistance (myData.get (i).getKey ().getPointInInterior ()));', ' }', ' }', ' }', ' ', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' returnVal.add (new DataWrapper <PointInMetricSpace, DataType> (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData ()));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return 1; ', ' }', '', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', '// this silly little class is just a wrapper for a key, data pair', 'class DataWrapper <Key, Data> {', ' ', ' Key key;', ' Data data;', ' ', ' public DataWrapper (Key keyIn, Data dataIn) {', ' key = keyIn;', ' data = dataIn;', ' }', ' ', ' public Key getKey () {', ' return key;', ' }', ' ', ' public Data getData () {', ' return data;', ' }', '}', '', '', '// this is an internal node', 'class InternalMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType>', ' implements IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> myData;', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' // this constructs a new internal node that holds precisely the two nodes that are passed in', ' public InternalMTreeNodeABCD (IMTreeNodeABCD <PointInMetricSpace, DataType> refOne,', ' IMTreeNodeABCD <PointInMetricSpace, DataType> refTwo) {', ' ', ' // create a necw list and add the two guys in', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> ();', ' myData.add (refOne.getBoundingSphere (), refOne);', ' myData.add (refTwo.getBoundingSphere (), refTwo);', ' }', ' ', ' // this constructs a new node that holds the list of data that we were passed in', ' public InternalMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> useMe) {', ' myData = useMe; ', ' }', ' ', ' // from the interface', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // find the best child; this is the one we are closest to', ' double bestDist = 9e99;', ' int bestIndex = 0;', ' for (int i = 0; i < myData.size (); i++) {', ' ', ' double newDist = myData.get (i).getKey ().getPointInInterior ().getDistance (keyToAdd);', ' if (newDist < bestDist) {', ' bestDist = newDist;', ' bestIndex = i;', ' }', ' }', ' ', ' // do the recursive insert', ' IMTreeNodeABCD <PointInMetricSpace, DataType> newRef = myData.get (bestIndex).getData ().insert (keyToAdd, dataToAdd);', ' ', ' // if we got something back, then there was a split, so add the new node into our list', ' if (newRef != null) {', ' myData.add (newRef.getBoundingSphere (), newRef);', ' }', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> newOne = myData.splitInTwo ();', ' InternalMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.intersects (myData.get (i).getKey ())) {', ' myData.get (i).getData ().findKClosest (query, myQ);', ' }', ' }', ' }', ' ', ' // from the interface', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.intersects (myData.get (i).getKey ())) {', ' returnVal.addAll (myData.get (i).getData ().find (query));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return myData.get (0).getData ().depth () + 1; ', ' }', ' ', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', 'abstract class AMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> implements IMetricDataListABCD <PointInMetricSpace,KeyType, DataType> {', '', ' // this is the data that is actually stored in the list', ' private ArrayList <DataWrapper <KeyType, DataType>> myData;', ' ', ' // this is the sphere that bounds everything in the list', ' private SphereABCD <PointInMetricSpace> myBoundingSphere;', ' ', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myBoundingSphere; ', ' }', ' ', ' public int size () {', ' if (myData != null)', ' return myData.size (); ', ' else', ' return 0;', ' }', ' ', ' public DataWrapper <KeyType, DataType> get (int pos) {', ' return myData.get (pos);', ' }', ' ', ' public void replaceKey (int pos, KeyType keyToAdd) {', ' DataWrapper <KeyType, DataType> temp = myData.remove (pos);', ' DataWrapper <KeyType, DataType> newOne = new DataWrapper <KeyType, DataType> (keyToAdd, temp.getData ());', ' myData.add (pos, newOne);', ' }', ' ', ' public void add (KeyType keyToAdd, DataType dataToAdd) {', ' ', ' // if this is the first add, then set everyone up', ' if (myData == null) {', ' PointInMetricSpace myCentroid = keyToAdd.getPointInInterior ();', ' myBoundingSphere = new SphereABCD <PointInMetricSpace> (myCentroid, keyToAdd.maxDistanceTo (myCentroid));', ' myData = new ArrayList <DataWrapper <KeyType, DataType>> ();', ' ', ' // otherwise, extend the sphere if needed', ' } else {', ' myBoundingSphere.swallow (keyToAdd);', ' }', ' ', ' // add the data', ' myData.add (new DataWrapper <KeyType, DataType> (keyToAdd, dataToAdd));', ' }', ' ', ' // we want to potentially allow many implementations of the splitting lalgorithm', ' abstract public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // this is here so the actual splitting algorithn can access the list and change the sphere', ' protected ArrayList <DataWrapper <KeyType, DataType>> getList () {', ' return myData;', ' }', ' ', ' // this is here so the splitting algorithm can modify the list and the sphere', ' protected void replaceGuts (AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> withMe) {', ' myData = withMe.myData;', ' myBoundingSphere = withMe.myBoundingSphere;', ' }', ' ', '}', '', '// this is a particular implementation of the metric data list that uses a simple quadratic clustering', '// algorithm to perform a list split. It picks two "seeds" (the most distant objects) and then repeatedly', '// adds to the two new lists by choosing the objects closest to the seeds', 'class ChrisMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> extends AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> {', '', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo () {', ' ', ' // first, we need to find the two most distant points in the list', ' ArrayList <DataWrapper <KeyType, DataType>> myData = getList ();', ' int bestI = 0, bestJ = 0;', ' double maxDist = -1.0;', ' for (int i = 0; i < myData.size (); i++) {', ' for (int j = i + 1; j < myData.size (); j++) {', ' ', ' // get the two keys', ' DataWrapper <KeyType, DataType> pointOne = myData.get (i);', ' DataWrapper <KeyType, DataType> pointTwo = myData.get (j);', ' ', ' // find the difference between them', ' double curDist = pointOne.getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', '', ' // see if it is the biggest', ' if (curDist > maxDist) {', ' maxDist = curDist;', ' bestI = i;', ' bestJ = j;', ' }', ' }', ' }', ' ', ' // now, we have the best two points; those are seeds for the clustering', ' DataWrapper <KeyType, DataType> pointOne = myData.remove (bestI);', ' DataWrapper <KeyType, DataType> pointTwo = myData.remove (bestJ - 1);', ' ', ' // these are the two new lists', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listOne = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listTwo = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' ', ' // put the two seeds in', ' listOne.add (pointOne.getKey (), pointOne.getData ());', ' listTwo.add (pointTwo.getKey (), pointTwo.getData ());', ' ', ' // and add everyone else in', ' while (myData.size () != 0) {', ' ', ' // find the one closest to the first seed', ' int bestIndex = 0;', ' double bestDist = 9e99;', ' ', ' // loop thru all of the candidate data objects', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listOne.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' ', ' // break if no more data', ' if (myData.size () == 0)', ' break;', ' ', ' // loop thru all of the candidate data objects', ' bestDist = 9e99;', ' for (int i = 0; i < myData.size (); i++) {'] | [' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }'] | [' ', ' // and add the best in', ' listTwo.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' }', ' ', ' // now we replace our own guts with the first list', ' replaceGuts (listOne);', ' ', ' // and return the other list', ' return listTwo;', ' }', '}', '', 'interface IMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> {', ' ', ' // add a new pair to the list', ' public void add (KeyType keyToAdd, DataType dataToAdd);', ' ', ' // replace a key at the indicated position', ' public void replaceKey (int pos, KeyType keyToAdd);', ' ', ' // get the key, data pair that resides at a particular position', ' public DataWrapper <KeyType, DataType> get (int pos);', ' ', ' // return the number of items in the list', ' public int size ();', ' ', ' // split the list in two, using some clutering algorithm', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // get a sphere that totally bounds all of the objects in the list', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class MTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public MTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class SCMTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public SCMTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', '', 'public class MTreeTester extends TestCase {', ' ', ' // compare two lists of strings to see if the contents are the same', ' private boolean compareStringSets (ArrayList <String> setOne, ArrayList <String> setTwo) {', ' ', ' // sort the sets and make sure they are the same', ' boolean returnVal = true;', ' if (setOne.size () == setTwo.size ()) {', ' Collections.sort (setOne);', ' Collections.sort (setTwo);', ' for (int i = 0; i < setOne.size (); i++) {', ' if (!setOne.get (i).equals (setTwo.get (i))) {', ' returnVal = false;', ' break; ', ' }', ' }', ' } else {', ' returnVal = false;', ' }', ' ', ' // print out the result', ' System.out.println ("**** Expected:");', ' for (int i = 0; i < setOne.size (); i++) {', ' System.out.format (setOne.get (i) + " ");', ' }', ' System.out.println ("\\n**** Got:");', ' for (int i = 0; i < setTwo.size (); i++) {', ' System.out.format (setTwo.get (i) + " ");', ' }', ' System.out.println ("");', ' ', ' return returnVal;', ' }', ' ', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST SIMPLE ONE DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testOneDimRangeQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.find (query, expectedQuerySize / 2);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.find (query, expectedQuerySize / 2);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (numPoints);', ' result1 = myTree.find (query, expectedQuerySize);', ' result2 = hisTree.find (query, expectedQuerySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // like the last one, but runs a top k', ' private void testOneDimTopKQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (167);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.findKClosest (query, querySize);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (0);', ' result1 = myTree.findKClosest (query, querySize);', ' result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST MULTI-DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimRangeQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' double dist1 = 0;', ' double dist2 = 0;', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' dist1 = Math.sqrt (numDims) * expectedQuerySize / 2.0;', ' dist2 = Math.sqrt (numDims) * expectedQuerySize;', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' // do a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, (int) expectedQuerySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = myTree.findKClosest (query2, (int) expectedQuerySize);', ' ', ' // find the distance to the furthest point in both cases', ' for (int i = 0; i < (int) expectedQuerySize; i++) {', ' double newDist = result1.get (i).getKey ().getDistance (query1);', ' if (newDist > dist1)', ' dist1 = newDist;', ' newDist = result2.get (i).getKey ().getDistance (query2);', ' if (newDist > dist2)', ' dist2 = newDist;', ' }', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.find (query1, dist1);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.find (query1, dist1);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.find (query2, dist2);', ' result2 = hisTree.find (query2, dist2);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimTopKQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, querySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.findKClosest (query1, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.findKClosest (query2, querySize);', ' result2 = hisTree.findKClosest (query2, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' ', ' /**', ' * "TIER 1" TESTS', ' * NONE OF THESE REQUIRE ANY SPLITS', ' */', ' public void testEasy1() {', ' testOneDimRangeQuery (true, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy2() {', ' testOneDimRangeQuery (false, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy3() {', ' testOneDimRangeQuery (true, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy4() {', ' testOneDimRangeQuery (false, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy5() {', ' testMultiDimRangeQuery (true, 1, 5, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy6() {', ' testMultiDimRangeQuery (false, 1, 10, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy7() {', ' testMultiDimRangeQuery (true, 1, 5, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy8() {', ' testMultiDimRangeQuery (false, 1, 15, 10000, 10000, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 2" TESTS', ' * NONE OF THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testMod1() {', ' testOneDimRangeQuery (true, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod2() {', ' testOneDimRangeQuery (false, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod3() {', ' testOneDimRangeQuery (true, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod4() {', ' testOneDimRangeQuery (false, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod5() {', ' testMultiDimRangeQuery (true, 2, 5, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod6() {', ' testMultiDimRangeQuery (false, 2, 10, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod7() {', ' testMultiDimRangeQuery (true, 2, 5, 10000, 100, 1000, 10);', ' }', ' ', ' public void testMod8() {', ' testMultiDimRangeQuery (false, 2, 15, 10000, 100, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 3" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testHard1() {', ' testOneDimRangeQuery (true, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard2() {', ' testOneDimRangeQuery (false, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard3() {', ' testOneDimRangeQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard4() {', ' testOneDimRangeQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard5() {', ' testMultiDimRangeQuery (true, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard6() {', ' testMultiDimRangeQuery (false, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard7() {', ' testMultiDimRangeQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard8() {', ' testMultiDimRangeQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', ' ', ' /**', ' * "TIER 4" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE AND THEY TEST THE TOPK FUNCTIONALITY', ' */', ' ', ' public void testTopK1() {', ' testOneDimTopKQuery (true, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK2() {', ' testOneDimTopKQuery (false, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK3() {', ' testOneDimTopKQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK4() {', ' testOneDimTopKQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK5() {', ' testMultiDimTopKQuery (true, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK6() {', ' testMultiDimTopKQuery (false, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK7() {', ' testMultiDimTopKQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK8() {', ' testMultiDimTopKQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', '}'] | [{'reason_category': 'Loop Body', 'usage_line': 682}, {'reason_category': 'If Condition', 'usage_line': 682}, {'reason_category': 'Loop Body', 'usage_line': 683}, {'reason_category': 'If Body', 'usage_line': 683}, {'reason_category': 'Loop Body', 'usage_line': 684}, {'reason_category': 'If Body', 'usage_line': 684}, {'reason_category': 'Loop Body', 'usage_line': 685}, {'reason_category': 'If Body', 'usage_line': 685}, {'reason_category': 'Loop Body', 'usage_line': 686}] | Variable 'myData' used at line 682 is defined at line 622 and has a Long-Range dependency.
Variable 'i' used at line 682 is defined at line 681 and has a Short-Range dependency.
Function 'getKey' used at line 682 is defined at line 439 and has a Long-Range dependency.
Function 'getPointInInterior' used at line 682 is defined at line 122 and has a Long-Range dependency.
Function 'getDistance' used at line 682 is defined at line 133 and has a Long-Range dependency.
Variable 'pointTwo' used at line 682 is defined at line 646 and has a Long-Range dependency.
Variable 'bestDist' used at line 682 is defined at line 680 and has a Short-Range dependency.
Variable 'myData' used at line 683 is defined at line 622 and has a Long-Range dependency.
Variable 'i' used at line 683 is defined at line 681 and has a Short-Range dependency.
Function 'getKey' used at line 683 is defined at line 439 and has a Long-Range dependency.
Function 'getPointInInterior' used at line 683 is defined at line 122 and has a Long-Range dependency.
Function 'getDistance' used at line 683 is defined at line 133 and has a Long-Range dependency.
Variable 'pointTwo' used at line 683 is defined at line 646 and has a Long-Range dependency.
Variable 'bestDist' used at line 683 is defined at line 680 and has a Short-Range dependency.
Variable 'i' used at line 684 is defined at line 681 and has a Short-Range dependency.
Variable 'bestIndex' used at line 684 is defined at line 660 and has a Medium-Range dependency. | {'Loop Body': 5, 'If Condition': 1, 'If Body': 3} | {'Variable Long-Range': 4, 'Variable Short-Range': 5, 'Function Long-Range': 6, 'Variable Medium-Range': 1} |
infilling_java | MTreeTester | 731 | 734 | ['import junit.framework.TestCase;', 'import java.util.ArrayList;', 'import java.util.Random;', 'import java.util.Collections;', '', '// this is a map from a set of keys of type PointInMetricSpace to a', '// set of data of type DataType', 'interface IMTree <Key extends IPointInMetricSpace <Key>, Data> {', ' ', ' // insert a new key/data pair into the map', ' void insert (Key keyToAdd, Data dataToAdd);', ' ', ' // find all of the key/data pairs in the map that fall within a', ' // particular distance of query point if no results are found, then', ' // an empty array is returned (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> find (Key query, double distance);', ' ', ' // find the k closest key/data pairs in the map to a particular', ' // query point ', ' //', ' // if the number of points in the map is less than k, then the', ' // returned list will have less than k pairs in it', ' //', ' // if the number of points is zero, then an empty array is returned', ' // (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> findKClosest (Key query, int k);', ' ', ' // returns the number of nodes that exist on a path from root to leaf in the tree...', ' // whtever the details of the implementation are, a tree with a single leaf node should return 1, and a tree', ' // with more than one lead node should return at least two (since it must have at least one internal node).', ' public int depth ();', ' ', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', '', 'interface IDoubleVector {', '', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '', '// this correponds to some geometric object in a metric space; the object is built out of', '// one or more points of type PointInMetricSpace', 'interface IObjectInMetricSpaceABCD <PointInMetricSpace extends IPointInMetricSpace<PointInMetricSpace>> {', ' ', ' // get the maximum distance from some point on the shape to a particular point in the metric space', ' double maxDistanceTo (PointInMetricSpace checkMe);', ' ', ' // return some arbitrary point on the interior of the geometric object', ' PointInMetricSpace getPointInInterior ();', '}', '', '', '// this interface corresponds to a point in some metric space', 'interface IPointInMetricSpace <PointInMetricSpace> {', ' ', ' // get the distance to another point', ' // ', ' // for this to work in an M-Tree, distances should be "metric" and', ' // obey the triangle inequality', ' double getDistance (PointInMetricSpace toMe);', '}', '', '// this is the basic node type in the structure', 'interface IMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> {', ' ', ' // insert a new key/data pair into the structure. The return value is a new MTreeNode if there was', ' // a split in response to the insertion, or a null if there was no split', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd);', ' ', ' // find all of the key/data pairs in the structure that fall within a particular query sphere', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query); ', ' ', ' // find the set of items closest to the given query point', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ);', ' ', ' // returns a sphere that totally encompasses everything in the node and its subtree', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', ' ', ' // returns the depth', ' public int depth ();', '}', '', '// this is a point in a particular metric space', 'class PointABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the point', ' private PointInMetricSpace me;', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return me; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return checkMe.getDistance (me); ', ' }', ' ', ' // contruct a point', ' public PointABCD (PointInMetricSpace useMe) {', ' me = useMe; ', ' }', '}', '', 'class PQueueABCD <PointInMetricSpace, DataType> {', ' ', ' // this is an object in the queue', ' private class Wrapper {', ' DataWrapper <PointInMetricSpace, DataType> myData;', ' double distance;', ' }', ' ', ' // this is the actual queue', ' ArrayList <Wrapper> myList;', ' ', ' // this is the largest distance value currently in the queue', ' double large;', ' ', ' // this is the max number of objects', ' int maxCount;', ' ', ' // create a priority queue with the speced number of slots', ' PQueueABCD (int maxCountIn) {', ' maxCount = maxCountIn;', ' myList = new ArrayList <Wrapper> ();', ' large = 9e99;', ' }', ' ', ' // get the largest distance in the queue', ' double getDist () {', ' return large;', ' }', ' ', ' // add a new object to the queue... the insertion is ignored if the distance value', ' // exceeds the largest that is in the queue and the queue is already full', ' void insert (PointInMetricSpace key, DataType data, double distance) {', ' ', ' // if we are full, remove the one with the largest distance', ' if (myList.size () == maxCount && distance < large) {', ' ', ' int badIndex = 0;', ' double maxDist = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > maxDist) {', ' maxDist = myList.get (i).distance;', ' badIndex = i;', ' }', ' }', ' ', ' myList.remove (badIndex);', ' }', ' ', ' // see if there is room', ' if (myList.size () < maxCount) {', ' ', ' // add it ', ' Wrapper newOne = new Wrapper ();', ' newOne.myData = new DataWrapper <PointInMetricSpace, DataType> (key, data);', ' newOne.distance = distance;', ' myList.add (newOne); ', ' }', ' ', ' // if we are full, reset the max distance', ' if (myList.size () == maxCount) {', ' large = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > large) {', ' large = myList.get (i).distance;', ' }', ' }', ' }', ' ', ' }', ' ', ' // extracts the contents of the queue', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> done () {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' for (int i = 0; i < myList.size (); i++) {', ' returnVal.add (myList.get (i).myData); ', ' }', ' ', ' return returnVal;', ' }', ' ', '}', '', '// this is a sphere in a particular metric space', 'class SphereABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the center of the sphere and its radius', ' private PointInMetricSpace center;', ' private double radius;', ' ', ' // build a sphere out of its center and its radius', ' public SphereABCD (PointInMetricSpace centerIn, double radiusIn) {', ' center = centerIn;', ' radius = radiusIn;', ' }', ' ', ' // increase the size of the sphere so it contains the object swallowMe', ' public void swallow (IObjectInMetricSpaceABCD <PointInMetricSpace> swallowMe) {', ' ', ' // see if we need to increase the radius to swallow this guy', ' double dist = swallowMe.maxDistanceTo (center);', ' if (dist > radius)', ' radius = dist;', ' }', ' ', ' // check to see if a sphere intersects another sphere', ' public boolean intersects (SphereABCD <PointInMetricSpace> me) {', ' return (me.center.getDistance (center) <= me.radius + radius);', ' }', ' ', ' // check to see if the sphere contains a point', ' public boolean contains (PointInMetricSpace checkMe) {', ' return (checkMe.getDistance (center) <= radius);', ' }', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return center; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return radius + checkMe.getDistance (center); ', ' }', '}', '', '', '', 'class OneDimPoint implements IPointInMetricSpace <OneDimPoint> {', ' ', ' // this is the actual double', ' Double value;', ' ', ' // construct this out of a double value', ' public OneDimPoint (double makeFromMe) {', ' value = new Double (makeFromMe);', ' }', ' ', ' // get the distance to another point', ' public double getDistance (OneDimPoint toMe) {', ' if (value > toMe.value)', ' return value - toMe.value;', ' else', ' return toMe.value - value;', ' }', ' ', '}', '', 'class MultiDimPoint implements IPointInMetricSpace <MultiDimPoint> {', ' ', ' // this is the point in a multidimensional space', ' IDoubleVector me;', ' ', ' // make this out of an IDoubleVector', ' public MultiDimPoint (IDoubleVector useMe) {', ' me = useMe;', ' }', ' ', ' // get the Euclidean distance to another point', ' public double getDistance (MultiDimPoint toMe) {', ' double distance = 0.0;', ' try {', ' for (int i = 0; i < me.getLength (); i++) {', ' double diff = me.getItem (i) - toMe.me.getItem (i);', ' diff *= diff;', ' distance += diff;', ' }', ' } catch (OutOfBoundsException e) {', ' throw new IndexOutOfBoundsException ("Can\'t compare two MultiDimPoint objects with different dimensionality!"); ', ' }', ' return Math.sqrt(distance);', ' }', ' ', '}', '// this is a leaf node', 'class LeafMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements ', ' IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myData;', ' ', ' // contructor that takes a data list and builds a node out of it', ' private LeafMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myDataIn) {', ' myData = myDataIn; ', ' }', ' ', ' // constructor that creates an empty node', ' public LeafMTreeNodeABCD () {', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> (); ', ' }', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // just add in the new data', ' myData.add (new PointABCD <PointInMetricSpace> (keyToAdd), dataToAdd);', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> newOne = myData.splitInTwo ();', ' LeafMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' myQ.insert (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData (), ', ' query.getDistance (myData.get (i).getKey ().getPointInInterior ()));', ' }', ' }', ' }', ' ', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' returnVal.add (new DataWrapper <PointInMetricSpace, DataType> (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData ()));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return 1; ', ' }', '', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', '// this silly little class is just a wrapper for a key, data pair', 'class DataWrapper <Key, Data> {', ' ', ' Key key;', ' Data data;', ' ', ' public DataWrapper (Key keyIn, Data dataIn) {', ' key = keyIn;', ' data = dataIn;', ' }', ' ', ' public Key getKey () {', ' return key;', ' }', ' ', ' public Data getData () {', ' return data;', ' }', '}', '', '', '// this is an internal node', 'class InternalMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType>', ' implements IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> myData;', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' // this constructs a new internal node that holds precisely the two nodes that are passed in', ' public InternalMTreeNodeABCD (IMTreeNodeABCD <PointInMetricSpace, DataType> refOne,', ' IMTreeNodeABCD <PointInMetricSpace, DataType> refTwo) {', ' ', ' // create a necw list and add the two guys in', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> ();', ' myData.add (refOne.getBoundingSphere (), refOne);', ' myData.add (refTwo.getBoundingSphere (), refTwo);', ' }', ' ', ' // this constructs a new node that holds the list of data that we were passed in', ' public InternalMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> useMe) {', ' myData = useMe; ', ' }', ' ', ' // from the interface', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // find the best child; this is the one we are closest to', ' double bestDist = 9e99;', ' int bestIndex = 0;', ' for (int i = 0; i < myData.size (); i++) {', ' ', ' double newDist = myData.get (i).getKey ().getPointInInterior ().getDistance (keyToAdd);', ' if (newDist < bestDist) {', ' bestDist = newDist;', ' bestIndex = i;', ' }', ' }', ' ', ' // do the recursive insert', ' IMTreeNodeABCD <PointInMetricSpace, DataType> newRef = myData.get (bestIndex).getData ().insert (keyToAdd, dataToAdd);', ' ', ' // if we got something back, then there was a split, so add the new node into our list', ' if (newRef != null) {', ' myData.add (newRef.getBoundingSphere (), newRef);', ' }', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> newOne = myData.splitInTwo ();', ' InternalMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.intersects (myData.get (i).getKey ())) {', ' myData.get (i).getData ().findKClosest (query, myQ);', ' }', ' }', ' }', ' ', ' // from the interface', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.intersects (myData.get (i).getKey ())) {', ' returnVal.addAll (myData.get (i).getData ().find (query));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return myData.get (0).getData ().depth () + 1; ', ' }', ' ', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', 'abstract class AMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> implements IMetricDataListABCD <PointInMetricSpace,KeyType, DataType> {', '', ' // this is the data that is actually stored in the list', ' private ArrayList <DataWrapper <KeyType, DataType>> myData;', ' ', ' // this is the sphere that bounds everything in the list', ' private SphereABCD <PointInMetricSpace> myBoundingSphere;', ' ', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myBoundingSphere; ', ' }', ' ', ' public int size () {', ' if (myData != null)', ' return myData.size (); ', ' else', ' return 0;', ' }', ' ', ' public DataWrapper <KeyType, DataType> get (int pos) {', ' return myData.get (pos);', ' }', ' ', ' public void replaceKey (int pos, KeyType keyToAdd) {', ' DataWrapper <KeyType, DataType> temp = myData.remove (pos);', ' DataWrapper <KeyType, DataType> newOne = new DataWrapper <KeyType, DataType> (keyToAdd, temp.getData ());', ' myData.add (pos, newOne);', ' }', ' ', ' public void add (KeyType keyToAdd, DataType dataToAdd) {', ' ', ' // if this is the first add, then set everyone up', ' if (myData == null) {', ' PointInMetricSpace myCentroid = keyToAdd.getPointInInterior ();', ' myBoundingSphere = new SphereABCD <PointInMetricSpace> (myCentroid, keyToAdd.maxDistanceTo (myCentroid));', ' myData = new ArrayList <DataWrapper <KeyType, DataType>> ();', ' ', ' // otherwise, extend the sphere if needed', ' } else {', ' myBoundingSphere.swallow (keyToAdd);', ' }', ' ', ' // add the data', ' myData.add (new DataWrapper <KeyType, DataType> (keyToAdd, dataToAdd));', ' }', ' ', ' // we want to potentially allow many implementations of the splitting lalgorithm', ' abstract public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // this is here so the actual splitting algorithn can access the list and change the sphere', ' protected ArrayList <DataWrapper <KeyType, DataType>> getList () {', ' return myData;', ' }', ' ', ' // this is here so the splitting algorithm can modify the list and the sphere', ' protected void replaceGuts (AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> withMe) {', ' myData = withMe.myData;', ' myBoundingSphere = withMe.myBoundingSphere;', ' }', ' ', '}', '', '// this is a particular implementation of the metric data list that uses a simple quadratic clustering', '// algorithm to perform a list split. It picks two "seeds" (the most distant objects) and then repeatedly', '// adds to the two new lists by choosing the objects closest to the seeds', 'class ChrisMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> extends AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> {', '', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo () {', ' ', ' // first, we need to find the two most distant points in the list', ' ArrayList <DataWrapper <KeyType, DataType>> myData = getList ();', ' int bestI = 0, bestJ = 0;', ' double maxDist = -1.0;', ' for (int i = 0; i < myData.size (); i++) {', ' for (int j = i + 1; j < myData.size (); j++) {', ' ', ' // get the two keys', ' DataWrapper <KeyType, DataType> pointOne = myData.get (i);', ' DataWrapper <KeyType, DataType> pointTwo = myData.get (j);', ' ', ' // find the difference between them', ' double curDist = pointOne.getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', '', ' // see if it is the biggest', ' if (curDist > maxDist) {', ' maxDist = curDist;', ' bestI = i;', ' bestJ = j;', ' }', ' }', ' }', ' ', ' // now, we have the best two points; those are seeds for the clustering', ' DataWrapper <KeyType, DataType> pointOne = myData.remove (bestI);', ' DataWrapper <KeyType, DataType> pointTwo = myData.remove (bestJ - 1);', ' ', ' // these are the two new lists', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listOne = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listTwo = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' ', ' // put the two seeds in', ' listOne.add (pointOne.getKey (), pointOne.getData ());', ' listTwo.add (pointTwo.getKey (), pointTwo.getData ());', ' ', ' // and add everyone else in', ' while (myData.size () != 0) {', ' ', ' // find the one closest to the first seed', ' int bestIndex = 0;', ' double bestDist = 9e99;', ' ', ' // loop thru all of the candidate data objects', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listOne.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' ', ' // break if no more data', ' if (myData.size () == 0)', ' break;', ' ', ' // loop thru all of the candidate data objects', ' bestDist = 9e99;', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listTwo.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' }', ' ', ' // now we replace our own guts with the first list', ' replaceGuts (listOne);', ' ', ' // and return the other list', ' return listTwo;', ' }', '}', '', 'interface IMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> {', ' ', ' // add a new pair to the list', ' public void add (KeyType keyToAdd, DataType dataToAdd);', ' ', ' // replace a key at the indicated position', ' public void replaceKey (int pos, KeyType keyToAdd);', ' ', ' // get the key, data pair that resides at a particular position', ' public DataWrapper <KeyType, DataType> get (int pos);', ' ', ' // return the number of items in the list', ' public int size ();', ' ', ' // split the list in two, using some clutering algorithm', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // get a sphere that totally bounds all of the objects in the list', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class MTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public MTree (int intNodeSize, int leafNodeSize) {'] | [' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }'] | [' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class SCMTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public SCMTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', '', 'public class MTreeTester extends TestCase {', ' ', ' // compare two lists of strings to see if the contents are the same', ' private boolean compareStringSets (ArrayList <String> setOne, ArrayList <String> setTwo) {', ' ', ' // sort the sets and make sure they are the same', ' boolean returnVal = true;', ' if (setOne.size () == setTwo.size ()) {', ' Collections.sort (setOne);', ' Collections.sort (setTwo);', ' for (int i = 0; i < setOne.size (); i++) {', ' if (!setOne.get (i).equals (setTwo.get (i))) {', ' returnVal = false;', ' break; ', ' }', ' }', ' } else {', ' returnVal = false;', ' }', ' ', ' // print out the result', ' System.out.println ("**** Expected:");', ' for (int i = 0; i < setOne.size (); i++) {', ' System.out.format (setOne.get (i) + " ");', ' }', ' System.out.println ("\\n**** Got:");', ' for (int i = 0; i < setTwo.size (); i++) {', ' System.out.format (setTwo.get (i) + " ");', ' }', ' System.out.println ("");', ' ', ' return returnVal;', ' }', ' ', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST SIMPLE ONE DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testOneDimRangeQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.find (query, expectedQuerySize / 2);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.find (query, expectedQuerySize / 2);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (numPoints);', ' result1 = myTree.find (query, expectedQuerySize);', ' result2 = hisTree.find (query, expectedQuerySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // like the last one, but runs a top k', ' private void testOneDimTopKQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (167);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.findKClosest (query, querySize);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (0);', ' result1 = myTree.findKClosest (query, querySize);', ' result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST MULTI-DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimRangeQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' double dist1 = 0;', ' double dist2 = 0;', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' dist1 = Math.sqrt (numDims) * expectedQuerySize / 2.0;', ' dist2 = Math.sqrt (numDims) * expectedQuerySize;', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' // do a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, (int) expectedQuerySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = myTree.findKClosest (query2, (int) expectedQuerySize);', ' ', ' // find the distance to the furthest point in both cases', ' for (int i = 0; i < (int) expectedQuerySize; i++) {', ' double newDist = result1.get (i).getKey ().getDistance (query1);', ' if (newDist > dist1)', ' dist1 = newDist;', ' newDist = result2.get (i).getKey ().getDistance (query2);', ' if (newDist > dist2)', ' dist2 = newDist;', ' }', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.find (query1, dist1);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.find (query1, dist1);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.find (query2, dist2);', ' result2 = hisTree.find (query2, dist2);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimTopKQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, querySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.findKClosest (query1, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.findKClosest (query2, querySize);', ' result2 = hisTree.findKClosest (query2, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' ', ' /**', ' * "TIER 1" TESTS', ' * NONE OF THESE REQUIRE ANY SPLITS', ' */', ' public void testEasy1() {', ' testOneDimRangeQuery (true, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy2() {', ' testOneDimRangeQuery (false, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy3() {', ' testOneDimRangeQuery (true, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy4() {', ' testOneDimRangeQuery (false, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy5() {', ' testMultiDimRangeQuery (true, 1, 5, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy6() {', ' testMultiDimRangeQuery (false, 1, 10, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy7() {', ' testMultiDimRangeQuery (true, 1, 5, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy8() {', ' testMultiDimRangeQuery (false, 1, 15, 10000, 10000, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 2" TESTS', ' * NONE OF THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testMod1() {', ' testOneDimRangeQuery (true, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod2() {', ' testOneDimRangeQuery (false, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod3() {', ' testOneDimRangeQuery (true, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod4() {', ' testOneDimRangeQuery (false, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod5() {', ' testMultiDimRangeQuery (true, 2, 5, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod6() {', ' testMultiDimRangeQuery (false, 2, 10, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod7() {', ' testMultiDimRangeQuery (true, 2, 5, 10000, 100, 1000, 10);', ' }', ' ', ' public void testMod8() {', ' testMultiDimRangeQuery (false, 2, 15, 10000, 100, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 3" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testHard1() {', ' testOneDimRangeQuery (true, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard2() {', ' testOneDimRangeQuery (false, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard3() {', ' testOneDimRangeQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard4() {', ' testOneDimRangeQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard5() {', ' testMultiDimRangeQuery (true, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard6() {', ' testMultiDimRangeQuery (false, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard7() {', ' testMultiDimRangeQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard8() {', ' testMultiDimRangeQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', ' ', ' /**', ' * "TIER 4" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE AND THEY TEST THE TOPK FUNCTIONALITY', ' */', ' ', ' public void testTopK1() {', ' testOneDimTopKQuery (true, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK2() {', ' testOneDimTopKQuery (false, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK3() {', ' testOneDimTopKQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK4() {', ' testOneDimTopKQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK5() {', ' testMultiDimTopKQuery (true, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK6() {', ' testMultiDimTopKQuery (false, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK7() {', ' testMultiDimTopKQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK8() {', ' testMultiDimTopKQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', '}'] | [] | Function 'InternalMTreeNodeABCD.setMaxSize' used at line 731 is defined at line 542 and has a Long-Range dependency.
Variable 'intNodeSize' used at line 731 is defined at line 730 and has a Short-Range dependency.
Function 'LeafMTreeNodeABCD.setMaxSize' used at line 732 is defined at line 420 and has a Long-Range dependency.
Variable 'leafNodeSize' used at line 732 is defined at line 730 and has a Short-Range dependency.
Class 'LeafMTreeNodeABCD' used at line 733 is defined at line 351 and has a Long-Range dependency.
Global_Variable 'root' used at line 733 is defined at line 727 and has a Short-Range dependency. | {} | {'Function Long-Range': 2, 'Variable Short-Range': 2, 'Class Long-Range': 1, 'Global_Variable Short-Range': 1} |
infilling_java | MTreeTester | 744 | 745 | ['import junit.framework.TestCase;', 'import java.util.ArrayList;', 'import java.util.Random;', 'import java.util.Collections;', '', '// this is a map from a set of keys of type PointInMetricSpace to a', '// set of data of type DataType', 'interface IMTree <Key extends IPointInMetricSpace <Key>, Data> {', ' ', ' // insert a new key/data pair into the map', ' void insert (Key keyToAdd, Data dataToAdd);', ' ', ' // find all of the key/data pairs in the map that fall within a', ' // particular distance of query point if no results are found, then', ' // an empty array is returned (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> find (Key query, double distance);', ' ', ' // find the k closest key/data pairs in the map to a particular', ' // query point ', ' //', ' // if the number of points in the map is less than k, then the', ' // returned list will have less than k pairs in it', ' //', ' // if the number of points is zero, then an empty array is returned', ' // (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> findKClosest (Key query, int k);', ' ', ' // returns the number of nodes that exist on a path from root to leaf in the tree...', ' // whtever the details of the implementation are, a tree with a single leaf node should return 1, and a tree', ' // with more than one lead node should return at least two (since it must have at least one internal node).', ' public int depth ();', ' ', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', '', 'interface IDoubleVector {', '', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '', '// this correponds to some geometric object in a metric space; the object is built out of', '// one or more points of type PointInMetricSpace', 'interface IObjectInMetricSpaceABCD <PointInMetricSpace extends IPointInMetricSpace<PointInMetricSpace>> {', ' ', ' // get the maximum distance from some point on the shape to a particular point in the metric space', ' double maxDistanceTo (PointInMetricSpace checkMe);', ' ', ' // return some arbitrary point on the interior of the geometric object', ' PointInMetricSpace getPointInInterior ();', '}', '', '', '// this interface corresponds to a point in some metric space', 'interface IPointInMetricSpace <PointInMetricSpace> {', ' ', ' // get the distance to another point', ' // ', ' // for this to work in an M-Tree, distances should be "metric" and', ' // obey the triangle inequality', ' double getDistance (PointInMetricSpace toMe);', '}', '', '// this is the basic node type in the structure', 'interface IMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> {', ' ', ' // insert a new key/data pair into the structure. The return value is a new MTreeNode if there was', ' // a split in response to the insertion, or a null if there was no split', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd);', ' ', ' // find all of the key/data pairs in the structure that fall within a particular query sphere', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query); ', ' ', ' // find the set of items closest to the given query point', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ);', ' ', ' // returns a sphere that totally encompasses everything in the node and its subtree', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', ' ', ' // returns the depth', ' public int depth ();', '}', '', '// this is a point in a particular metric space', 'class PointABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the point', ' private PointInMetricSpace me;', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return me; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return checkMe.getDistance (me); ', ' }', ' ', ' // contruct a point', ' public PointABCD (PointInMetricSpace useMe) {', ' me = useMe; ', ' }', '}', '', 'class PQueueABCD <PointInMetricSpace, DataType> {', ' ', ' // this is an object in the queue', ' private class Wrapper {', ' DataWrapper <PointInMetricSpace, DataType> myData;', ' double distance;', ' }', ' ', ' // this is the actual queue', ' ArrayList <Wrapper> myList;', ' ', ' // this is the largest distance value currently in the queue', ' double large;', ' ', ' // this is the max number of objects', ' int maxCount;', ' ', ' // create a priority queue with the speced number of slots', ' PQueueABCD (int maxCountIn) {', ' maxCount = maxCountIn;', ' myList = new ArrayList <Wrapper> ();', ' large = 9e99;', ' }', ' ', ' // get the largest distance in the queue', ' double getDist () {', ' return large;', ' }', ' ', ' // add a new object to the queue... the insertion is ignored if the distance value', ' // exceeds the largest that is in the queue and the queue is already full', ' void insert (PointInMetricSpace key, DataType data, double distance) {', ' ', ' // if we are full, remove the one with the largest distance', ' if (myList.size () == maxCount && distance < large) {', ' ', ' int badIndex = 0;', ' double maxDist = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > maxDist) {', ' maxDist = myList.get (i).distance;', ' badIndex = i;', ' }', ' }', ' ', ' myList.remove (badIndex);', ' }', ' ', ' // see if there is room', ' if (myList.size () < maxCount) {', ' ', ' // add it ', ' Wrapper newOne = new Wrapper ();', ' newOne.myData = new DataWrapper <PointInMetricSpace, DataType> (key, data);', ' newOne.distance = distance;', ' myList.add (newOne); ', ' }', ' ', ' // if we are full, reset the max distance', ' if (myList.size () == maxCount) {', ' large = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > large) {', ' large = myList.get (i).distance;', ' }', ' }', ' }', ' ', ' }', ' ', ' // extracts the contents of the queue', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> done () {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' for (int i = 0; i < myList.size (); i++) {', ' returnVal.add (myList.get (i).myData); ', ' }', ' ', ' return returnVal;', ' }', ' ', '}', '', '// this is a sphere in a particular metric space', 'class SphereABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the center of the sphere and its radius', ' private PointInMetricSpace center;', ' private double radius;', ' ', ' // build a sphere out of its center and its radius', ' public SphereABCD (PointInMetricSpace centerIn, double radiusIn) {', ' center = centerIn;', ' radius = radiusIn;', ' }', ' ', ' // increase the size of the sphere so it contains the object swallowMe', ' public void swallow (IObjectInMetricSpaceABCD <PointInMetricSpace> swallowMe) {', ' ', ' // see if we need to increase the radius to swallow this guy', ' double dist = swallowMe.maxDistanceTo (center);', ' if (dist > radius)', ' radius = dist;', ' }', ' ', ' // check to see if a sphere intersects another sphere', ' public boolean intersects (SphereABCD <PointInMetricSpace> me) {', ' return (me.center.getDistance (center) <= me.radius + radius);', ' }', ' ', ' // check to see if the sphere contains a point', ' public boolean contains (PointInMetricSpace checkMe) {', ' return (checkMe.getDistance (center) <= radius);', ' }', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return center; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return radius + checkMe.getDistance (center); ', ' }', '}', '', '', '', 'class OneDimPoint implements IPointInMetricSpace <OneDimPoint> {', ' ', ' // this is the actual double', ' Double value;', ' ', ' // construct this out of a double value', ' public OneDimPoint (double makeFromMe) {', ' value = new Double (makeFromMe);', ' }', ' ', ' // get the distance to another point', ' public double getDistance (OneDimPoint toMe) {', ' if (value > toMe.value)', ' return value - toMe.value;', ' else', ' return toMe.value - value;', ' }', ' ', '}', '', 'class MultiDimPoint implements IPointInMetricSpace <MultiDimPoint> {', ' ', ' // this is the point in a multidimensional space', ' IDoubleVector me;', ' ', ' // make this out of an IDoubleVector', ' public MultiDimPoint (IDoubleVector useMe) {', ' me = useMe;', ' }', ' ', ' // get the Euclidean distance to another point', ' public double getDistance (MultiDimPoint toMe) {', ' double distance = 0.0;', ' try {', ' for (int i = 0; i < me.getLength (); i++) {', ' double diff = me.getItem (i) - toMe.me.getItem (i);', ' diff *= diff;', ' distance += diff;', ' }', ' } catch (OutOfBoundsException e) {', ' throw new IndexOutOfBoundsException ("Can\'t compare two MultiDimPoint objects with different dimensionality!"); ', ' }', ' return Math.sqrt(distance);', ' }', ' ', '}', '// this is a leaf node', 'class LeafMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements ', ' IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myData;', ' ', ' // contructor that takes a data list and builds a node out of it', ' private LeafMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myDataIn) {', ' myData = myDataIn; ', ' }', ' ', ' // constructor that creates an empty node', ' public LeafMTreeNodeABCD () {', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> (); ', ' }', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // just add in the new data', ' myData.add (new PointABCD <PointInMetricSpace> (keyToAdd), dataToAdd);', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> newOne = myData.splitInTwo ();', ' LeafMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' myQ.insert (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData (), ', ' query.getDistance (myData.get (i).getKey ().getPointInInterior ()));', ' }', ' }', ' }', ' ', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' returnVal.add (new DataWrapper <PointInMetricSpace, DataType> (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData ()));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return 1; ', ' }', '', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', '// this silly little class is just a wrapper for a key, data pair', 'class DataWrapper <Key, Data> {', ' ', ' Key key;', ' Data data;', ' ', ' public DataWrapper (Key keyIn, Data dataIn) {', ' key = keyIn;', ' data = dataIn;', ' }', ' ', ' public Key getKey () {', ' return key;', ' }', ' ', ' public Data getData () {', ' return data;', ' }', '}', '', '', '// this is an internal node', 'class InternalMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType>', ' implements IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> myData;', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' // this constructs a new internal node that holds precisely the two nodes that are passed in', ' public InternalMTreeNodeABCD (IMTreeNodeABCD <PointInMetricSpace, DataType> refOne,', ' IMTreeNodeABCD <PointInMetricSpace, DataType> refTwo) {', ' ', ' // create a necw list and add the two guys in', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> ();', ' myData.add (refOne.getBoundingSphere (), refOne);', ' myData.add (refTwo.getBoundingSphere (), refTwo);', ' }', ' ', ' // this constructs a new node that holds the list of data that we were passed in', ' public InternalMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> useMe) {', ' myData = useMe; ', ' }', ' ', ' // from the interface', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // find the best child; this is the one we are closest to', ' double bestDist = 9e99;', ' int bestIndex = 0;', ' for (int i = 0; i < myData.size (); i++) {', ' ', ' double newDist = myData.get (i).getKey ().getPointInInterior ().getDistance (keyToAdd);', ' if (newDist < bestDist) {', ' bestDist = newDist;', ' bestIndex = i;', ' }', ' }', ' ', ' // do the recursive insert', ' IMTreeNodeABCD <PointInMetricSpace, DataType> newRef = myData.get (bestIndex).getData ().insert (keyToAdd, dataToAdd);', ' ', ' // if we got something back, then there was a split, so add the new node into our list', ' if (newRef != null) {', ' myData.add (newRef.getBoundingSphere (), newRef);', ' }', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> newOne = myData.splitInTwo ();', ' InternalMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.intersects (myData.get (i).getKey ())) {', ' myData.get (i).getData ().findKClosest (query, myQ);', ' }', ' }', ' }', ' ', ' // from the interface', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.intersects (myData.get (i).getKey ())) {', ' returnVal.addAll (myData.get (i).getData ().find (query));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return myData.get (0).getData ().depth () + 1; ', ' }', ' ', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', 'abstract class AMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> implements IMetricDataListABCD <PointInMetricSpace,KeyType, DataType> {', '', ' // this is the data that is actually stored in the list', ' private ArrayList <DataWrapper <KeyType, DataType>> myData;', ' ', ' // this is the sphere that bounds everything in the list', ' private SphereABCD <PointInMetricSpace> myBoundingSphere;', ' ', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myBoundingSphere; ', ' }', ' ', ' public int size () {', ' if (myData != null)', ' return myData.size (); ', ' else', ' return 0;', ' }', ' ', ' public DataWrapper <KeyType, DataType> get (int pos) {', ' return myData.get (pos);', ' }', ' ', ' public void replaceKey (int pos, KeyType keyToAdd) {', ' DataWrapper <KeyType, DataType> temp = myData.remove (pos);', ' DataWrapper <KeyType, DataType> newOne = new DataWrapper <KeyType, DataType> (keyToAdd, temp.getData ());', ' myData.add (pos, newOne);', ' }', ' ', ' public void add (KeyType keyToAdd, DataType dataToAdd) {', ' ', ' // if this is the first add, then set everyone up', ' if (myData == null) {', ' PointInMetricSpace myCentroid = keyToAdd.getPointInInterior ();', ' myBoundingSphere = new SphereABCD <PointInMetricSpace> (myCentroid, keyToAdd.maxDistanceTo (myCentroid));', ' myData = new ArrayList <DataWrapper <KeyType, DataType>> ();', ' ', ' // otherwise, extend the sphere if needed', ' } else {', ' myBoundingSphere.swallow (keyToAdd);', ' }', ' ', ' // add the data', ' myData.add (new DataWrapper <KeyType, DataType> (keyToAdd, dataToAdd));', ' }', ' ', ' // we want to potentially allow many implementations of the splitting lalgorithm', ' abstract public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // this is here so the actual splitting algorithn can access the list and change the sphere', ' protected ArrayList <DataWrapper <KeyType, DataType>> getList () {', ' return myData;', ' }', ' ', ' // this is here so the splitting algorithm can modify the list and the sphere', ' protected void replaceGuts (AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> withMe) {', ' myData = withMe.myData;', ' myBoundingSphere = withMe.myBoundingSphere;', ' }', ' ', '}', '', '// this is a particular implementation of the metric data list that uses a simple quadratic clustering', '// algorithm to perform a list split. It picks two "seeds" (the most distant objects) and then repeatedly', '// adds to the two new lists by choosing the objects closest to the seeds', 'class ChrisMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> extends AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> {', '', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo () {', ' ', ' // first, we need to find the two most distant points in the list', ' ArrayList <DataWrapper <KeyType, DataType>> myData = getList ();', ' int bestI = 0, bestJ = 0;', ' double maxDist = -1.0;', ' for (int i = 0; i < myData.size (); i++) {', ' for (int j = i + 1; j < myData.size (); j++) {', ' ', ' // get the two keys', ' DataWrapper <KeyType, DataType> pointOne = myData.get (i);', ' DataWrapper <KeyType, DataType> pointTwo = myData.get (j);', ' ', ' // find the difference between them', ' double curDist = pointOne.getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', '', ' // see if it is the biggest', ' if (curDist > maxDist) {', ' maxDist = curDist;', ' bestI = i;', ' bestJ = j;', ' }', ' }', ' }', ' ', ' // now, we have the best two points; those are seeds for the clustering', ' DataWrapper <KeyType, DataType> pointOne = myData.remove (bestI);', ' DataWrapper <KeyType, DataType> pointTwo = myData.remove (bestJ - 1);', ' ', ' // these are the two new lists', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listOne = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listTwo = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' ', ' // put the two seeds in', ' listOne.add (pointOne.getKey (), pointOne.getData ());', ' listTwo.add (pointTwo.getKey (), pointTwo.getData ());', ' ', ' // and add everyone else in', ' while (myData.size () != 0) {', ' ', ' // find the one closest to the first seed', ' int bestIndex = 0;', ' double bestDist = 9e99;', ' ', ' // loop thru all of the candidate data objects', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listOne.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' ', ' // break if no more data', ' if (myData.size () == 0)', ' break;', ' ', ' // loop thru all of the candidate data objects', ' bestDist = 9e99;', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listTwo.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' }', ' ', ' // now we replace our own guts with the first list', ' replaceGuts (listOne);', ' ', ' // and return the other list', ' return listTwo;', ' }', '}', '', 'interface IMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> {', ' ', ' // add a new pair to the list', ' public void add (KeyType keyToAdd, DataType dataToAdd);', ' ', ' // replace a key at the indicated position', ' public void replaceKey (int pos, KeyType keyToAdd);', ' ', ' // get the key, data pair that resides at a particular position', ' public DataWrapper <KeyType, DataType> get (int pos);', ' ', ' // return the number of items in the list', ' public int size ();', ' ', ' // split the list in two, using some clutering algorithm', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // get a sphere that totally bounds all of the objects in the list', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class MTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public MTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {'] | [' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }'] | [' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class SCMTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public SCMTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', '', 'public class MTreeTester extends TestCase {', ' ', ' // compare two lists of strings to see if the contents are the same', ' private boolean compareStringSets (ArrayList <String> setOne, ArrayList <String> setTwo) {', ' ', ' // sort the sets and make sure they are the same', ' boolean returnVal = true;', ' if (setOne.size () == setTwo.size ()) {', ' Collections.sort (setOne);', ' Collections.sort (setTwo);', ' for (int i = 0; i < setOne.size (); i++) {', ' if (!setOne.get (i).equals (setTwo.get (i))) {', ' returnVal = false;', ' break; ', ' }', ' }', ' } else {', ' returnVal = false;', ' }', ' ', ' // print out the result', ' System.out.println ("**** Expected:");', ' for (int i = 0; i < setOne.size (); i++) {', ' System.out.format (setOne.get (i) + " ");', ' }', ' System.out.println ("\\n**** Got:");', ' for (int i = 0; i < setTwo.size (); i++) {', ' System.out.format (setTwo.get (i) + " ");', ' }', ' System.out.println ("");', ' ', ' return returnVal;', ' }', ' ', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST SIMPLE ONE DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testOneDimRangeQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.find (query, expectedQuerySize / 2);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.find (query, expectedQuerySize / 2);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (numPoints);', ' result1 = myTree.find (query, expectedQuerySize);', ' result2 = hisTree.find (query, expectedQuerySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // like the last one, but runs a top k', ' private void testOneDimTopKQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (167);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.findKClosest (query, querySize);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (0);', ' result1 = myTree.findKClosest (query, querySize);', ' result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST MULTI-DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimRangeQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' double dist1 = 0;', ' double dist2 = 0;', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' dist1 = Math.sqrt (numDims) * expectedQuerySize / 2.0;', ' dist2 = Math.sqrt (numDims) * expectedQuerySize;', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' // do a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, (int) expectedQuerySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = myTree.findKClosest (query2, (int) expectedQuerySize);', ' ', ' // find the distance to the furthest point in both cases', ' for (int i = 0; i < (int) expectedQuerySize; i++) {', ' double newDist = result1.get (i).getKey ().getDistance (query1);', ' if (newDist > dist1)', ' dist1 = newDist;', ' newDist = result2.get (i).getKey ().getDistance (query2);', ' if (newDist > dist2)', ' dist2 = newDist;', ' }', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.find (query1, dist1);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.find (query1, dist1);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.find (query2, dist2);', ' result2 = hisTree.find (query2, dist2);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimTopKQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, querySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.findKClosest (query1, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.findKClosest (query2, querySize);', ' result2 = hisTree.findKClosest (query2, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' ', ' /**', ' * "TIER 1" TESTS', ' * NONE OF THESE REQUIRE ANY SPLITS', ' */', ' public void testEasy1() {', ' testOneDimRangeQuery (true, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy2() {', ' testOneDimRangeQuery (false, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy3() {', ' testOneDimRangeQuery (true, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy4() {', ' testOneDimRangeQuery (false, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy5() {', ' testMultiDimRangeQuery (true, 1, 5, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy6() {', ' testMultiDimRangeQuery (false, 1, 10, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy7() {', ' testMultiDimRangeQuery (true, 1, 5, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy8() {', ' testMultiDimRangeQuery (false, 1, 15, 10000, 10000, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 2" TESTS', ' * NONE OF THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testMod1() {', ' testOneDimRangeQuery (true, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod2() {', ' testOneDimRangeQuery (false, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod3() {', ' testOneDimRangeQuery (true, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod4() {', ' testOneDimRangeQuery (false, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod5() {', ' testMultiDimRangeQuery (true, 2, 5, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod6() {', ' testMultiDimRangeQuery (false, 2, 10, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod7() {', ' testMultiDimRangeQuery (true, 2, 5, 10000, 100, 1000, 10);', ' }', ' ', ' public void testMod8() {', ' testMultiDimRangeQuery (false, 2, 15, 10000, 100, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 3" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testHard1() {', ' testOneDimRangeQuery (true, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard2() {', ' testOneDimRangeQuery (false, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard3() {', ' testOneDimRangeQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard4() {', ' testOneDimRangeQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard5() {', ' testMultiDimRangeQuery (true, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard6() {', ' testMultiDimRangeQuery (false, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard7() {', ' testMultiDimRangeQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard8() {', ' testMultiDimRangeQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', ' ', ' /**', ' * "TIER 4" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE AND THEY TEST THE TOPK FUNCTIONALITY', ' */', ' ', ' public void testTopK1() {', ' testOneDimTopKQuery (true, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK2() {', ' testOneDimTopKQuery (false, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK3() {', ' testOneDimTopKQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK4() {', ' testOneDimTopKQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK5() {', ' testMultiDimTopKQuery (true, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK6() {', ' testMultiDimTopKQuery (false, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK7() {', ' testMultiDimTopKQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK8() {', ' testMultiDimTopKQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', '}'] | [{'reason_category': 'If Body', 'usage_line': 744}, {'reason_category': 'If Body', 'usage_line': 745}] | Class 'InternalMTreeNodeABCD' used at line 744 is defined at line 450 and has a Long-Range dependency.
Global_Variable 'root' used at line 744 is defined at line 727 and has a Medium-Range dependency.
Variable 'res' used at line 744 is defined at line 740 and has a Short-Range dependency. | {'If Body': 2} | {'Class Long-Range': 1, 'Global_Variable Medium-Range': 1, 'Variable Short-Range': 1} |
infilling_java | MTreeTester | 750 | 751 | ['import junit.framework.TestCase;', 'import java.util.ArrayList;', 'import java.util.Random;', 'import java.util.Collections;', '', '// this is a map from a set of keys of type PointInMetricSpace to a', '// set of data of type DataType', 'interface IMTree <Key extends IPointInMetricSpace <Key>, Data> {', ' ', ' // insert a new key/data pair into the map', ' void insert (Key keyToAdd, Data dataToAdd);', ' ', ' // find all of the key/data pairs in the map that fall within a', ' // particular distance of query point if no results are found, then', ' // an empty array is returned (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> find (Key query, double distance);', ' ', ' // find the k closest key/data pairs in the map to a particular', ' // query point ', ' //', ' // if the number of points in the map is less than k, then the', ' // returned list will have less than k pairs in it', ' //', ' // if the number of points is zero, then an empty array is returned', ' // (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> findKClosest (Key query, int k);', ' ', ' // returns the number of nodes that exist on a path from root to leaf in the tree...', ' // whtever the details of the implementation are, a tree with a single leaf node should return 1, and a tree', ' // with more than one lead node should return at least two (since it must have at least one internal node).', ' public int depth ();', ' ', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', '', 'interface IDoubleVector {', '', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '', '// this correponds to some geometric object in a metric space; the object is built out of', '// one or more points of type PointInMetricSpace', 'interface IObjectInMetricSpaceABCD <PointInMetricSpace extends IPointInMetricSpace<PointInMetricSpace>> {', ' ', ' // get the maximum distance from some point on the shape to a particular point in the metric space', ' double maxDistanceTo (PointInMetricSpace checkMe);', ' ', ' // return some arbitrary point on the interior of the geometric object', ' PointInMetricSpace getPointInInterior ();', '}', '', '', '// this interface corresponds to a point in some metric space', 'interface IPointInMetricSpace <PointInMetricSpace> {', ' ', ' // get the distance to another point', ' // ', ' // for this to work in an M-Tree, distances should be "metric" and', ' // obey the triangle inequality', ' double getDistance (PointInMetricSpace toMe);', '}', '', '// this is the basic node type in the structure', 'interface IMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> {', ' ', ' // insert a new key/data pair into the structure. The return value is a new MTreeNode if there was', ' // a split in response to the insertion, or a null if there was no split', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd);', ' ', ' // find all of the key/data pairs in the structure that fall within a particular query sphere', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query); ', ' ', ' // find the set of items closest to the given query point', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ);', ' ', ' // returns a sphere that totally encompasses everything in the node and its subtree', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', ' ', ' // returns the depth', ' public int depth ();', '}', '', '// this is a point in a particular metric space', 'class PointABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the point', ' private PointInMetricSpace me;', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return me; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return checkMe.getDistance (me); ', ' }', ' ', ' // contruct a point', ' public PointABCD (PointInMetricSpace useMe) {', ' me = useMe; ', ' }', '}', '', 'class PQueueABCD <PointInMetricSpace, DataType> {', ' ', ' // this is an object in the queue', ' private class Wrapper {', ' DataWrapper <PointInMetricSpace, DataType> myData;', ' double distance;', ' }', ' ', ' // this is the actual queue', ' ArrayList <Wrapper> myList;', ' ', ' // this is the largest distance value currently in the queue', ' double large;', ' ', ' // this is the max number of objects', ' int maxCount;', ' ', ' // create a priority queue with the speced number of slots', ' PQueueABCD (int maxCountIn) {', ' maxCount = maxCountIn;', ' myList = new ArrayList <Wrapper> ();', ' large = 9e99;', ' }', ' ', ' // get the largest distance in the queue', ' double getDist () {', ' return large;', ' }', ' ', ' // add a new object to the queue... the insertion is ignored if the distance value', ' // exceeds the largest that is in the queue and the queue is already full', ' void insert (PointInMetricSpace key, DataType data, double distance) {', ' ', ' // if we are full, remove the one with the largest distance', ' if (myList.size () == maxCount && distance < large) {', ' ', ' int badIndex = 0;', ' double maxDist = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > maxDist) {', ' maxDist = myList.get (i).distance;', ' badIndex = i;', ' }', ' }', ' ', ' myList.remove (badIndex);', ' }', ' ', ' // see if there is room', ' if (myList.size () < maxCount) {', ' ', ' // add it ', ' Wrapper newOne = new Wrapper ();', ' newOne.myData = new DataWrapper <PointInMetricSpace, DataType> (key, data);', ' newOne.distance = distance;', ' myList.add (newOne); ', ' }', ' ', ' // if we are full, reset the max distance', ' if (myList.size () == maxCount) {', ' large = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > large) {', ' large = myList.get (i).distance;', ' }', ' }', ' }', ' ', ' }', ' ', ' // extracts the contents of the queue', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> done () {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' for (int i = 0; i < myList.size (); i++) {', ' returnVal.add (myList.get (i).myData); ', ' }', ' ', ' return returnVal;', ' }', ' ', '}', '', '// this is a sphere in a particular metric space', 'class SphereABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the center of the sphere and its radius', ' private PointInMetricSpace center;', ' private double radius;', ' ', ' // build a sphere out of its center and its radius', ' public SphereABCD (PointInMetricSpace centerIn, double radiusIn) {', ' center = centerIn;', ' radius = radiusIn;', ' }', ' ', ' // increase the size of the sphere so it contains the object swallowMe', ' public void swallow (IObjectInMetricSpaceABCD <PointInMetricSpace> swallowMe) {', ' ', ' // see if we need to increase the radius to swallow this guy', ' double dist = swallowMe.maxDistanceTo (center);', ' if (dist > radius)', ' radius = dist;', ' }', ' ', ' // check to see if a sphere intersects another sphere', ' public boolean intersects (SphereABCD <PointInMetricSpace> me) {', ' return (me.center.getDistance (center) <= me.radius + radius);', ' }', ' ', ' // check to see if the sphere contains a point', ' public boolean contains (PointInMetricSpace checkMe) {', ' return (checkMe.getDistance (center) <= radius);', ' }', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return center; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return radius + checkMe.getDistance (center); ', ' }', '}', '', '', '', 'class OneDimPoint implements IPointInMetricSpace <OneDimPoint> {', ' ', ' // this is the actual double', ' Double value;', ' ', ' // construct this out of a double value', ' public OneDimPoint (double makeFromMe) {', ' value = new Double (makeFromMe);', ' }', ' ', ' // get the distance to another point', ' public double getDistance (OneDimPoint toMe) {', ' if (value > toMe.value)', ' return value - toMe.value;', ' else', ' return toMe.value - value;', ' }', ' ', '}', '', 'class MultiDimPoint implements IPointInMetricSpace <MultiDimPoint> {', ' ', ' // this is the point in a multidimensional space', ' IDoubleVector me;', ' ', ' // make this out of an IDoubleVector', ' public MultiDimPoint (IDoubleVector useMe) {', ' me = useMe;', ' }', ' ', ' // get the Euclidean distance to another point', ' public double getDistance (MultiDimPoint toMe) {', ' double distance = 0.0;', ' try {', ' for (int i = 0; i < me.getLength (); i++) {', ' double diff = me.getItem (i) - toMe.me.getItem (i);', ' diff *= diff;', ' distance += diff;', ' }', ' } catch (OutOfBoundsException e) {', ' throw new IndexOutOfBoundsException ("Can\'t compare two MultiDimPoint objects with different dimensionality!"); ', ' }', ' return Math.sqrt(distance);', ' }', ' ', '}', '// this is a leaf node', 'class LeafMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements ', ' IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myData;', ' ', ' // contructor that takes a data list and builds a node out of it', ' private LeafMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myDataIn) {', ' myData = myDataIn; ', ' }', ' ', ' // constructor that creates an empty node', ' public LeafMTreeNodeABCD () {', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> (); ', ' }', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // just add in the new data', ' myData.add (new PointABCD <PointInMetricSpace> (keyToAdd), dataToAdd);', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> newOne = myData.splitInTwo ();', ' LeafMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' myQ.insert (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData (), ', ' query.getDistance (myData.get (i).getKey ().getPointInInterior ()));', ' }', ' }', ' }', ' ', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' returnVal.add (new DataWrapper <PointInMetricSpace, DataType> (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData ()));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return 1; ', ' }', '', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', '// this silly little class is just a wrapper for a key, data pair', 'class DataWrapper <Key, Data> {', ' ', ' Key key;', ' Data data;', ' ', ' public DataWrapper (Key keyIn, Data dataIn) {', ' key = keyIn;', ' data = dataIn;', ' }', ' ', ' public Key getKey () {', ' return key;', ' }', ' ', ' public Data getData () {', ' return data;', ' }', '}', '', '', '// this is an internal node', 'class InternalMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType>', ' implements IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> myData;', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' // this constructs a new internal node that holds precisely the two nodes that are passed in', ' public InternalMTreeNodeABCD (IMTreeNodeABCD <PointInMetricSpace, DataType> refOne,', ' IMTreeNodeABCD <PointInMetricSpace, DataType> refTwo) {', ' ', ' // create a necw list and add the two guys in', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> ();', ' myData.add (refOne.getBoundingSphere (), refOne);', ' myData.add (refTwo.getBoundingSphere (), refTwo);', ' }', ' ', ' // this constructs a new node that holds the list of data that we were passed in', ' public InternalMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> useMe) {', ' myData = useMe; ', ' }', ' ', ' // from the interface', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // find the best child; this is the one we are closest to', ' double bestDist = 9e99;', ' int bestIndex = 0;', ' for (int i = 0; i < myData.size (); i++) {', ' ', ' double newDist = myData.get (i).getKey ().getPointInInterior ().getDistance (keyToAdd);', ' if (newDist < bestDist) {', ' bestDist = newDist;', ' bestIndex = i;', ' }', ' }', ' ', ' // do the recursive insert', ' IMTreeNodeABCD <PointInMetricSpace, DataType> newRef = myData.get (bestIndex).getData ().insert (keyToAdd, dataToAdd);', ' ', ' // if we got something back, then there was a split, so add the new node into our list', ' if (newRef != null) {', ' myData.add (newRef.getBoundingSphere (), newRef);', ' }', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> newOne = myData.splitInTwo ();', ' InternalMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.intersects (myData.get (i).getKey ())) {', ' myData.get (i).getData ().findKClosest (query, myQ);', ' }', ' }', ' }', ' ', ' // from the interface', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.intersects (myData.get (i).getKey ())) {', ' returnVal.addAll (myData.get (i).getData ().find (query));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return myData.get (0).getData ().depth () + 1; ', ' }', ' ', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', 'abstract class AMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> implements IMetricDataListABCD <PointInMetricSpace,KeyType, DataType> {', '', ' // this is the data that is actually stored in the list', ' private ArrayList <DataWrapper <KeyType, DataType>> myData;', ' ', ' // this is the sphere that bounds everything in the list', ' private SphereABCD <PointInMetricSpace> myBoundingSphere;', ' ', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myBoundingSphere; ', ' }', ' ', ' public int size () {', ' if (myData != null)', ' return myData.size (); ', ' else', ' return 0;', ' }', ' ', ' public DataWrapper <KeyType, DataType> get (int pos) {', ' return myData.get (pos);', ' }', ' ', ' public void replaceKey (int pos, KeyType keyToAdd) {', ' DataWrapper <KeyType, DataType> temp = myData.remove (pos);', ' DataWrapper <KeyType, DataType> newOne = new DataWrapper <KeyType, DataType> (keyToAdd, temp.getData ());', ' myData.add (pos, newOne);', ' }', ' ', ' public void add (KeyType keyToAdd, DataType dataToAdd) {', ' ', ' // if this is the first add, then set everyone up', ' if (myData == null) {', ' PointInMetricSpace myCentroid = keyToAdd.getPointInInterior ();', ' myBoundingSphere = new SphereABCD <PointInMetricSpace> (myCentroid, keyToAdd.maxDistanceTo (myCentroid));', ' myData = new ArrayList <DataWrapper <KeyType, DataType>> ();', ' ', ' // otherwise, extend the sphere if needed', ' } else {', ' myBoundingSphere.swallow (keyToAdd);', ' }', ' ', ' // add the data', ' myData.add (new DataWrapper <KeyType, DataType> (keyToAdd, dataToAdd));', ' }', ' ', ' // we want to potentially allow many implementations of the splitting lalgorithm', ' abstract public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // this is here so the actual splitting algorithn can access the list and change the sphere', ' protected ArrayList <DataWrapper <KeyType, DataType>> getList () {', ' return myData;', ' }', ' ', ' // this is here so the splitting algorithm can modify the list and the sphere', ' protected void replaceGuts (AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> withMe) {', ' myData = withMe.myData;', ' myBoundingSphere = withMe.myBoundingSphere;', ' }', ' ', '}', '', '// this is a particular implementation of the metric data list that uses a simple quadratic clustering', '// algorithm to perform a list split. It picks two "seeds" (the most distant objects) and then repeatedly', '// adds to the two new lists by choosing the objects closest to the seeds', 'class ChrisMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> extends AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> {', '', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo () {', ' ', ' // first, we need to find the two most distant points in the list', ' ArrayList <DataWrapper <KeyType, DataType>> myData = getList ();', ' int bestI = 0, bestJ = 0;', ' double maxDist = -1.0;', ' for (int i = 0; i < myData.size (); i++) {', ' for (int j = i + 1; j < myData.size (); j++) {', ' ', ' // get the two keys', ' DataWrapper <KeyType, DataType> pointOne = myData.get (i);', ' DataWrapper <KeyType, DataType> pointTwo = myData.get (j);', ' ', ' // find the difference between them', ' double curDist = pointOne.getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', '', ' // see if it is the biggest', ' if (curDist > maxDist) {', ' maxDist = curDist;', ' bestI = i;', ' bestJ = j;', ' }', ' }', ' }', ' ', ' // now, we have the best two points; those are seeds for the clustering', ' DataWrapper <KeyType, DataType> pointOne = myData.remove (bestI);', ' DataWrapper <KeyType, DataType> pointTwo = myData.remove (bestJ - 1);', ' ', ' // these are the two new lists', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listOne = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listTwo = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' ', ' // put the two seeds in', ' listOne.add (pointOne.getKey (), pointOne.getData ());', ' listTwo.add (pointTwo.getKey (), pointTwo.getData ());', ' ', ' // and add everyone else in', ' while (myData.size () != 0) {', ' ', ' // find the one closest to the first seed', ' int bestIndex = 0;', ' double bestDist = 9e99;', ' ', ' // loop thru all of the candidate data objects', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listOne.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' ', ' // break if no more data', ' if (myData.size () == 0)', ' break;', ' ', ' // loop thru all of the candidate data objects', ' bestDist = 9e99;', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listTwo.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' }', ' ', ' // now we replace our own guts with the first list', ' replaceGuts (listOne);', ' ', ' // and return the other list', ' return listTwo;', ' }', '}', '', 'interface IMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> {', ' ', ' // add a new pair to the list', ' public void add (KeyType keyToAdd, DataType dataToAdd);', ' ', ' // replace a key at the indicated position', ' public void replaceKey (int pos, KeyType keyToAdd);', ' ', ' // get the key, data pair that resides at a particular position', ' public DataWrapper <KeyType, DataType> get (int pos);', ' ', ' // return the number of items in the list', ' public int size ();', ' ', ' // split the list in two, using some clutering algorithm', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // get a sphere that totally bounds all of the objects in the list', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class MTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public MTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {'] | [' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }'] | [' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class SCMTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public SCMTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', '', 'public class MTreeTester extends TestCase {', ' ', ' // compare two lists of strings to see if the contents are the same', ' private boolean compareStringSets (ArrayList <String> setOne, ArrayList <String> setTwo) {', ' ', ' // sort the sets and make sure they are the same', ' boolean returnVal = true;', ' if (setOne.size () == setTwo.size ()) {', ' Collections.sort (setOne);', ' Collections.sort (setTwo);', ' for (int i = 0; i < setOne.size (); i++) {', ' if (!setOne.get (i).equals (setTwo.get (i))) {', ' returnVal = false;', ' break; ', ' }', ' }', ' } else {', ' returnVal = false;', ' }', ' ', ' // print out the result', ' System.out.println ("**** Expected:");', ' for (int i = 0; i < setOne.size (); i++) {', ' System.out.format (setOne.get (i) + " ");', ' }', ' System.out.println ("\\n**** Got:");', ' for (int i = 0; i < setTwo.size (); i++) {', ' System.out.format (setTwo.get (i) + " ");', ' }', ' System.out.println ("");', ' ', ' return returnVal;', ' }', ' ', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST SIMPLE ONE DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testOneDimRangeQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.find (query, expectedQuerySize / 2);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.find (query, expectedQuerySize / 2);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (numPoints);', ' result1 = myTree.find (query, expectedQuerySize);', ' result2 = hisTree.find (query, expectedQuerySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // like the last one, but runs a top k', ' private void testOneDimTopKQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (167);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.findKClosest (query, querySize);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (0);', ' result1 = myTree.findKClosest (query, querySize);', ' result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST MULTI-DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimRangeQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' double dist1 = 0;', ' double dist2 = 0;', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' dist1 = Math.sqrt (numDims) * expectedQuerySize / 2.0;', ' dist2 = Math.sqrt (numDims) * expectedQuerySize;', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' // do a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, (int) expectedQuerySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = myTree.findKClosest (query2, (int) expectedQuerySize);', ' ', ' // find the distance to the furthest point in both cases', ' for (int i = 0; i < (int) expectedQuerySize; i++) {', ' double newDist = result1.get (i).getKey ().getDistance (query1);', ' if (newDist > dist1)', ' dist1 = newDist;', ' newDist = result2.get (i).getKey ().getDistance (query2);', ' if (newDist > dist2)', ' dist2 = newDist;', ' }', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.find (query1, dist1);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.find (query1, dist1);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.find (query2, dist2);', ' result2 = hisTree.find (query2, dist2);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimTopKQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, querySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.findKClosest (query1, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.findKClosest (query2, querySize);', ' result2 = hisTree.findKClosest (query2, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' ', ' /**', ' * "TIER 1" TESTS', ' * NONE OF THESE REQUIRE ANY SPLITS', ' */', ' public void testEasy1() {', ' testOneDimRangeQuery (true, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy2() {', ' testOneDimRangeQuery (false, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy3() {', ' testOneDimRangeQuery (true, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy4() {', ' testOneDimRangeQuery (false, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy5() {', ' testMultiDimRangeQuery (true, 1, 5, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy6() {', ' testMultiDimRangeQuery (false, 1, 10, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy7() {', ' testMultiDimRangeQuery (true, 1, 5, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy8() {', ' testMultiDimRangeQuery (false, 1, 15, 10000, 10000, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 2" TESTS', ' * NONE OF THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testMod1() {', ' testOneDimRangeQuery (true, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod2() {', ' testOneDimRangeQuery (false, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod3() {', ' testOneDimRangeQuery (true, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod4() {', ' testOneDimRangeQuery (false, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod5() {', ' testMultiDimRangeQuery (true, 2, 5, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod6() {', ' testMultiDimRangeQuery (false, 2, 10, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod7() {', ' testMultiDimRangeQuery (true, 2, 5, 10000, 100, 1000, 10);', ' }', ' ', ' public void testMod8() {', ' testMultiDimRangeQuery (false, 2, 15, 10000, 100, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 3" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testHard1() {', ' testOneDimRangeQuery (true, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard2() {', ' testOneDimRangeQuery (false, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard3() {', ' testOneDimRangeQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard4() {', ' testOneDimRangeQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard5() {', ' testMultiDimRangeQuery (true, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard6() {', ' testMultiDimRangeQuery (false, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard7() {', ' testMultiDimRangeQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard8() {', ' testMultiDimRangeQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', ' ', ' /**', ' * "TIER 4" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE AND THEY TEST THE TOPK FUNCTIONALITY', ' */', ' ', ' public void testTopK1() {', ' testOneDimTopKQuery (true, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK2() {', ' testOneDimTopKQuery (false, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK3() {', ' testOneDimTopKQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK4() {', ' testOneDimTopKQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK5() {', ' testMultiDimTopKQuery (true, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK6() {', ' testMultiDimTopKQuery (false, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK7() {', ' testMultiDimTopKQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK8() {', ' testMultiDimTopKQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', '}'] | [] | Global_Variable 'root' used at line 750 is defined at line 727 and has a Medium-Range dependency.
Class 'SphereABCD' used at line 750 is defined at line 261 and has a Long-Range dependency.
Variable 'query' used at line 750 is defined at line 749 and has a Short-Range dependency.
Variable 'distance' used at line 750 is defined at line 749 and has a Short-Range dependency. | {} | {'Global_Variable Medium-Range': 1, 'Class Long-Range': 1, 'Variable Short-Range': 2} |
infilling_java | MTreeTester | 755 | 758 | ['import junit.framework.TestCase;', 'import java.util.ArrayList;', 'import java.util.Random;', 'import java.util.Collections;', '', '// this is a map from a set of keys of type PointInMetricSpace to a', '// set of data of type DataType', 'interface IMTree <Key extends IPointInMetricSpace <Key>, Data> {', ' ', ' // insert a new key/data pair into the map', ' void insert (Key keyToAdd, Data dataToAdd);', ' ', ' // find all of the key/data pairs in the map that fall within a', ' // particular distance of query point if no results are found, then', ' // an empty array is returned (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> find (Key query, double distance);', ' ', ' // find the k closest key/data pairs in the map to a particular', ' // query point ', ' //', ' // if the number of points in the map is less than k, then the', ' // returned list will have less than k pairs in it', ' //', ' // if the number of points is zero, then an empty array is returned', ' // (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> findKClosest (Key query, int k);', ' ', ' // returns the number of nodes that exist on a path from root to leaf in the tree...', ' // whtever the details of the implementation are, a tree with a single leaf node should return 1, and a tree', ' // with more than one lead node should return at least two (since it must have at least one internal node).', ' public int depth ();', ' ', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', '', 'interface IDoubleVector {', '', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '', '// this correponds to some geometric object in a metric space; the object is built out of', '// one or more points of type PointInMetricSpace', 'interface IObjectInMetricSpaceABCD <PointInMetricSpace extends IPointInMetricSpace<PointInMetricSpace>> {', ' ', ' // get the maximum distance from some point on the shape to a particular point in the metric space', ' double maxDistanceTo (PointInMetricSpace checkMe);', ' ', ' // return some arbitrary point on the interior of the geometric object', ' PointInMetricSpace getPointInInterior ();', '}', '', '', '// this interface corresponds to a point in some metric space', 'interface IPointInMetricSpace <PointInMetricSpace> {', ' ', ' // get the distance to another point', ' // ', ' // for this to work in an M-Tree, distances should be "metric" and', ' // obey the triangle inequality', ' double getDistance (PointInMetricSpace toMe);', '}', '', '// this is the basic node type in the structure', 'interface IMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> {', ' ', ' // insert a new key/data pair into the structure. The return value is a new MTreeNode if there was', ' // a split in response to the insertion, or a null if there was no split', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd);', ' ', ' // find all of the key/data pairs in the structure that fall within a particular query sphere', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query); ', ' ', ' // find the set of items closest to the given query point', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ);', ' ', ' // returns a sphere that totally encompasses everything in the node and its subtree', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', ' ', ' // returns the depth', ' public int depth ();', '}', '', '// this is a point in a particular metric space', 'class PointABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the point', ' private PointInMetricSpace me;', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return me; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return checkMe.getDistance (me); ', ' }', ' ', ' // contruct a point', ' public PointABCD (PointInMetricSpace useMe) {', ' me = useMe; ', ' }', '}', '', 'class PQueueABCD <PointInMetricSpace, DataType> {', ' ', ' // this is an object in the queue', ' private class Wrapper {', ' DataWrapper <PointInMetricSpace, DataType> myData;', ' double distance;', ' }', ' ', ' // this is the actual queue', ' ArrayList <Wrapper> myList;', ' ', ' // this is the largest distance value currently in the queue', ' double large;', ' ', ' // this is the max number of objects', ' int maxCount;', ' ', ' // create a priority queue with the speced number of slots', ' PQueueABCD (int maxCountIn) {', ' maxCount = maxCountIn;', ' myList = new ArrayList <Wrapper> ();', ' large = 9e99;', ' }', ' ', ' // get the largest distance in the queue', ' double getDist () {', ' return large;', ' }', ' ', ' // add a new object to the queue... the insertion is ignored if the distance value', ' // exceeds the largest that is in the queue and the queue is already full', ' void insert (PointInMetricSpace key, DataType data, double distance) {', ' ', ' // if we are full, remove the one with the largest distance', ' if (myList.size () == maxCount && distance < large) {', ' ', ' int badIndex = 0;', ' double maxDist = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > maxDist) {', ' maxDist = myList.get (i).distance;', ' badIndex = i;', ' }', ' }', ' ', ' myList.remove (badIndex);', ' }', ' ', ' // see if there is room', ' if (myList.size () < maxCount) {', ' ', ' // add it ', ' Wrapper newOne = new Wrapper ();', ' newOne.myData = new DataWrapper <PointInMetricSpace, DataType> (key, data);', ' newOne.distance = distance;', ' myList.add (newOne); ', ' }', ' ', ' // if we are full, reset the max distance', ' if (myList.size () == maxCount) {', ' large = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > large) {', ' large = myList.get (i).distance;', ' }', ' }', ' }', ' ', ' }', ' ', ' // extracts the contents of the queue', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> done () {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' for (int i = 0; i < myList.size (); i++) {', ' returnVal.add (myList.get (i).myData); ', ' }', ' ', ' return returnVal;', ' }', ' ', '}', '', '// this is a sphere in a particular metric space', 'class SphereABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the center of the sphere and its radius', ' private PointInMetricSpace center;', ' private double radius;', ' ', ' // build a sphere out of its center and its radius', ' public SphereABCD (PointInMetricSpace centerIn, double radiusIn) {', ' center = centerIn;', ' radius = radiusIn;', ' }', ' ', ' // increase the size of the sphere so it contains the object swallowMe', ' public void swallow (IObjectInMetricSpaceABCD <PointInMetricSpace> swallowMe) {', ' ', ' // see if we need to increase the radius to swallow this guy', ' double dist = swallowMe.maxDistanceTo (center);', ' if (dist > radius)', ' radius = dist;', ' }', ' ', ' // check to see if a sphere intersects another sphere', ' public boolean intersects (SphereABCD <PointInMetricSpace> me) {', ' return (me.center.getDistance (center) <= me.radius + radius);', ' }', ' ', ' // check to see if the sphere contains a point', ' public boolean contains (PointInMetricSpace checkMe) {', ' return (checkMe.getDistance (center) <= radius);', ' }', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return center; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return radius + checkMe.getDistance (center); ', ' }', '}', '', '', '', 'class OneDimPoint implements IPointInMetricSpace <OneDimPoint> {', ' ', ' // this is the actual double', ' Double value;', ' ', ' // construct this out of a double value', ' public OneDimPoint (double makeFromMe) {', ' value = new Double (makeFromMe);', ' }', ' ', ' // get the distance to another point', ' public double getDistance (OneDimPoint toMe) {', ' if (value > toMe.value)', ' return value - toMe.value;', ' else', ' return toMe.value - value;', ' }', ' ', '}', '', 'class MultiDimPoint implements IPointInMetricSpace <MultiDimPoint> {', ' ', ' // this is the point in a multidimensional space', ' IDoubleVector me;', ' ', ' // make this out of an IDoubleVector', ' public MultiDimPoint (IDoubleVector useMe) {', ' me = useMe;', ' }', ' ', ' // get the Euclidean distance to another point', ' public double getDistance (MultiDimPoint toMe) {', ' double distance = 0.0;', ' try {', ' for (int i = 0; i < me.getLength (); i++) {', ' double diff = me.getItem (i) - toMe.me.getItem (i);', ' diff *= diff;', ' distance += diff;', ' }', ' } catch (OutOfBoundsException e) {', ' throw new IndexOutOfBoundsException ("Can\'t compare two MultiDimPoint objects with different dimensionality!"); ', ' }', ' return Math.sqrt(distance);', ' }', ' ', '}', '// this is a leaf node', 'class LeafMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements ', ' IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myData;', ' ', ' // contructor that takes a data list and builds a node out of it', ' private LeafMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myDataIn) {', ' myData = myDataIn; ', ' }', ' ', ' // constructor that creates an empty node', ' public LeafMTreeNodeABCD () {', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> (); ', ' }', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // just add in the new data', ' myData.add (new PointABCD <PointInMetricSpace> (keyToAdd), dataToAdd);', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> newOne = myData.splitInTwo ();', ' LeafMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' myQ.insert (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData (), ', ' query.getDistance (myData.get (i).getKey ().getPointInInterior ()));', ' }', ' }', ' }', ' ', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' returnVal.add (new DataWrapper <PointInMetricSpace, DataType> (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData ()));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return 1; ', ' }', '', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', '// this silly little class is just a wrapper for a key, data pair', 'class DataWrapper <Key, Data> {', ' ', ' Key key;', ' Data data;', ' ', ' public DataWrapper (Key keyIn, Data dataIn) {', ' key = keyIn;', ' data = dataIn;', ' }', ' ', ' public Key getKey () {', ' return key;', ' }', ' ', ' public Data getData () {', ' return data;', ' }', '}', '', '', '// this is an internal node', 'class InternalMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType>', ' implements IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> myData;', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' // this constructs a new internal node that holds precisely the two nodes that are passed in', ' public InternalMTreeNodeABCD (IMTreeNodeABCD <PointInMetricSpace, DataType> refOne,', ' IMTreeNodeABCD <PointInMetricSpace, DataType> refTwo) {', ' ', ' // create a necw list and add the two guys in', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> ();', ' myData.add (refOne.getBoundingSphere (), refOne);', ' myData.add (refTwo.getBoundingSphere (), refTwo);', ' }', ' ', ' // this constructs a new node that holds the list of data that we were passed in', ' public InternalMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> useMe) {', ' myData = useMe; ', ' }', ' ', ' // from the interface', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // find the best child; this is the one we are closest to', ' double bestDist = 9e99;', ' int bestIndex = 0;', ' for (int i = 0; i < myData.size (); i++) {', ' ', ' double newDist = myData.get (i).getKey ().getPointInInterior ().getDistance (keyToAdd);', ' if (newDist < bestDist) {', ' bestDist = newDist;', ' bestIndex = i;', ' }', ' }', ' ', ' // do the recursive insert', ' IMTreeNodeABCD <PointInMetricSpace, DataType> newRef = myData.get (bestIndex).getData ().insert (keyToAdd, dataToAdd);', ' ', ' // if we got something back, then there was a split, so add the new node into our list', ' if (newRef != null) {', ' myData.add (newRef.getBoundingSphere (), newRef);', ' }', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> newOne = myData.splitInTwo ();', ' InternalMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.intersects (myData.get (i).getKey ())) {', ' myData.get (i).getData ().findKClosest (query, myQ);', ' }', ' }', ' }', ' ', ' // from the interface', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.intersects (myData.get (i).getKey ())) {', ' returnVal.addAll (myData.get (i).getData ().find (query));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return myData.get (0).getData ().depth () + 1; ', ' }', ' ', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', 'abstract class AMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> implements IMetricDataListABCD <PointInMetricSpace,KeyType, DataType> {', '', ' // this is the data that is actually stored in the list', ' private ArrayList <DataWrapper <KeyType, DataType>> myData;', ' ', ' // this is the sphere that bounds everything in the list', ' private SphereABCD <PointInMetricSpace> myBoundingSphere;', ' ', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myBoundingSphere; ', ' }', ' ', ' public int size () {', ' if (myData != null)', ' return myData.size (); ', ' else', ' return 0;', ' }', ' ', ' public DataWrapper <KeyType, DataType> get (int pos) {', ' return myData.get (pos);', ' }', ' ', ' public void replaceKey (int pos, KeyType keyToAdd) {', ' DataWrapper <KeyType, DataType> temp = myData.remove (pos);', ' DataWrapper <KeyType, DataType> newOne = new DataWrapper <KeyType, DataType> (keyToAdd, temp.getData ());', ' myData.add (pos, newOne);', ' }', ' ', ' public void add (KeyType keyToAdd, DataType dataToAdd) {', ' ', ' // if this is the first add, then set everyone up', ' if (myData == null) {', ' PointInMetricSpace myCentroid = keyToAdd.getPointInInterior ();', ' myBoundingSphere = new SphereABCD <PointInMetricSpace> (myCentroid, keyToAdd.maxDistanceTo (myCentroid));', ' myData = new ArrayList <DataWrapper <KeyType, DataType>> ();', ' ', ' // otherwise, extend the sphere if needed', ' } else {', ' myBoundingSphere.swallow (keyToAdd);', ' }', ' ', ' // add the data', ' myData.add (new DataWrapper <KeyType, DataType> (keyToAdd, dataToAdd));', ' }', ' ', ' // we want to potentially allow many implementations of the splitting lalgorithm', ' abstract public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // this is here so the actual splitting algorithn can access the list and change the sphere', ' protected ArrayList <DataWrapper <KeyType, DataType>> getList () {', ' return myData;', ' }', ' ', ' // this is here so the splitting algorithm can modify the list and the sphere', ' protected void replaceGuts (AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> withMe) {', ' myData = withMe.myData;', ' myBoundingSphere = withMe.myBoundingSphere;', ' }', ' ', '}', '', '// this is a particular implementation of the metric data list that uses a simple quadratic clustering', '// algorithm to perform a list split. It picks two "seeds" (the most distant objects) and then repeatedly', '// adds to the two new lists by choosing the objects closest to the seeds', 'class ChrisMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> extends AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> {', '', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo () {', ' ', ' // first, we need to find the two most distant points in the list', ' ArrayList <DataWrapper <KeyType, DataType>> myData = getList ();', ' int bestI = 0, bestJ = 0;', ' double maxDist = -1.0;', ' for (int i = 0; i < myData.size (); i++) {', ' for (int j = i + 1; j < myData.size (); j++) {', ' ', ' // get the two keys', ' DataWrapper <KeyType, DataType> pointOne = myData.get (i);', ' DataWrapper <KeyType, DataType> pointTwo = myData.get (j);', ' ', ' // find the difference between them', ' double curDist = pointOne.getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', '', ' // see if it is the biggest', ' if (curDist > maxDist) {', ' maxDist = curDist;', ' bestI = i;', ' bestJ = j;', ' }', ' }', ' }', ' ', ' // now, we have the best two points; those are seeds for the clustering', ' DataWrapper <KeyType, DataType> pointOne = myData.remove (bestI);', ' DataWrapper <KeyType, DataType> pointTwo = myData.remove (bestJ - 1);', ' ', ' // these are the two new lists', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listOne = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listTwo = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' ', ' // put the two seeds in', ' listOne.add (pointOne.getKey (), pointOne.getData ());', ' listTwo.add (pointTwo.getKey (), pointTwo.getData ());', ' ', ' // and add everyone else in', ' while (myData.size () != 0) {', ' ', ' // find the one closest to the first seed', ' int bestIndex = 0;', ' double bestDist = 9e99;', ' ', ' // loop thru all of the candidate data objects', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listOne.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' ', ' // break if no more data', ' if (myData.size () == 0)', ' break;', ' ', ' // loop thru all of the candidate data objects', ' bestDist = 9e99;', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listTwo.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' }', ' ', ' // now we replace our own guts with the first list', ' replaceGuts (listOne);', ' ', ' // and return the other list', ' return listTwo;', ' }', '}', '', 'interface IMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> {', ' ', ' // add a new pair to the list', ' public void add (KeyType keyToAdd, DataType dataToAdd);', ' ', ' // replace a key at the indicated position', ' public void replaceKey (int pos, KeyType keyToAdd);', ' ', ' // get the key, data pair that resides at a particular position', ' public DataWrapper <KeyType, DataType> get (int pos);', ' ', ' // return the number of items in the list', ' public int size ();', ' ', ' // split the list in two, using some clutering algorithm', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // get a sphere that totally bounds all of the objects in the list', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class MTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public MTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {'] | [' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }'] | [' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class SCMTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public SCMTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', '', 'public class MTreeTester extends TestCase {', ' ', ' // compare two lists of strings to see if the contents are the same', ' private boolean compareStringSets (ArrayList <String> setOne, ArrayList <String> setTwo) {', ' ', ' // sort the sets and make sure they are the same', ' boolean returnVal = true;', ' if (setOne.size () == setTwo.size ()) {', ' Collections.sort (setOne);', ' Collections.sort (setTwo);', ' for (int i = 0; i < setOne.size (); i++) {', ' if (!setOne.get (i).equals (setTwo.get (i))) {', ' returnVal = false;', ' break; ', ' }', ' }', ' } else {', ' returnVal = false;', ' }', ' ', ' // print out the result', ' System.out.println ("**** Expected:");', ' for (int i = 0; i < setOne.size (); i++) {', ' System.out.format (setOne.get (i) + " ");', ' }', ' System.out.println ("\\n**** Got:");', ' for (int i = 0; i < setTwo.size (); i++) {', ' System.out.format (setTwo.get (i) + " ");', ' }', ' System.out.println ("");', ' ', ' return returnVal;', ' }', ' ', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST SIMPLE ONE DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testOneDimRangeQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.find (query, expectedQuerySize / 2);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.find (query, expectedQuerySize / 2);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (numPoints);', ' result1 = myTree.find (query, expectedQuerySize);', ' result2 = hisTree.find (query, expectedQuerySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // like the last one, but runs a top k', ' private void testOneDimTopKQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (167);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.findKClosest (query, querySize);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (0);', ' result1 = myTree.findKClosest (query, querySize);', ' result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST MULTI-DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimRangeQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' double dist1 = 0;', ' double dist2 = 0;', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' dist1 = Math.sqrt (numDims) * expectedQuerySize / 2.0;', ' dist2 = Math.sqrt (numDims) * expectedQuerySize;', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' // do a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, (int) expectedQuerySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = myTree.findKClosest (query2, (int) expectedQuerySize);', ' ', ' // find the distance to the furthest point in both cases', ' for (int i = 0; i < (int) expectedQuerySize; i++) {', ' double newDist = result1.get (i).getKey ().getDistance (query1);', ' if (newDist > dist1)', ' dist1 = newDist;', ' newDist = result2.get (i).getKey ().getDistance (query2);', ' if (newDist > dist2)', ' dist2 = newDist;', ' }', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.find (query1, dist1);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.find (query1, dist1);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.find (query2, dist2);', ' result2 = hisTree.find (query2, dist2);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimTopKQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, querySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.findKClosest (query1, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.findKClosest (query2, querySize);', ' result2 = hisTree.findKClosest (query2, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' ', ' /**', ' * "TIER 1" TESTS', ' * NONE OF THESE REQUIRE ANY SPLITS', ' */', ' public void testEasy1() {', ' testOneDimRangeQuery (true, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy2() {', ' testOneDimRangeQuery (false, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy3() {', ' testOneDimRangeQuery (true, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy4() {', ' testOneDimRangeQuery (false, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy5() {', ' testMultiDimRangeQuery (true, 1, 5, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy6() {', ' testMultiDimRangeQuery (false, 1, 10, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy7() {', ' testMultiDimRangeQuery (true, 1, 5, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy8() {', ' testMultiDimRangeQuery (false, 1, 15, 10000, 10000, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 2" TESTS', ' * NONE OF THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testMod1() {', ' testOneDimRangeQuery (true, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod2() {', ' testOneDimRangeQuery (false, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod3() {', ' testOneDimRangeQuery (true, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod4() {', ' testOneDimRangeQuery (false, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod5() {', ' testMultiDimRangeQuery (true, 2, 5, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod6() {', ' testMultiDimRangeQuery (false, 2, 10, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod7() {', ' testMultiDimRangeQuery (true, 2, 5, 10000, 100, 1000, 10);', ' }', ' ', ' public void testMod8() {', ' testMultiDimRangeQuery (false, 2, 15, 10000, 100, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 3" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testHard1() {', ' testOneDimRangeQuery (true, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard2() {', ' testOneDimRangeQuery (false, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard3() {', ' testOneDimRangeQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard4() {', ' testOneDimRangeQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard5() {', ' testMultiDimRangeQuery (true, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard6() {', ' testMultiDimRangeQuery (false, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard7() {', ' testMultiDimRangeQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard8() {', ' testMultiDimRangeQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', ' ', ' /**', ' * "TIER 4" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE AND THEY TEST THE TOPK FUNCTIONALITY', ' */', ' ', ' public void testTopK1() {', ' testOneDimTopKQuery (true, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK2() {', ' testOneDimTopKQuery (false, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK3() {', ' testOneDimTopKQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK4() {', ' testOneDimTopKQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK5() {', ' testMultiDimTopKQuery (true, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK6() {', ' testMultiDimTopKQuery (false, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK7() {', ' testMultiDimTopKQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK8() {', ' testMultiDimTopKQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', '}'] | [] | Class 'PQueueABCD' used at line 755 is defined at line 177 and has a Long-Range dependency.
Variable 'k' used at line 755 is defined at line 754 and has a Short-Range dependency.
Global_Variable 'root' used at line 756 is defined at line 727 and has a Medium-Range dependency.
Variable 'query' used at line 756 is defined at line 754 and has a Short-Range dependency.
Variable 'myQ' used at line 756 is defined at line 755 and has a Short-Range dependency.
Function 'PQueueABCD.done' used at line 757 is defined at line 248 and has a Long-Range dependency. | {} | {'Class Long-Range': 1, 'Variable Short-Range': 3, 'Global_Variable Medium-Range': 1, 'Function Long-Range': 1} |
infilling_java | MTreeTester | 762 | 763 | ['import junit.framework.TestCase;', 'import java.util.ArrayList;', 'import java.util.Random;', 'import java.util.Collections;', '', '// this is a map from a set of keys of type PointInMetricSpace to a', '// set of data of type DataType', 'interface IMTree <Key extends IPointInMetricSpace <Key>, Data> {', ' ', ' // insert a new key/data pair into the map', ' void insert (Key keyToAdd, Data dataToAdd);', ' ', ' // find all of the key/data pairs in the map that fall within a', ' // particular distance of query point if no results are found, then', ' // an empty array is returned (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> find (Key query, double distance);', ' ', ' // find the k closest key/data pairs in the map to a particular', ' // query point ', ' //', ' // if the number of points in the map is less than k, then the', ' // returned list will have less than k pairs in it', ' //', ' // if the number of points is zero, then an empty array is returned', ' // (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> findKClosest (Key query, int k);', ' ', ' // returns the number of nodes that exist on a path from root to leaf in the tree...', ' // whtever the details of the implementation are, a tree with a single leaf node should return 1, and a tree', ' // with more than one lead node should return at least two (since it must have at least one internal node).', ' public int depth ();', ' ', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', '', 'interface IDoubleVector {', '', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '', '// this correponds to some geometric object in a metric space; the object is built out of', '// one or more points of type PointInMetricSpace', 'interface IObjectInMetricSpaceABCD <PointInMetricSpace extends IPointInMetricSpace<PointInMetricSpace>> {', ' ', ' // get the maximum distance from some point on the shape to a particular point in the metric space', ' double maxDistanceTo (PointInMetricSpace checkMe);', ' ', ' // return some arbitrary point on the interior of the geometric object', ' PointInMetricSpace getPointInInterior ();', '}', '', '', '// this interface corresponds to a point in some metric space', 'interface IPointInMetricSpace <PointInMetricSpace> {', ' ', ' // get the distance to another point', ' // ', ' // for this to work in an M-Tree, distances should be "metric" and', ' // obey the triangle inequality', ' double getDistance (PointInMetricSpace toMe);', '}', '', '// this is the basic node type in the structure', 'interface IMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> {', ' ', ' // insert a new key/data pair into the structure. The return value is a new MTreeNode if there was', ' // a split in response to the insertion, or a null if there was no split', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd);', ' ', ' // find all of the key/data pairs in the structure that fall within a particular query sphere', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query); ', ' ', ' // find the set of items closest to the given query point', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ);', ' ', ' // returns a sphere that totally encompasses everything in the node and its subtree', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', ' ', ' // returns the depth', ' public int depth ();', '}', '', '// this is a point in a particular metric space', 'class PointABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the point', ' private PointInMetricSpace me;', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return me; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return checkMe.getDistance (me); ', ' }', ' ', ' // contruct a point', ' public PointABCD (PointInMetricSpace useMe) {', ' me = useMe; ', ' }', '}', '', 'class PQueueABCD <PointInMetricSpace, DataType> {', ' ', ' // this is an object in the queue', ' private class Wrapper {', ' DataWrapper <PointInMetricSpace, DataType> myData;', ' double distance;', ' }', ' ', ' // this is the actual queue', ' ArrayList <Wrapper> myList;', ' ', ' // this is the largest distance value currently in the queue', ' double large;', ' ', ' // this is the max number of objects', ' int maxCount;', ' ', ' // create a priority queue with the speced number of slots', ' PQueueABCD (int maxCountIn) {', ' maxCount = maxCountIn;', ' myList = new ArrayList <Wrapper> ();', ' large = 9e99;', ' }', ' ', ' // get the largest distance in the queue', ' double getDist () {', ' return large;', ' }', ' ', ' // add a new object to the queue... the insertion is ignored if the distance value', ' // exceeds the largest that is in the queue and the queue is already full', ' void insert (PointInMetricSpace key, DataType data, double distance) {', ' ', ' // if we are full, remove the one with the largest distance', ' if (myList.size () == maxCount && distance < large) {', ' ', ' int badIndex = 0;', ' double maxDist = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > maxDist) {', ' maxDist = myList.get (i).distance;', ' badIndex = i;', ' }', ' }', ' ', ' myList.remove (badIndex);', ' }', ' ', ' // see if there is room', ' if (myList.size () < maxCount) {', ' ', ' // add it ', ' Wrapper newOne = new Wrapper ();', ' newOne.myData = new DataWrapper <PointInMetricSpace, DataType> (key, data);', ' newOne.distance = distance;', ' myList.add (newOne); ', ' }', ' ', ' // if we are full, reset the max distance', ' if (myList.size () == maxCount) {', ' large = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > large) {', ' large = myList.get (i).distance;', ' }', ' }', ' }', ' ', ' }', ' ', ' // extracts the contents of the queue', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> done () {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' for (int i = 0; i < myList.size (); i++) {', ' returnVal.add (myList.get (i).myData); ', ' }', ' ', ' return returnVal;', ' }', ' ', '}', '', '// this is a sphere in a particular metric space', 'class SphereABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the center of the sphere and its radius', ' private PointInMetricSpace center;', ' private double radius;', ' ', ' // build a sphere out of its center and its radius', ' public SphereABCD (PointInMetricSpace centerIn, double radiusIn) {', ' center = centerIn;', ' radius = radiusIn;', ' }', ' ', ' // increase the size of the sphere so it contains the object swallowMe', ' public void swallow (IObjectInMetricSpaceABCD <PointInMetricSpace> swallowMe) {', ' ', ' // see if we need to increase the radius to swallow this guy', ' double dist = swallowMe.maxDistanceTo (center);', ' if (dist > radius)', ' radius = dist;', ' }', ' ', ' // check to see if a sphere intersects another sphere', ' public boolean intersects (SphereABCD <PointInMetricSpace> me) {', ' return (me.center.getDistance (center) <= me.radius + radius);', ' }', ' ', ' // check to see if the sphere contains a point', ' public boolean contains (PointInMetricSpace checkMe) {', ' return (checkMe.getDistance (center) <= radius);', ' }', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return center; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return radius + checkMe.getDistance (center); ', ' }', '}', '', '', '', 'class OneDimPoint implements IPointInMetricSpace <OneDimPoint> {', ' ', ' // this is the actual double', ' Double value;', ' ', ' // construct this out of a double value', ' public OneDimPoint (double makeFromMe) {', ' value = new Double (makeFromMe);', ' }', ' ', ' // get the distance to another point', ' public double getDistance (OneDimPoint toMe) {', ' if (value > toMe.value)', ' return value - toMe.value;', ' else', ' return toMe.value - value;', ' }', ' ', '}', '', 'class MultiDimPoint implements IPointInMetricSpace <MultiDimPoint> {', ' ', ' // this is the point in a multidimensional space', ' IDoubleVector me;', ' ', ' // make this out of an IDoubleVector', ' public MultiDimPoint (IDoubleVector useMe) {', ' me = useMe;', ' }', ' ', ' // get the Euclidean distance to another point', ' public double getDistance (MultiDimPoint toMe) {', ' double distance = 0.0;', ' try {', ' for (int i = 0; i < me.getLength (); i++) {', ' double diff = me.getItem (i) - toMe.me.getItem (i);', ' diff *= diff;', ' distance += diff;', ' }', ' } catch (OutOfBoundsException e) {', ' throw new IndexOutOfBoundsException ("Can\'t compare two MultiDimPoint objects with different dimensionality!"); ', ' }', ' return Math.sqrt(distance);', ' }', ' ', '}', '// this is a leaf node', 'class LeafMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements ', ' IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myData;', ' ', ' // contructor that takes a data list and builds a node out of it', ' private LeafMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myDataIn) {', ' myData = myDataIn; ', ' }', ' ', ' // constructor that creates an empty node', ' public LeafMTreeNodeABCD () {', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> (); ', ' }', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // just add in the new data', ' myData.add (new PointABCD <PointInMetricSpace> (keyToAdd), dataToAdd);', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> newOne = myData.splitInTwo ();', ' LeafMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' myQ.insert (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData (), ', ' query.getDistance (myData.get (i).getKey ().getPointInInterior ()));', ' }', ' }', ' }', ' ', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' returnVal.add (new DataWrapper <PointInMetricSpace, DataType> (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData ()));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return 1; ', ' }', '', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', '// this silly little class is just a wrapper for a key, data pair', 'class DataWrapper <Key, Data> {', ' ', ' Key key;', ' Data data;', ' ', ' public DataWrapper (Key keyIn, Data dataIn) {', ' key = keyIn;', ' data = dataIn;', ' }', ' ', ' public Key getKey () {', ' return key;', ' }', ' ', ' public Data getData () {', ' return data;', ' }', '}', '', '', '// this is an internal node', 'class InternalMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType>', ' implements IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> myData;', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' // this constructs a new internal node that holds precisely the two nodes that are passed in', ' public InternalMTreeNodeABCD (IMTreeNodeABCD <PointInMetricSpace, DataType> refOne,', ' IMTreeNodeABCD <PointInMetricSpace, DataType> refTwo) {', ' ', ' // create a necw list and add the two guys in', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> ();', ' myData.add (refOne.getBoundingSphere (), refOne);', ' myData.add (refTwo.getBoundingSphere (), refTwo);', ' }', ' ', ' // this constructs a new node that holds the list of data that we were passed in', ' public InternalMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> useMe) {', ' myData = useMe; ', ' }', ' ', ' // from the interface', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // find the best child; this is the one we are closest to', ' double bestDist = 9e99;', ' int bestIndex = 0;', ' for (int i = 0; i < myData.size (); i++) {', ' ', ' double newDist = myData.get (i).getKey ().getPointInInterior ().getDistance (keyToAdd);', ' if (newDist < bestDist) {', ' bestDist = newDist;', ' bestIndex = i;', ' }', ' }', ' ', ' // do the recursive insert', ' IMTreeNodeABCD <PointInMetricSpace, DataType> newRef = myData.get (bestIndex).getData ().insert (keyToAdd, dataToAdd);', ' ', ' // if we got something back, then there was a split, so add the new node into our list', ' if (newRef != null) {', ' myData.add (newRef.getBoundingSphere (), newRef);', ' }', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> newOne = myData.splitInTwo ();', ' InternalMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.intersects (myData.get (i).getKey ())) {', ' myData.get (i).getData ().findKClosest (query, myQ);', ' }', ' }', ' }', ' ', ' // from the interface', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.intersects (myData.get (i).getKey ())) {', ' returnVal.addAll (myData.get (i).getData ().find (query));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return myData.get (0).getData ().depth () + 1; ', ' }', ' ', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', 'abstract class AMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> implements IMetricDataListABCD <PointInMetricSpace,KeyType, DataType> {', '', ' // this is the data that is actually stored in the list', ' private ArrayList <DataWrapper <KeyType, DataType>> myData;', ' ', ' // this is the sphere that bounds everything in the list', ' private SphereABCD <PointInMetricSpace> myBoundingSphere;', ' ', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myBoundingSphere; ', ' }', ' ', ' public int size () {', ' if (myData != null)', ' return myData.size (); ', ' else', ' return 0;', ' }', ' ', ' public DataWrapper <KeyType, DataType> get (int pos) {', ' return myData.get (pos);', ' }', ' ', ' public void replaceKey (int pos, KeyType keyToAdd) {', ' DataWrapper <KeyType, DataType> temp = myData.remove (pos);', ' DataWrapper <KeyType, DataType> newOne = new DataWrapper <KeyType, DataType> (keyToAdd, temp.getData ());', ' myData.add (pos, newOne);', ' }', ' ', ' public void add (KeyType keyToAdd, DataType dataToAdd) {', ' ', ' // if this is the first add, then set everyone up', ' if (myData == null) {', ' PointInMetricSpace myCentroid = keyToAdd.getPointInInterior ();', ' myBoundingSphere = new SphereABCD <PointInMetricSpace> (myCentroid, keyToAdd.maxDistanceTo (myCentroid));', ' myData = new ArrayList <DataWrapper <KeyType, DataType>> ();', ' ', ' // otherwise, extend the sphere if needed', ' } else {', ' myBoundingSphere.swallow (keyToAdd);', ' }', ' ', ' // add the data', ' myData.add (new DataWrapper <KeyType, DataType> (keyToAdd, dataToAdd));', ' }', ' ', ' // we want to potentially allow many implementations of the splitting lalgorithm', ' abstract public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // this is here so the actual splitting algorithn can access the list and change the sphere', ' protected ArrayList <DataWrapper <KeyType, DataType>> getList () {', ' return myData;', ' }', ' ', ' // this is here so the splitting algorithm can modify the list and the sphere', ' protected void replaceGuts (AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> withMe) {', ' myData = withMe.myData;', ' myBoundingSphere = withMe.myBoundingSphere;', ' }', ' ', '}', '', '// this is a particular implementation of the metric data list that uses a simple quadratic clustering', '// algorithm to perform a list split. It picks two "seeds" (the most distant objects) and then repeatedly', '// adds to the two new lists by choosing the objects closest to the seeds', 'class ChrisMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> extends AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> {', '', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo () {', ' ', ' // first, we need to find the two most distant points in the list', ' ArrayList <DataWrapper <KeyType, DataType>> myData = getList ();', ' int bestI = 0, bestJ = 0;', ' double maxDist = -1.0;', ' for (int i = 0; i < myData.size (); i++) {', ' for (int j = i + 1; j < myData.size (); j++) {', ' ', ' // get the two keys', ' DataWrapper <KeyType, DataType> pointOne = myData.get (i);', ' DataWrapper <KeyType, DataType> pointTwo = myData.get (j);', ' ', ' // find the difference between them', ' double curDist = pointOne.getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', '', ' // see if it is the biggest', ' if (curDist > maxDist) {', ' maxDist = curDist;', ' bestI = i;', ' bestJ = j;', ' }', ' }', ' }', ' ', ' // now, we have the best two points; those are seeds for the clustering', ' DataWrapper <KeyType, DataType> pointOne = myData.remove (bestI);', ' DataWrapper <KeyType, DataType> pointTwo = myData.remove (bestJ - 1);', ' ', ' // these are the two new lists', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listOne = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listTwo = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' ', ' // put the two seeds in', ' listOne.add (pointOne.getKey (), pointOne.getData ());', ' listTwo.add (pointTwo.getKey (), pointTwo.getData ());', ' ', ' // and add everyone else in', ' while (myData.size () != 0) {', ' ', ' // find the one closest to the first seed', ' int bestIndex = 0;', ' double bestDist = 9e99;', ' ', ' // loop thru all of the candidate data objects', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listOne.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' ', ' // break if no more data', ' if (myData.size () == 0)', ' break;', ' ', ' // loop thru all of the candidate data objects', ' bestDist = 9e99;', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listTwo.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' }', ' ', ' // now we replace our own guts with the first list', ' replaceGuts (listOne);', ' ', ' // and return the other list', ' return listTwo;', ' }', '}', '', 'interface IMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> {', ' ', ' // add a new pair to the list', ' public void add (KeyType keyToAdd, DataType dataToAdd);', ' ', ' // replace a key at the indicated position', ' public void replaceKey (int pos, KeyType keyToAdd);', ' ', ' // get the key, data pair that resides at a particular position', ' public DataWrapper <KeyType, DataType> get (int pos);', ' ', ' // return the number of items in the list', ' public int size ();', ' ', ' // split the list in two, using some clutering algorithm', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // get a sphere that totally bounds all of the objects in the list', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class MTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public MTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {'] | [' return root.depth (); ', ' }'] | ['}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class SCMTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public SCMTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', '', 'public class MTreeTester extends TestCase {', ' ', ' // compare two lists of strings to see if the contents are the same', ' private boolean compareStringSets (ArrayList <String> setOne, ArrayList <String> setTwo) {', ' ', ' // sort the sets and make sure they are the same', ' boolean returnVal = true;', ' if (setOne.size () == setTwo.size ()) {', ' Collections.sort (setOne);', ' Collections.sort (setTwo);', ' for (int i = 0; i < setOne.size (); i++) {', ' if (!setOne.get (i).equals (setTwo.get (i))) {', ' returnVal = false;', ' break; ', ' }', ' }', ' } else {', ' returnVal = false;', ' }', ' ', ' // print out the result', ' System.out.println ("**** Expected:");', ' for (int i = 0; i < setOne.size (); i++) {', ' System.out.format (setOne.get (i) + " ");', ' }', ' System.out.println ("\\n**** Got:");', ' for (int i = 0; i < setTwo.size (); i++) {', ' System.out.format (setTwo.get (i) + " ");', ' }', ' System.out.println ("");', ' ', ' return returnVal;', ' }', ' ', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST SIMPLE ONE DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testOneDimRangeQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.find (query, expectedQuerySize / 2);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.find (query, expectedQuerySize / 2);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (numPoints);', ' result1 = myTree.find (query, expectedQuerySize);', ' result2 = hisTree.find (query, expectedQuerySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // like the last one, but runs a top k', ' private void testOneDimTopKQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (167);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.findKClosest (query, querySize);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (0);', ' result1 = myTree.findKClosest (query, querySize);', ' result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST MULTI-DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimRangeQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' double dist1 = 0;', ' double dist2 = 0;', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' dist1 = Math.sqrt (numDims) * expectedQuerySize / 2.0;', ' dist2 = Math.sqrt (numDims) * expectedQuerySize;', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' // do a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, (int) expectedQuerySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = myTree.findKClosest (query2, (int) expectedQuerySize);', ' ', ' // find the distance to the furthest point in both cases', ' for (int i = 0; i < (int) expectedQuerySize; i++) {', ' double newDist = result1.get (i).getKey ().getDistance (query1);', ' if (newDist > dist1)', ' dist1 = newDist;', ' newDist = result2.get (i).getKey ().getDistance (query2);', ' if (newDist > dist2)', ' dist2 = newDist;', ' }', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.find (query1, dist1);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.find (query1, dist1);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.find (query2, dist2);', ' result2 = hisTree.find (query2, dist2);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimTopKQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, querySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.findKClosest (query1, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.findKClosest (query2, querySize);', ' result2 = hisTree.findKClosest (query2, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' ', ' /**', ' * "TIER 1" TESTS', ' * NONE OF THESE REQUIRE ANY SPLITS', ' */', ' public void testEasy1() {', ' testOneDimRangeQuery (true, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy2() {', ' testOneDimRangeQuery (false, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy3() {', ' testOneDimRangeQuery (true, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy4() {', ' testOneDimRangeQuery (false, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy5() {', ' testMultiDimRangeQuery (true, 1, 5, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy6() {', ' testMultiDimRangeQuery (false, 1, 10, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy7() {', ' testMultiDimRangeQuery (true, 1, 5, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy8() {', ' testMultiDimRangeQuery (false, 1, 15, 10000, 10000, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 2" TESTS', ' * NONE OF THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testMod1() {', ' testOneDimRangeQuery (true, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod2() {', ' testOneDimRangeQuery (false, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod3() {', ' testOneDimRangeQuery (true, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod4() {', ' testOneDimRangeQuery (false, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod5() {', ' testMultiDimRangeQuery (true, 2, 5, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod6() {', ' testMultiDimRangeQuery (false, 2, 10, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod7() {', ' testMultiDimRangeQuery (true, 2, 5, 10000, 100, 1000, 10);', ' }', ' ', ' public void testMod8() {', ' testMultiDimRangeQuery (false, 2, 15, 10000, 100, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 3" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testHard1() {', ' testOneDimRangeQuery (true, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard2() {', ' testOneDimRangeQuery (false, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard3() {', ' testOneDimRangeQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard4() {', ' testOneDimRangeQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard5() {', ' testMultiDimRangeQuery (true, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard6() {', ' testMultiDimRangeQuery (false, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard7() {', ' testMultiDimRangeQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard8() {', ' testMultiDimRangeQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', ' ', ' /**', ' * "TIER 4" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE AND THEY TEST THE TOPK FUNCTIONALITY', ' */', ' ', ' public void testTopK1() {', ' testOneDimTopKQuery (true, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK2() {', ' testOneDimTopKQuery (false, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK3() {', ' testOneDimTopKQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK4() {', ' testOneDimTopKQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK5() {', ' testMultiDimTopKQuery (true, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK6() {', ' testMultiDimTopKQuery (false, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK7() {', ' testMultiDimTopKQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK8() {', ' testMultiDimTopKQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', '}'] | [] | Global_Variable 'root' used at line 762 is defined at line 727 and has a Long-Range dependency. | {} | {'Global_Variable Long-Range': 1} |
infilling_java | MTreeTester | 774 | 777 | ['import junit.framework.TestCase;', 'import java.util.ArrayList;', 'import java.util.Random;', 'import java.util.Collections;', '', '// this is a map from a set of keys of type PointInMetricSpace to a', '// set of data of type DataType', 'interface IMTree <Key extends IPointInMetricSpace <Key>, Data> {', ' ', ' // insert a new key/data pair into the map', ' void insert (Key keyToAdd, Data dataToAdd);', ' ', ' // find all of the key/data pairs in the map that fall within a', ' // particular distance of query point if no results are found, then', ' // an empty array is returned (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> find (Key query, double distance);', ' ', ' // find the k closest key/data pairs in the map to a particular', ' // query point ', ' //', ' // if the number of points in the map is less than k, then the', ' // returned list will have less than k pairs in it', ' //', ' // if the number of points is zero, then an empty array is returned', ' // (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> findKClosest (Key query, int k);', ' ', ' // returns the number of nodes that exist on a path from root to leaf in the tree...', ' // whtever the details of the implementation are, a tree with a single leaf node should return 1, and a tree', ' // with more than one lead node should return at least two (since it must have at least one internal node).', ' public int depth ();', ' ', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', '', 'interface IDoubleVector {', '', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '', '// this correponds to some geometric object in a metric space; the object is built out of', '// one or more points of type PointInMetricSpace', 'interface IObjectInMetricSpaceABCD <PointInMetricSpace extends IPointInMetricSpace<PointInMetricSpace>> {', ' ', ' // get the maximum distance from some point on the shape to a particular point in the metric space', ' double maxDistanceTo (PointInMetricSpace checkMe);', ' ', ' // return some arbitrary point on the interior of the geometric object', ' PointInMetricSpace getPointInInterior ();', '}', '', '', '// this interface corresponds to a point in some metric space', 'interface IPointInMetricSpace <PointInMetricSpace> {', ' ', ' // get the distance to another point', ' // ', ' // for this to work in an M-Tree, distances should be "metric" and', ' // obey the triangle inequality', ' double getDistance (PointInMetricSpace toMe);', '}', '', '// this is the basic node type in the structure', 'interface IMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> {', ' ', ' // insert a new key/data pair into the structure. The return value is a new MTreeNode if there was', ' // a split in response to the insertion, or a null if there was no split', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd);', ' ', ' // find all of the key/data pairs in the structure that fall within a particular query sphere', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query); ', ' ', ' // find the set of items closest to the given query point', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ);', ' ', ' // returns a sphere that totally encompasses everything in the node and its subtree', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', ' ', ' // returns the depth', ' public int depth ();', '}', '', '// this is a point in a particular metric space', 'class PointABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the point', ' private PointInMetricSpace me;', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return me; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return checkMe.getDistance (me); ', ' }', ' ', ' // contruct a point', ' public PointABCD (PointInMetricSpace useMe) {', ' me = useMe; ', ' }', '}', '', 'class PQueueABCD <PointInMetricSpace, DataType> {', ' ', ' // this is an object in the queue', ' private class Wrapper {', ' DataWrapper <PointInMetricSpace, DataType> myData;', ' double distance;', ' }', ' ', ' // this is the actual queue', ' ArrayList <Wrapper> myList;', ' ', ' // this is the largest distance value currently in the queue', ' double large;', ' ', ' // this is the max number of objects', ' int maxCount;', ' ', ' // create a priority queue with the speced number of slots', ' PQueueABCD (int maxCountIn) {', ' maxCount = maxCountIn;', ' myList = new ArrayList <Wrapper> ();', ' large = 9e99;', ' }', ' ', ' // get the largest distance in the queue', ' double getDist () {', ' return large;', ' }', ' ', ' // add a new object to the queue... the insertion is ignored if the distance value', ' // exceeds the largest that is in the queue and the queue is already full', ' void insert (PointInMetricSpace key, DataType data, double distance) {', ' ', ' // if we are full, remove the one with the largest distance', ' if (myList.size () == maxCount && distance < large) {', ' ', ' int badIndex = 0;', ' double maxDist = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > maxDist) {', ' maxDist = myList.get (i).distance;', ' badIndex = i;', ' }', ' }', ' ', ' myList.remove (badIndex);', ' }', ' ', ' // see if there is room', ' if (myList.size () < maxCount) {', ' ', ' // add it ', ' Wrapper newOne = new Wrapper ();', ' newOne.myData = new DataWrapper <PointInMetricSpace, DataType> (key, data);', ' newOne.distance = distance;', ' myList.add (newOne); ', ' }', ' ', ' // if we are full, reset the max distance', ' if (myList.size () == maxCount) {', ' large = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > large) {', ' large = myList.get (i).distance;', ' }', ' }', ' }', ' ', ' }', ' ', ' // extracts the contents of the queue', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> done () {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' for (int i = 0; i < myList.size (); i++) {', ' returnVal.add (myList.get (i).myData); ', ' }', ' ', ' return returnVal;', ' }', ' ', '}', '', '// this is a sphere in a particular metric space', 'class SphereABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the center of the sphere and its radius', ' private PointInMetricSpace center;', ' private double radius;', ' ', ' // build a sphere out of its center and its radius', ' public SphereABCD (PointInMetricSpace centerIn, double radiusIn) {', ' center = centerIn;', ' radius = radiusIn;', ' }', ' ', ' // increase the size of the sphere so it contains the object swallowMe', ' public void swallow (IObjectInMetricSpaceABCD <PointInMetricSpace> swallowMe) {', ' ', ' // see if we need to increase the radius to swallow this guy', ' double dist = swallowMe.maxDistanceTo (center);', ' if (dist > radius)', ' radius = dist;', ' }', ' ', ' // check to see if a sphere intersects another sphere', ' public boolean intersects (SphereABCD <PointInMetricSpace> me) {', ' return (me.center.getDistance (center) <= me.radius + radius);', ' }', ' ', ' // check to see if the sphere contains a point', ' public boolean contains (PointInMetricSpace checkMe) {', ' return (checkMe.getDistance (center) <= radius);', ' }', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return center; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return radius + checkMe.getDistance (center); ', ' }', '}', '', '', '', 'class OneDimPoint implements IPointInMetricSpace <OneDimPoint> {', ' ', ' // this is the actual double', ' Double value;', ' ', ' // construct this out of a double value', ' public OneDimPoint (double makeFromMe) {', ' value = new Double (makeFromMe);', ' }', ' ', ' // get the distance to another point', ' public double getDistance (OneDimPoint toMe) {', ' if (value > toMe.value)', ' return value - toMe.value;', ' else', ' return toMe.value - value;', ' }', ' ', '}', '', 'class MultiDimPoint implements IPointInMetricSpace <MultiDimPoint> {', ' ', ' // this is the point in a multidimensional space', ' IDoubleVector me;', ' ', ' // make this out of an IDoubleVector', ' public MultiDimPoint (IDoubleVector useMe) {', ' me = useMe;', ' }', ' ', ' // get the Euclidean distance to another point', ' public double getDistance (MultiDimPoint toMe) {', ' double distance = 0.0;', ' try {', ' for (int i = 0; i < me.getLength (); i++) {', ' double diff = me.getItem (i) - toMe.me.getItem (i);', ' diff *= diff;', ' distance += diff;', ' }', ' } catch (OutOfBoundsException e) {', ' throw new IndexOutOfBoundsException ("Can\'t compare two MultiDimPoint objects with different dimensionality!"); ', ' }', ' return Math.sqrt(distance);', ' }', ' ', '}', '// this is a leaf node', 'class LeafMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements ', ' IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myData;', ' ', ' // contructor that takes a data list and builds a node out of it', ' private LeafMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myDataIn) {', ' myData = myDataIn; ', ' }', ' ', ' // constructor that creates an empty node', ' public LeafMTreeNodeABCD () {', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> (); ', ' }', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // just add in the new data', ' myData.add (new PointABCD <PointInMetricSpace> (keyToAdd), dataToAdd);', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> newOne = myData.splitInTwo ();', ' LeafMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' myQ.insert (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData (), ', ' query.getDistance (myData.get (i).getKey ().getPointInInterior ()));', ' }', ' }', ' }', ' ', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' returnVal.add (new DataWrapper <PointInMetricSpace, DataType> (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData ()));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return 1; ', ' }', '', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', '// this silly little class is just a wrapper for a key, data pair', 'class DataWrapper <Key, Data> {', ' ', ' Key key;', ' Data data;', ' ', ' public DataWrapper (Key keyIn, Data dataIn) {', ' key = keyIn;', ' data = dataIn;', ' }', ' ', ' public Key getKey () {', ' return key;', ' }', ' ', ' public Data getData () {', ' return data;', ' }', '}', '', '', '// this is an internal node', 'class InternalMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType>', ' implements IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> myData;', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' // this constructs a new internal node that holds precisely the two nodes that are passed in', ' public InternalMTreeNodeABCD (IMTreeNodeABCD <PointInMetricSpace, DataType> refOne,', ' IMTreeNodeABCD <PointInMetricSpace, DataType> refTwo) {', ' ', ' // create a necw list and add the two guys in', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> ();', ' myData.add (refOne.getBoundingSphere (), refOne);', ' myData.add (refTwo.getBoundingSphere (), refTwo);', ' }', ' ', ' // this constructs a new node that holds the list of data that we were passed in', ' public InternalMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> useMe) {', ' myData = useMe; ', ' }', ' ', ' // from the interface', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // find the best child; this is the one we are closest to', ' double bestDist = 9e99;', ' int bestIndex = 0;', ' for (int i = 0; i < myData.size (); i++) {', ' ', ' double newDist = myData.get (i).getKey ().getPointInInterior ().getDistance (keyToAdd);', ' if (newDist < bestDist) {', ' bestDist = newDist;', ' bestIndex = i;', ' }', ' }', ' ', ' // do the recursive insert', ' IMTreeNodeABCD <PointInMetricSpace, DataType> newRef = myData.get (bestIndex).getData ().insert (keyToAdd, dataToAdd);', ' ', ' // if we got something back, then there was a split, so add the new node into our list', ' if (newRef != null) {', ' myData.add (newRef.getBoundingSphere (), newRef);', ' }', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> newOne = myData.splitInTwo ();', ' InternalMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.intersects (myData.get (i).getKey ())) {', ' myData.get (i).getData ().findKClosest (query, myQ);', ' }', ' }', ' }', ' ', ' // from the interface', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.intersects (myData.get (i).getKey ())) {', ' returnVal.addAll (myData.get (i).getData ().find (query));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return myData.get (0).getData ().depth () + 1; ', ' }', ' ', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', 'abstract class AMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> implements IMetricDataListABCD <PointInMetricSpace,KeyType, DataType> {', '', ' // this is the data that is actually stored in the list', ' private ArrayList <DataWrapper <KeyType, DataType>> myData;', ' ', ' // this is the sphere that bounds everything in the list', ' private SphereABCD <PointInMetricSpace> myBoundingSphere;', ' ', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myBoundingSphere; ', ' }', ' ', ' public int size () {', ' if (myData != null)', ' return myData.size (); ', ' else', ' return 0;', ' }', ' ', ' public DataWrapper <KeyType, DataType> get (int pos) {', ' return myData.get (pos);', ' }', ' ', ' public void replaceKey (int pos, KeyType keyToAdd) {', ' DataWrapper <KeyType, DataType> temp = myData.remove (pos);', ' DataWrapper <KeyType, DataType> newOne = new DataWrapper <KeyType, DataType> (keyToAdd, temp.getData ());', ' myData.add (pos, newOne);', ' }', ' ', ' public void add (KeyType keyToAdd, DataType dataToAdd) {', ' ', ' // if this is the first add, then set everyone up', ' if (myData == null) {', ' PointInMetricSpace myCentroid = keyToAdd.getPointInInterior ();', ' myBoundingSphere = new SphereABCD <PointInMetricSpace> (myCentroid, keyToAdd.maxDistanceTo (myCentroid));', ' myData = new ArrayList <DataWrapper <KeyType, DataType>> ();', ' ', ' // otherwise, extend the sphere if needed', ' } else {', ' myBoundingSphere.swallow (keyToAdd);', ' }', ' ', ' // add the data', ' myData.add (new DataWrapper <KeyType, DataType> (keyToAdd, dataToAdd));', ' }', ' ', ' // we want to potentially allow many implementations of the splitting lalgorithm', ' abstract public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // this is here so the actual splitting algorithn can access the list and change the sphere', ' protected ArrayList <DataWrapper <KeyType, DataType>> getList () {', ' return myData;', ' }', ' ', ' // this is here so the splitting algorithm can modify the list and the sphere', ' protected void replaceGuts (AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> withMe) {', ' myData = withMe.myData;', ' myBoundingSphere = withMe.myBoundingSphere;', ' }', ' ', '}', '', '// this is a particular implementation of the metric data list that uses a simple quadratic clustering', '// algorithm to perform a list split. It picks two "seeds" (the most distant objects) and then repeatedly', '// adds to the two new lists by choosing the objects closest to the seeds', 'class ChrisMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> extends AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> {', '', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo () {', ' ', ' // first, we need to find the two most distant points in the list', ' ArrayList <DataWrapper <KeyType, DataType>> myData = getList ();', ' int bestI = 0, bestJ = 0;', ' double maxDist = -1.0;', ' for (int i = 0; i < myData.size (); i++) {', ' for (int j = i + 1; j < myData.size (); j++) {', ' ', ' // get the two keys', ' DataWrapper <KeyType, DataType> pointOne = myData.get (i);', ' DataWrapper <KeyType, DataType> pointTwo = myData.get (j);', ' ', ' // find the difference between them', ' double curDist = pointOne.getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', '', ' // see if it is the biggest', ' if (curDist > maxDist) {', ' maxDist = curDist;', ' bestI = i;', ' bestJ = j;', ' }', ' }', ' }', ' ', ' // now, we have the best two points; those are seeds for the clustering', ' DataWrapper <KeyType, DataType> pointOne = myData.remove (bestI);', ' DataWrapper <KeyType, DataType> pointTwo = myData.remove (bestJ - 1);', ' ', ' // these are the two new lists', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listOne = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listTwo = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' ', ' // put the two seeds in', ' listOne.add (pointOne.getKey (), pointOne.getData ());', ' listTwo.add (pointTwo.getKey (), pointTwo.getData ());', ' ', ' // and add everyone else in', ' while (myData.size () != 0) {', ' ', ' // find the one closest to the first seed', ' int bestIndex = 0;', ' double bestDist = 9e99;', ' ', ' // loop thru all of the candidate data objects', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listOne.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' ', ' // break if no more data', ' if (myData.size () == 0)', ' break;', ' ', ' // loop thru all of the candidate data objects', ' bestDist = 9e99;', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listTwo.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' }', ' ', ' // now we replace our own guts with the first list', ' replaceGuts (listOne);', ' ', ' // and return the other list', ' return listTwo;', ' }', '}', '', 'interface IMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> {', ' ', ' // add a new pair to the list', ' public void add (KeyType keyToAdd, DataType dataToAdd);', ' ', ' // replace a key at the indicated position', ' public void replaceKey (int pos, KeyType keyToAdd);', ' ', ' // get the key, data pair that resides at a particular position', ' public DataWrapper <KeyType, DataType> get (int pos);', ' ', ' // return the number of items in the list', ' public int size ();', ' ', ' // split the list in two, using some clutering algorithm', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // get a sphere that totally bounds all of the objects in the list', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class MTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public MTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class SCMTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public SCMTree (int intNodeSize, int leafNodeSize) {'] | [' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }'] | [' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', '', 'public class MTreeTester extends TestCase {', ' ', ' // compare two lists of strings to see if the contents are the same', ' private boolean compareStringSets (ArrayList <String> setOne, ArrayList <String> setTwo) {', ' ', ' // sort the sets and make sure they are the same', ' boolean returnVal = true;', ' if (setOne.size () == setTwo.size ()) {', ' Collections.sort (setOne);', ' Collections.sort (setTwo);', ' for (int i = 0; i < setOne.size (); i++) {', ' if (!setOne.get (i).equals (setTwo.get (i))) {', ' returnVal = false;', ' break; ', ' }', ' }', ' } else {', ' returnVal = false;', ' }', ' ', ' // print out the result', ' System.out.println ("**** Expected:");', ' for (int i = 0; i < setOne.size (); i++) {', ' System.out.format (setOne.get (i) + " ");', ' }', ' System.out.println ("\\n**** Got:");', ' for (int i = 0; i < setTwo.size (); i++) {', ' System.out.format (setTwo.get (i) + " ");', ' }', ' System.out.println ("");', ' ', ' return returnVal;', ' }', ' ', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST SIMPLE ONE DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testOneDimRangeQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.find (query, expectedQuerySize / 2);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.find (query, expectedQuerySize / 2);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (numPoints);', ' result1 = myTree.find (query, expectedQuerySize);', ' result2 = hisTree.find (query, expectedQuerySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // like the last one, but runs a top k', ' private void testOneDimTopKQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (167);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.findKClosest (query, querySize);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (0);', ' result1 = myTree.findKClosest (query, querySize);', ' result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST MULTI-DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimRangeQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' double dist1 = 0;', ' double dist2 = 0;', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' dist1 = Math.sqrt (numDims) * expectedQuerySize / 2.0;', ' dist2 = Math.sqrt (numDims) * expectedQuerySize;', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' // do a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, (int) expectedQuerySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = myTree.findKClosest (query2, (int) expectedQuerySize);', ' ', ' // find the distance to the furthest point in both cases', ' for (int i = 0; i < (int) expectedQuerySize; i++) {', ' double newDist = result1.get (i).getKey ().getDistance (query1);', ' if (newDist > dist1)', ' dist1 = newDist;', ' newDist = result2.get (i).getKey ().getDistance (query2);', ' if (newDist > dist2)', ' dist2 = newDist;', ' }', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.find (query1, dist1);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.find (query1, dist1);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.find (query2, dist2);', ' result2 = hisTree.find (query2, dist2);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimTopKQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, querySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.findKClosest (query1, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.findKClosest (query2, querySize);', ' result2 = hisTree.findKClosest (query2, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' ', ' /**', ' * "TIER 1" TESTS', ' * NONE OF THESE REQUIRE ANY SPLITS', ' */', ' public void testEasy1() {', ' testOneDimRangeQuery (true, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy2() {', ' testOneDimRangeQuery (false, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy3() {', ' testOneDimRangeQuery (true, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy4() {', ' testOneDimRangeQuery (false, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy5() {', ' testMultiDimRangeQuery (true, 1, 5, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy6() {', ' testMultiDimRangeQuery (false, 1, 10, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy7() {', ' testMultiDimRangeQuery (true, 1, 5, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy8() {', ' testMultiDimRangeQuery (false, 1, 15, 10000, 10000, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 2" TESTS', ' * NONE OF THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testMod1() {', ' testOneDimRangeQuery (true, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod2() {', ' testOneDimRangeQuery (false, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod3() {', ' testOneDimRangeQuery (true, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod4() {', ' testOneDimRangeQuery (false, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod5() {', ' testMultiDimRangeQuery (true, 2, 5, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod6() {', ' testMultiDimRangeQuery (false, 2, 10, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod7() {', ' testMultiDimRangeQuery (true, 2, 5, 10000, 100, 1000, 10);', ' }', ' ', ' public void testMod8() {', ' testMultiDimRangeQuery (false, 2, 15, 10000, 100, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 3" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testHard1() {', ' testOneDimRangeQuery (true, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard2() {', ' testOneDimRangeQuery (false, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard3() {', ' testOneDimRangeQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard4() {', ' testOneDimRangeQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard5() {', ' testMultiDimRangeQuery (true, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard6() {', ' testMultiDimRangeQuery (false, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard7() {', ' testMultiDimRangeQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard8() {', ' testMultiDimRangeQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', ' ', ' /**', ' * "TIER 4" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE AND THEY TEST THE TOPK FUNCTIONALITY', ' */', ' ', ' public void testTopK1() {', ' testOneDimTopKQuery (true, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK2() {', ' testOneDimTopKQuery (false, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK3() {', ' testOneDimTopKQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK4() {', ' testOneDimTopKQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK5() {', ' testMultiDimTopKQuery (true, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK6() {', ' testMultiDimTopKQuery (false, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK7() {', ' testMultiDimTopKQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK8() {', ' testMultiDimTopKQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', '}'] | [] | Function 'InternalMTreeNodeABCD.setMaxSize' used at line 774 is defined at line 542 and has a Long-Range dependency.
Variable 'intNodeSize' used at line 774 is defined at line 773 and has a Short-Range dependency.
Function 'LeafMTreeNodeABCD.setMaxSize' used at line 775 is defined at line 420 and has a Long-Range dependency.
Variable 'leafNodeSize' used at line 775 is defined at line 773 and has a Short-Range dependency.
Class 'LeafMTreeNodeABCD' used at line 776 is defined at line 351 and has a Long-Range dependency.
Global_Variable 'root' used at line 776 is defined at line 770 and has a Short-Range dependency. | {} | {'Function Long-Range': 2, 'Variable Short-Range': 2, 'Class Long-Range': 1, 'Global_Variable Short-Range': 1} |
infilling_java | MTreeTester | 787 | 788 | ['import junit.framework.TestCase;', 'import java.util.ArrayList;', 'import java.util.Random;', 'import java.util.Collections;', '', '// this is a map from a set of keys of type PointInMetricSpace to a', '// set of data of type DataType', 'interface IMTree <Key extends IPointInMetricSpace <Key>, Data> {', ' ', ' // insert a new key/data pair into the map', ' void insert (Key keyToAdd, Data dataToAdd);', ' ', ' // find all of the key/data pairs in the map that fall within a', ' // particular distance of query point if no results are found, then', ' // an empty array is returned (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> find (Key query, double distance);', ' ', ' // find the k closest key/data pairs in the map to a particular', ' // query point ', ' //', ' // if the number of points in the map is less than k, then the', ' // returned list will have less than k pairs in it', ' //', ' // if the number of points is zero, then an empty array is returned', ' // (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> findKClosest (Key query, int k);', ' ', ' // returns the number of nodes that exist on a path from root to leaf in the tree...', ' // whtever the details of the implementation are, a tree with a single leaf node should return 1, and a tree', ' // with more than one lead node should return at least two (since it must have at least one internal node).', ' public int depth ();', ' ', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', '', 'interface IDoubleVector {', '', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '', '// this correponds to some geometric object in a metric space; the object is built out of', '// one or more points of type PointInMetricSpace', 'interface IObjectInMetricSpaceABCD <PointInMetricSpace extends IPointInMetricSpace<PointInMetricSpace>> {', ' ', ' // get the maximum distance from some point on the shape to a particular point in the metric space', ' double maxDistanceTo (PointInMetricSpace checkMe);', ' ', ' // return some arbitrary point on the interior of the geometric object', ' PointInMetricSpace getPointInInterior ();', '}', '', '', '// this interface corresponds to a point in some metric space', 'interface IPointInMetricSpace <PointInMetricSpace> {', ' ', ' // get the distance to another point', ' // ', ' // for this to work in an M-Tree, distances should be "metric" and', ' // obey the triangle inequality', ' double getDistance (PointInMetricSpace toMe);', '}', '', '// this is the basic node type in the structure', 'interface IMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> {', ' ', ' // insert a new key/data pair into the structure. The return value is a new MTreeNode if there was', ' // a split in response to the insertion, or a null if there was no split', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd);', ' ', ' // find all of the key/data pairs in the structure that fall within a particular query sphere', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query); ', ' ', ' // find the set of items closest to the given query point', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ);', ' ', ' // returns a sphere that totally encompasses everything in the node and its subtree', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', ' ', ' // returns the depth', ' public int depth ();', '}', '', '// this is a point in a particular metric space', 'class PointABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the point', ' private PointInMetricSpace me;', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return me; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return checkMe.getDistance (me); ', ' }', ' ', ' // contruct a point', ' public PointABCD (PointInMetricSpace useMe) {', ' me = useMe; ', ' }', '}', '', 'class PQueueABCD <PointInMetricSpace, DataType> {', ' ', ' // this is an object in the queue', ' private class Wrapper {', ' DataWrapper <PointInMetricSpace, DataType> myData;', ' double distance;', ' }', ' ', ' // this is the actual queue', ' ArrayList <Wrapper> myList;', ' ', ' // this is the largest distance value currently in the queue', ' double large;', ' ', ' // this is the max number of objects', ' int maxCount;', ' ', ' // create a priority queue with the speced number of slots', ' PQueueABCD (int maxCountIn) {', ' maxCount = maxCountIn;', ' myList = new ArrayList <Wrapper> ();', ' large = 9e99;', ' }', ' ', ' // get the largest distance in the queue', ' double getDist () {', ' return large;', ' }', ' ', ' // add a new object to the queue... the insertion is ignored if the distance value', ' // exceeds the largest that is in the queue and the queue is already full', ' void insert (PointInMetricSpace key, DataType data, double distance) {', ' ', ' // if we are full, remove the one with the largest distance', ' if (myList.size () == maxCount && distance < large) {', ' ', ' int badIndex = 0;', ' double maxDist = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > maxDist) {', ' maxDist = myList.get (i).distance;', ' badIndex = i;', ' }', ' }', ' ', ' myList.remove (badIndex);', ' }', ' ', ' // see if there is room', ' if (myList.size () < maxCount) {', ' ', ' // add it ', ' Wrapper newOne = new Wrapper ();', ' newOne.myData = new DataWrapper <PointInMetricSpace, DataType> (key, data);', ' newOne.distance = distance;', ' myList.add (newOne); ', ' }', ' ', ' // if we are full, reset the max distance', ' if (myList.size () == maxCount) {', ' large = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > large) {', ' large = myList.get (i).distance;', ' }', ' }', ' }', ' ', ' }', ' ', ' // extracts the contents of the queue', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> done () {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' for (int i = 0; i < myList.size (); i++) {', ' returnVal.add (myList.get (i).myData); ', ' }', ' ', ' return returnVal;', ' }', ' ', '}', '', '// this is a sphere in a particular metric space', 'class SphereABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the center of the sphere and its radius', ' private PointInMetricSpace center;', ' private double radius;', ' ', ' // build a sphere out of its center and its radius', ' public SphereABCD (PointInMetricSpace centerIn, double radiusIn) {', ' center = centerIn;', ' radius = radiusIn;', ' }', ' ', ' // increase the size of the sphere so it contains the object swallowMe', ' public void swallow (IObjectInMetricSpaceABCD <PointInMetricSpace> swallowMe) {', ' ', ' // see if we need to increase the radius to swallow this guy', ' double dist = swallowMe.maxDistanceTo (center);', ' if (dist > radius)', ' radius = dist;', ' }', ' ', ' // check to see if a sphere intersects another sphere', ' public boolean intersects (SphereABCD <PointInMetricSpace> me) {', ' return (me.center.getDistance (center) <= me.radius + radius);', ' }', ' ', ' // check to see if the sphere contains a point', ' public boolean contains (PointInMetricSpace checkMe) {', ' return (checkMe.getDistance (center) <= radius);', ' }', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return center; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return radius + checkMe.getDistance (center); ', ' }', '}', '', '', '', 'class OneDimPoint implements IPointInMetricSpace <OneDimPoint> {', ' ', ' // this is the actual double', ' Double value;', ' ', ' // construct this out of a double value', ' public OneDimPoint (double makeFromMe) {', ' value = new Double (makeFromMe);', ' }', ' ', ' // get the distance to another point', ' public double getDistance (OneDimPoint toMe) {', ' if (value > toMe.value)', ' return value - toMe.value;', ' else', ' return toMe.value - value;', ' }', ' ', '}', '', 'class MultiDimPoint implements IPointInMetricSpace <MultiDimPoint> {', ' ', ' // this is the point in a multidimensional space', ' IDoubleVector me;', ' ', ' // make this out of an IDoubleVector', ' public MultiDimPoint (IDoubleVector useMe) {', ' me = useMe;', ' }', ' ', ' // get the Euclidean distance to another point', ' public double getDistance (MultiDimPoint toMe) {', ' double distance = 0.0;', ' try {', ' for (int i = 0; i < me.getLength (); i++) {', ' double diff = me.getItem (i) - toMe.me.getItem (i);', ' diff *= diff;', ' distance += diff;', ' }', ' } catch (OutOfBoundsException e) {', ' throw new IndexOutOfBoundsException ("Can\'t compare two MultiDimPoint objects with different dimensionality!"); ', ' }', ' return Math.sqrt(distance);', ' }', ' ', '}', '// this is a leaf node', 'class LeafMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements ', ' IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myData;', ' ', ' // contructor that takes a data list and builds a node out of it', ' private LeafMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myDataIn) {', ' myData = myDataIn; ', ' }', ' ', ' // constructor that creates an empty node', ' public LeafMTreeNodeABCD () {', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> (); ', ' }', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // just add in the new data', ' myData.add (new PointABCD <PointInMetricSpace> (keyToAdd), dataToAdd);', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> newOne = myData.splitInTwo ();', ' LeafMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' myQ.insert (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData (), ', ' query.getDistance (myData.get (i).getKey ().getPointInInterior ()));', ' }', ' }', ' }', ' ', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' returnVal.add (new DataWrapper <PointInMetricSpace, DataType> (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData ()));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return 1; ', ' }', '', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', '// this silly little class is just a wrapper for a key, data pair', 'class DataWrapper <Key, Data> {', ' ', ' Key key;', ' Data data;', ' ', ' public DataWrapper (Key keyIn, Data dataIn) {', ' key = keyIn;', ' data = dataIn;', ' }', ' ', ' public Key getKey () {', ' return key;', ' }', ' ', ' public Data getData () {', ' return data;', ' }', '}', '', '', '// this is an internal node', 'class InternalMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType>', ' implements IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> myData;', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' // this constructs a new internal node that holds precisely the two nodes that are passed in', ' public InternalMTreeNodeABCD (IMTreeNodeABCD <PointInMetricSpace, DataType> refOne,', ' IMTreeNodeABCD <PointInMetricSpace, DataType> refTwo) {', ' ', ' // create a necw list and add the two guys in', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> ();', ' myData.add (refOne.getBoundingSphere (), refOne);', ' myData.add (refTwo.getBoundingSphere (), refTwo);', ' }', ' ', ' // this constructs a new node that holds the list of data that we were passed in', ' public InternalMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> useMe) {', ' myData = useMe; ', ' }', ' ', ' // from the interface', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // find the best child; this is the one we are closest to', ' double bestDist = 9e99;', ' int bestIndex = 0;', ' for (int i = 0; i < myData.size (); i++) {', ' ', ' double newDist = myData.get (i).getKey ().getPointInInterior ().getDistance (keyToAdd);', ' if (newDist < bestDist) {', ' bestDist = newDist;', ' bestIndex = i;', ' }', ' }', ' ', ' // do the recursive insert', ' IMTreeNodeABCD <PointInMetricSpace, DataType> newRef = myData.get (bestIndex).getData ().insert (keyToAdd, dataToAdd);', ' ', ' // if we got something back, then there was a split, so add the new node into our list', ' if (newRef != null) {', ' myData.add (newRef.getBoundingSphere (), newRef);', ' }', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> newOne = myData.splitInTwo ();', ' InternalMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.intersects (myData.get (i).getKey ())) {', ' myData.get (i).getData ().findKClosest (query, myQ);', ' }', ' }', ' }', ' ', ' // from the interface', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.intersects (myData.get (i).getKey ())) {', ' returnVal.addAll (myData.get (i).getData ().find (query));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return myData.get (0).getData ().depth () + 1; ', ' }', ' ', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', 'abstract class AMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> implements IMetricDataListABCD <PointInMetricSpace,KeyType, DataType> {', '', ' // this is the data that is actually stored in the list', ' private ArrayList <DataWrapper <KeyType, DataType>> myData;', ' ', ' // this is the sphere that bounds everything in the list', ' private SphereABCD <PointInMetricSpace> myBoundingSphere;', ' ', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myBoundingSphere; ', ' }', ' ', ' public int size () {', ' if (myData != null)', ' return myData.size (); ', ' else', ' return 0;', ' }', ' ', ' public DataWrapper <KeyType, DataType> get (int pos) {', ' return myData.get (pos);', ' }', ' ', ' public void replaceKey (int pos, KeyType keyToAdd) {', ' DataWrapper <KeyType, DataType> temp = myData.remove (pos);', ' DataWrapper <KeyType, DataType> newOne = new DataWrapper <KeyType, DataType> (keyToAdd, temp.getData ());', ' myData.add (pos, newOne);', ' }', ' ', ' public void add (KeyType keyToAdd, DataType dataToAdd) {', ' ', ' // if this is the first add, then set everyone up', ' if (myData == null) {', ' PointInMetricSpace myCentroid = keyToAdd.getPointInInterior ();', ' myBoundingSphere = new SphereABCD <PointInMetricSpace> (myCentroid, keyToAdd.maxDistanceTo (myCentroid));', ' myData = new ArrayList <DataWrapper <KeyType, DataType>> ();', ' ', ' // otherwise, extend the sphere if needed', ' } else {', ' myBoundingSphere.swallow (keyToAdd);', ' }', ' ', ' // add the data', ' myData.add (new DataWrapper <KeyType, DataType> (keyToAdd, dataToAdd));', ' }', ' ', ' // we want to potentially allow many implementations of the splitting lalgorithm', ' abstract public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // this is here so the actual splitting algorithn can access the list and change the sphere', ' protected ArrayList <DataWrapper <KeyType, DataType>> getList () {', ' return myData;', ' }', ' ', ' // this is here so the splitting algorithm can modify the list and the sphere', ' protected void replaceGuts (AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> withMe) {', ' myData = withMe.myData;', ' myBoundingSphere = withMe.myBoundingSphere;', ' }', ' ', '}', '', '// this is a particular implementation of the metric data list that uses a simple quadratic clustering', '// algorithm to perform a list split. It picks two "seeds" (the most distant objects) and then repeatedly', '// adds to the two new lists by choosing the objects closest to the seeds', 'class ChrisMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> extends AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> {', '', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo () {', ' ', ' // first, we need to find the two most distant points in the list', ' ArrayList <DataWrapper <KeyType, DataType>> myData = getList ();', ' int bestI = 0, bestJ = 0;', ' double maxDist = -1.0;', ' for (int i = 0; i < myData.size (); i++) {', ' for (int j = i + 1; j < myData.size (); j++) {', ' ', ' // get the two keys', ' DataWrapper <KeyType, DataType> pointOne = myData.get (i);', ' DataWrapper <KeyType, DataType> pointTwo = myData.get (j);', ' ', ' // find the difference between them', ' double curDist = pointOne.getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', '', ' // see if it is the biggest', ' if (curDist > maxDist) {', ' maxDist = curDist;', ' bestI = i;', ' bestJ = j;', ' }', ' }', ' }', ' ', ' // now, we have the best two points; those are seeds for the clustering', ' DataWrapper <KeyType, DataType> pointOne = myData.remove (bestI);', ' DataWrapper <KeyType, DataType> pointTwo = myData.remove (bestJ - 1);', ' ', ' // these are the two new lists', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listOne = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listTwo = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' ', ' // put the two seeds in', ' listOne.add (pointOne.getKey (), pointOne.getData ());', ' listTwo.add (pointTwo.getKey (), pointTwo.getData ());', ' ', ' // and add everyone else in', ' while (myData.size () != 0) {', ' ', ' // find the one closest to the first seed', ' int bestIndex = 0;', ' double bestDist = 9e99;', ' ', ' // loop thru all of the candidate data objects', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listOne.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' ', ' // break if no more data', ' if (myData.size () == 0)', ' break;', ' ', ' // loop thru all of the candidate data objects', ' bestDist = 9e99;', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listTwo.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' }', ' ', ' // now we replace our own guts with the first list', ' replaceGuts (listOne);', ' ', ' // and return the other list', ' return listTwo;', ' }', '}', '', 'interface IMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> {', ' ', ' // add a new pair to the list', ' public void add (KeyType keyToAdd, DataType dataToAdd);', ' ', ' // replace a key at the indicated position', ' public void replaceKey (int pos, KeyType keyToAdd);', ' ', ' // get the key, data pair that resides at a particular position', ' public DataWrapper <KeyType, DataType> get (int pos);', ' ', ' // return the number of items in the list', ' public int size ();', ' ', ' // split the list in two, using some clutering algorithm', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // get a sphere that totally bounds all of the objects in the list', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class MTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public MTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class SCMTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public SCMTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {'] | [' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }'] | [' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', '', 'public class MTreeTester extends TestCase {', ' ', ' // compare two lists of strings to see if the contents are the same', ' private boolean compareStringSets (ArrayList <String> setOne, ArrayList <String> setTwo) {', ' ', ' // sort the sets and make sure they are the same', ' boolean returnVal = true;', ' if (setOne.size () == setTwo.size ()) {', ' Collections.sort (setOne);', ' Collections.sort (setTwo);', ' for (int i = 0; i < setOne.size (); i++) {', ' if (!setOne.get (i).equals (setTwo.get (i))) {', ' returnVal = false;', ' break; ', ' }', ' }', ' } else {', ' returnVal = false;', ' }', ' ', ' // print out the result', ' System.out.println ("**** Expected:");', ' for (int i = 0; i < setOne.size (); i++) {', ' System.out.format (setOne.get (i) + " ");', ' }', ' System.out.println ("\\n**** Got:");', ' for (int i = 0; i < setTwo.size (); i++) {', ' System.out.format (setTwo.get (i) + " ");', ' }', ' System.out.println ("");', ' ', ' return returnVal;', ' }', ' ', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST SIMPLE ONE DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testOneDimRangeQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.find (query, expectedQuerySize / 2);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.find (query, expectedQuerySize / 2);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (numPoints);', ' result1 = myTree.find (query, expectedQuerySize);', ' result2 = hisTree.find (query, expectedQuerySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // like the last one, but runs a top k', ' private void testOneDimTopKQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (167);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.findKClosest (query, querySize);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (0);', ' result1 = myTree.findKClosest (query, querySize);', ' result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST MULTI-DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimRangeQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' double dist1 = 0;', ' double dist2 = 0;', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' dist1 = Math.sqrt (numDims) * expectedQuerySize / 2.0;', ' dist2 = Math.sqrt (numDims) * expectedQuerySize;', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' // do a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, (int) expectedQuerySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = myTree.findKClosest (query2, (int) expectedQuerySize);', ' ', ' // find the distance to the furthest point in both cases', ' for (int i = 0; i < (int) expectedQuerySize; i++) {', ' double newDist = result1.get (i).getKey ().getDistance (query1);', ' if (newDist > dist1)', ' dist1 = newDist;', ' newDist = result2.get (i).getKey ().getDistance (query2);', ' if (newDist > dist2)', ' dist2 = newDist;', ' }', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.find (query1, dist1);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.find (query1, dist1);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.find (query2, dist2);', ' result2 = hisTree.find (query2, dist2);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimTopKQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, querySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.findKClosest (query1, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.findKClosest (query2, querySize);', ' result2 = hisTree.findKClosest (query2, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' ', ' /**', ' * "TIER 1" TESTS', ' * NONE OF THESE REQUIRE ANY SPLITS', ' */', ' public void testEasy1() {', ' testOneDimRangeQuery (true, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy2() {', ' testOneDimRangeQuery (false, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy3() {', ' testOneDimRangeQuery (true, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy4() {', ' testOneDimRangeQuery (false, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy5() {', ' testMultiDimRangeQuery (true, 1, 5, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy6() {', ' testMultiDimRangeQuery (false, 1, 10, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy7() {', ' testMultiDimRangeQuery (true, 1, 5, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy8() {', ' testMultiDimRangeQuery (false, 1, 15, 10000, 10000, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 2" TESTS', ' * NONE OF THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testMod1() {', ' testOneDimRangeQuery (true, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod2() {', ' testOneDimRangeQuery (false, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod3() {', ' testOneDimRangeQuery (true, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod4() {', ' testOneDimRangeQuery (false, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod5() {', ' testMultiDimRangeQuery (true, 2, 5, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod6() {', ' testMultiDimRangeQuery (false, 2, 10, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod7() {', ' testMultiDimRangeQuery (true, 2, 5, 10000, 100, 1000, 10);', ' }', ' ', ' public void testMod8() {', ' testMultiDimRangeQuery (false, 2, 15, 10000, 100, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 3" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testHard1() {', ' testOneDimRangeQuery (true, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard2() {', ' testOneDimRangeQuery (false, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard3() {', ' testOneDimRangeQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard4() {', ' testOneDimRangeQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard5() {', ' testMultiDimRangeQuery (true, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard6() {', ' testMultiDimRangeQuery (false, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard7() {', ' testMultiDimRangeQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard8() {', ' testMultiDimRangeQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', ' ', ' /**', ' * "TIER 4" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE AND THEY TEST THE TOPK FUNCTIONALITY', ' */', ' ', ' public void testTopK1() {', ' testOneDimTopKQuery (true, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK2() {', ' testOneDimTopKQuery (false, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK3() {', ' testOneDimTopKQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK4() {', ' testOneDimTopKQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK5() {', ' testMultiDimTopKQuery (true, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK6() {', ' testMultiDimTopKQuery (false, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK7() {', ' testMultiDimTopKQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK8() {', ' testMultiDimTopKQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', '}'] | [{'reason_category': 'If Body', 'usage_line': 787}, {'reason_category': 'If Body', 'usage_line': 788}] | Class 'InternalMTreeNodeABCD' used at line 787 is defined at line 450 and has a Long-Range dependency.
Global_Variable 'root' used at line 787 is defined at line 770 and has a Medium-Range dependency.
Variable 'res' used at line 787 is defined at line 783 and has a Short-Range dependency. | {'If Body': 2} | {'Class Long-Range': 1, 'Global_Variable Medium-Range': 1, 'Variable Short-Range': 1} |
infilling_java | MTreeTester | 805 | 806 | ['import junit.framework.TestCase;', 'import java.util.ArrayList;', 'import java.util.Random;', 'import java.util.Collections;', '', '// this is a map from a set of keys of type PointInMetricSpace to a', '// set of data of type DataType', 'interface IMTree <Key extends IPointInMetricSpace <Key>, Data> {', ' ', ' // insert a new key/data pair into the map', ' void insert (Key keyToAdd, Data dataToAdd);', ' ', ' // find all of the key/data pairs in the map that fall within a', ' // particular distance of query point if no results are found, then', ' // an empty array is returned (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> find (Key query, double distance);', ' ', ' // find the k closest key/data pairs in the map to a particular', ' // query point ', ' //', ' // if the number of points in the map is less than k, then the', ' // returned list will have less than k pairs in it', ' //', ' // if the number of points is zero, then an empty array is returned', ' // (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> findKClosest (Key query, int k);', ' ', ' // returns the number of nodes that exist on a path from root to leaf in the tree...', ' // whtever the details of the implementation are, a tree with a single leaf node should return 1, and a tree', ' // with more than one lead node should return at least two (since it must have at least one internal node).', ' public int depth ();', ' ', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', '', 'interface IDoubleVector {', '', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '', '// this correponds to some geometric object in a metric space; the object is built out of', '// one or more points of type PointInMetricSpace', 'interface IObjectInMetricSpaceABCD <PointInMetricSpace extends IPointInMetricSpace<PointInMetricSpace>> {', ' ', ' // get the maximum distance from some point on the shape to a particular point in the metric space', ' double maxDistanceTo (PointInMetricSpace checkMe);', ' ', ' // return some arbitrary point on the interior of the geometric object', ' PointInMetricSpace getPointInInterior ();', '}', '', '', '// this interface corresponds to a point in some metric space', 'interface IPointInMetricSpace <PointInMetricSpace> {', ' ', ' // get the distance to another point', ' // ', ' // for this to work in an M-Tree, distances should be "metric" and', ' // obey the triangle inequality', ' double getDistance (PointInMetricSpace toMe);', '}', '', '// this is the basic node type in the structure', 'interface IMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> {', ' ', ' // insert a new key/data pair into the structure. The return value is a new MTreeNode if there was', ' // a split in response to the insertion, or a null if there was no split', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd);', ' ', ' // find all of the key/data pairs in the structure that fall within a particular query sphere', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query); ', ' ', ' // find the set of items closest to the given query point', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ);', ' ', ' // returns a sphere that totally encompasses everything in the node and its subtree', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', ' ', ' // returns the depth', ' public int depth ();', '}', '', '// this is a point in a particular metric space', 'class PointABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the point', ' private PointInMetricSpace me;', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return me; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return checkMe.getDistance (me); ', ' }', ' ', ' // contruct a point', ' public PointABCD (PointInMetricSpace useMe) {', ' me = useMe; ', ' }', '}', '', 'class PQueueABCD <PointInMetricSpace, DataType> {', ' ', ' // this is an object in the queue', ' private class Wrapper {', ' DataWrapper <PointInMetricSpace, DataType> myData;', ' double distance;', ' }', ' ', ' // this is the actual queue', ' ArrayList <Wrapper> myList;', ' ', ' // this is the largest distance value currently in the queue', ' double large;', ' ', ' // this is the max number of objects', ' int maxCount;', ' ', ' // create a priority queue with the speced number of slots', ' PQueueABCD (int maxCountIn) {', ' maxCount = maxCountIn;', ' myList = new ArrayList <Wrapper> ();', ' large = 9e99;', ' }', ' ', ' // get the largest distance in the queue', ' double getDist () {', ' return large;', ' }', ' ', ' // add a new object to the queue... the insertion is ignored if the distance value', ' // exceeds the largest that is in the queue and the queue is already full', ' void insert (PointInMetricSpace key, DataType data, double distance) {', ' ', ' // if we are full, remove the one with the largest distance', ' if (myList.size () == maxCount && distance < large) {', ' ', ' int badIndex = 0;', ' double maxDist = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > maxDist) {', ' maxDist = myList.get (i).distance;', ' badIndex = i;', ' }', ' }', ' ', ' myList.remove (badIndex);', ' }', ' ', ' // see if there is room', ' if (myList.size () < maxCount) {', ' ', ' // add it ', ' Wrapper newOne = new Wrapper ();', ' newOne.myData = new DataWrapper <PointInMetricSpace, DataType> (key, data);', ' newOne.distance = distance;', ' myList.add (newOne); ', ' }', ' ', ' // if we are full, reset the max distance', ' if (myList.size () == maxCount) {', ' large = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > large) {', ' large = myList.get (i).distance;', ' }', ' }', ' }', ' ', ' }', ' ', ' // extracts the contents of the queue', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> done () {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' for (int i = 0; i < myList.size (); i++) {', ' returnVal.add (myList.get (i).myData); ', ' }', ' ', ' return returnVal;', ' }', ' ', '}', '', '// this is a sphere in a particular metric space', 'class SphereABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the center of the sphere and its radius', ' private PointInMetricSpace center;', ' private double radius;', ' ', ' // build a sphere out of its center and its radius', ' public SphereABCD (PointInMetricSpace centerIn, double radiusIn) {', ' center = centerIn;', ' radius = radiusIn;', ' }', ' ', ' // increase the size of the sphere so it contains the object swallowMe', ' public void swallow (IObjectInMetricSpaceABCD <PointInMetricSpace> swallowMe) {', ' ', ' // see if we need to increase the radius to swallow this guy', ' double dist = swallowMe.maxDistanceTo (center);', ' if (dist > radius)', ' radius = dist;', ' }', ' ', ' // check to see if a sphere intersects another sphere', ' public boolean intersects (SphereABCD <PointInMetricSpace> me) {', ' return (me.center.getDistance (center) <= me.radius + radius);', ' }', ' ', ' // check to see if the sphere contains a point', ' public boolean contains (PointInMetricSpace checkMe) {', ' return (checkMe.getDistance (center) <= radius);', ' }', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return center; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return radius + checkMe.getDistance (center); ', ' }', '}', '', '', '', 'class OneDimPoint implements IPointInMetricSpace <OneDimPoint> {', ' ', ' // this is the actual double', ' Double value;', ' ', ' // construct this out of a double value', ' public OneDimPoint (double makeFromMe) {', ' value = new Double (makeFromMe);', ' }', ' ', ' // get the distance to another point', ' public double getDistance (OneDimPoint toMe) {', ' if (value > toMe.value)', ' return value - toMe.value;', ' else', ' return toMe.value - value;', ' }', ' ', '}', '', 'class MultiDimPoint implements IPointInMetricSpace <MultiDimPoint> {', ' ', ' // this is the point in a multidimensional space', ' IDoubleVector me;', ' ', ' // make this out of an IDoubleVector', ' public MultiDimPoint (IDoubleVector useMe) {', ' me = useMe;', ' }', ' ', ' // get the Euclidean distance to another point', ' public double getDistance (MultiDimPoint toMe) {', ' double distance = 0.0;', ' try {', ' for (int i = 0; i < me.getLength (); i++) {', ' double diff = me.getItem (i) - toMe.me.getItem (i);', ' diff *= diff;', ' distance += diff;', ' }', ' } catch (OutOfBoundsException e) {', ' throw new IndexOutOfBoundsException ("Can\'t compare two MultiDimPoint objects with different dimensionality!"); ', ' }', ' return Math.sqrt(distance);', ' }', ' ', '}', '// this is a leaf node', 'class LeafMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements ', ' IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myData;', ' ', ' // contructor that takes a data list and builds a node out of it', ' private LeafMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myDataIn) {', ' myData = myDataIn; ', ' }', ' ', ' // constructor that creates an empty node', ' public LeafMTreeNodeABCD () {', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> (); ', ' }', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // just add in the new data', ' myData.add (new PointABCD <PointInMetricSpace> (keyToAdd), dataToAdd);', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> newOne = myData.splitInTwo ();', ' LeafMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' myQ.insert (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData (), ', ' query.getDistance (myData.get (i).getKey ().getPointInInterior ()));', ' }', ' }', ' }', ' ', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' returnVal.add (new DataWrapper <PointInMetricSpace, DataType> (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData ()));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return 1; ', ' }', '', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', '// this silly little class is just a wrapper for a key, data pair', 'class DataWrapper <Key, Data> {', ' ', ' Key key;', ' Data data;', ' ', ' public DataWrapper (Key keyIn, Data dataIn) {', ' key = keyIn;', ' data = dataIn;', ' }', ' ', ' public Key getKey () {', ' return key;', ' }', ' ', ' public Data getData () {', ' return data;', ' }', '}', '', '', '// this is an internal node', 'class InternalMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType>', ' implements IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> myData;', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' // this constructs a new internal node that holds precisely the two nodes that are passed in', ' public InternalMTreeNodeABCD (IMTreeNodeABCD <PointInMetricSpace, DataType> refOne,', ' IMTreeNodeABCD <PointInMetricSpace, DataType> refTwo) {', ' ', ' // create a necw list and add the two guys in', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> ();', ' myData.add (refOne.getBoundingSphere (), refOne);', ' myData.add (refTwo.getBoundingSphere (), refTwo);', ' }', ' ', ' // this constructs a new node that holds the list of data that we were passed in', ' public InternalMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> useMe) {', ' myData = useMe; ', ' }', ' ', ' // from the interface', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // find the best child; this is the one we are closest to', ' double bestDist = 9e99;', ' int bestIndex = 0;', ' for (int i = 0; i < myData.size (); i++) {', ' ', ' double newDist = myData.get (i).getKey ().getPointInInterior ().getDistance (keyToAdd);', ' if (newDist < bestDist) {', ' bestDist = newDist;', ' bestIndex = i;', ' }', ' }', ' ', ' // do the recursive insert', ' IMTreeNodeABCD <PointInMetricSpace, DataType> newRef = myData.get (bestIndex).getData ().insert (keyToAdd, dataToAdd);', ' ', ' // if we got something back, then there was a split, so add the new node into our list', ' if (newRef != null) {', ' myData.add (newRef.getBoundingSphere (), newRef);', ' }', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> newOne = myData.splitInTwo ();', ' InternalMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.intersects (myData.get (i).getKey ())) {', ' myData.get (i).getData ().findKClosest (query, myQ);', ' }', ' }', ' }', ' ', ' // from the interface', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.intersects (myData.get (i).getKey ())) {', ' returnVal.addAll (myData.get (i).getData ().find (query));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return myData.get (0).getData ().depth () + 1; ', ' }', ' ', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', 'abstract class AMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> implements IMetricDataListABCD <PointInMetricSpace,KeyType, DataType> {', '', ' // this is the data that is actually stored in the list', ' private ArrayList <DataWrapper <KeyType, DataType>> myData;', ' ', ' // this is the sphere that bounds everything in the list', ' private SphereABCD <PointInMetricSpace> myBoundingSphere;', ' ', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myBoundingSphere; ', ' }', ' ', ' public int size () {', ' if (myData != null)', ' return myData.size (); ', ' else', ' return 0;', ' }', ' ', ' public DataWrapper <KeyType, DataType> get (int pos) {', ' return myData.get (pos);', ' }', ' ', ' public void replaceKey (int pos, KeyType keyToAdd) {', ' DataWrapper <KeyType, DataType> temp = myData.remove (pos);', ' DataWrapper <KeyType, DataType> newOne = new DataWrapper <KeyType, DataType> (keyToAdd, temp.getData ());', ' myData.add (pos, newOne);', ' }', ' ', ' public void add (KeyType keyToAdd, DataType dataToAdd) {', ' ', ' // if this is the first add, then set everyone up', ' if (myData == null) {', ' PointInMetricSpace myCentroid = keyToAdd.getPointInInterior ();', ' myBoundingSphere = new SphereABCD <PointInMetricSpace> (myCentroid, keyToAdd.maxDistanceTo (myCentroid));', ' myData = new ArrayList <DataWrapper <KeyType, DataType>> ();', ' ', ' // otherwise, extend the sphere if needed', ' } else {', ' myBoundingSphere.swallow (keyToAdd);', ' }', ' ', ' // add the data', ' myData.add (new DataWrapper <KeyType, DataType> (keyToAdd, dataToAdd));', ' }', ' ', ' // we want to potentially allow many implementations of the splitting lalgorithm', ' abstract public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // this is here so the actual splitting algorithn can access the list and change the sphere', ' protected ArrayList <DataWrapper <KeyType, DataType>> getList () {', ' return myData;', ' }', ' ', ' // this is here so the splitting algorithm can modify the list and the sphere', ' protected void replaceGuts (AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> withMe) {', ' myData = withMe.myData;', ' myBoundingSphere = withMe.myBoundingSphere;', ' }', ' ', '}', '', '// this is a particular implementation of the metric data list that uses a simple quadratic clustering', '// algorithm to perform a list split. It picks two "seeds" (the most distant objects) and then repeatedly', '// adds to the two new lists by choosing the objects closest to the seeds', 'class ChrisMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> extends AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> {', '', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo () {', ' ', ' // first, we need to find the two most distant points in the list', ' ArrayList <DataWrapper <KeyType, DataType>> myData = getList ();', ' int bestI = 0, bestJ = 0;', ' double maxDist = -1.0;', ' for (int i = 0; i < myData.size (); i++) {', ' for (int j = i + 1; j < myData.size (); j++) {', ' ', ' // get the two keys', ' DataWrapper <KeyType, DataType> pointOne = myData.get (i);', ' DataWrapper <KeyType, DataType> pointTwo = myData.get (j);', ' ', ' // find the difference between them', ' double curDist = pointOne.getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', '', ' // see if it is the biggest', ' if (curDist > maxDist) {', ' maxDist = curDist;', ' bestI = i;', ' bestJ = j;', ' }', ' }', ' }', ' ', ' // now, we have the best two points; those are seeds for the clustering', ' DataWrapper <KeyType, DataType> pointOne = myData.remove (bestI);', ' DataWrapper <KeyType, DataType> pointTwo = myData.remove (bestJ - 1);', ' ', ' // these are the two new lists', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listOne = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listTwo = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' ', ' // put the two seeds in', ' listOne.add (pointOne.getKey (), pointOne.getData ());', ' listTwo.add (pointTwo.getKey (), pointTwo.getData ());', ' ', ' // and add everyone else in', ' while (myData.size () != 0) {', ' ', ' // find the one closest to the first seed', ' int bestIndex = 0;', ' double bestDist = 9e99;', ' ', ' // loop thru all of the candidate data objects', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listOne.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' ', ' // break if no more data', ' if (myData.size () == 0)', ' break;', ' ', ' // loop thru all of the candidate data objects', ' bestDist = 9e99;', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listTwo.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' }', ' ', ' // now we replace our own guts with the first list', ' replaceGuts (listOne);', ' ', ' // and return the other list', ' return listTwo;', ' }', '}', '', 'interface IMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> {', ' ', ' // add a new pair to the list', ' public void add (KeyType keyToAdd, DataType dataToAdd);', ' ', ' // replace a key at the indicated position', ' public void replaceKey (int pos, KeyType keyToAdd);', ' ', ' // get the key, data pair that resides at a particular position', ' public DataWrapper <KeyType, DataType> get (int pos);', ' ', ' // return the number of items in the list', ' public int size ();', ' ', ' // split the list in two, using some clutering algorithm', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // get a sphere that totally bounds all of the objects in the list', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class MTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public MTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class SCMTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public SCMTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {'] | [' return root.depth (); ', ' }'] | ['}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', '', 'public class MTreeTester extends TestCase {', ' ', ' // compare two lists of strings to see if the contents are the same', ' private boolean compareStringSets (ArrayList <String> setOne, ArrayList <String> setTwo) {', ' ', ' // sort the sets and make sure they are the same', ' boolean returnVal = true;', ' if (setOne.size () == setTwo.size ()) {', ' Collections.sort (setOne);', ' Collections.sort (setTwo);', ' for (int i = 0; i < setOne.size (); i++) {', ' if (!setOne.get (i).equals (setTwo.get (i))) {', ' returnVal = false;', ' break; ', ' }', ' }', ' } else {', ' returnVal = false;', ' }', ' ', ' // print out the result', ' System.out.println ("**** Expected:");', ' for (int i = 0; i < setOne.size (); i++) {', ' System.out.format (setOne.get (i) + " ");', ' }', ' System.out.println ("\\n**** Got:");', ' for (int i = 0; i < setTwo.size (); i++) {', ' System.out.format (setTwo.get (i) + " ");', ' }', ' System.out.println ("");', ' ', ' return returnVal;', ' }', ' ', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST SIMPLE ONE DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testOneDimRangeQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.find (query, expectedQuerySize / 2);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.find (query, expectedQuerySize / 2);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (numPoints);', ' result1 = myTree.find (query, expectedQuerySize);', ' result2 = hisTree.find (query, expectedQuerySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // like the last one, but runs a top k', ' private void testOneDimTopKQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (167);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.findKClosest (query, querySize);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (0);', ' result1 = myTree.findKClosest (query, querySize);', ' result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST MULTI-DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimRangeQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' double dist1 = 0;', ' double dist2 = 0;', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' dist1 = Math.sqrt (numDims) * expectedQuerySize / 2.0;', ' dist2 = Math.sqrt (numDims) * expectedQuerySize;', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' // do a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, (int) expectedQuerySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = myTree.findKClosest (query2, (int) expectedQuerySize);', ' ', ' // find the distance to the furthest point in both cases', ' for (int i = 0; i < (int) expectedQuerySize; i++) {', ' double newDist = result1.get (i).getKey ().getDistance (query1);', ' if (newDist > dist1)', ' dist1 = newDist;', ' newDist = result2.get (i).getKey ().getDistance (query2);', ' if (newDist > dist2)', ' dist2 = newDist;', ' }', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.find (query1, dist1);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.find (query1, dist1);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.find (query2, dist2);', ' result2 = hisTree.find (query2, dist2);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimTopKQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, querySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.findKClosest (query1, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.findKClosest (query2, querySize);', ' result2 = hisTree.findKClosest (query2, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' ', ' /**', ' * "TIER 1" TESTS', ' * NONE OF THESE REQUIRE ANY SPLITS', ' */', ' public void testEasy1() {', ' testOneDimRangeQuery (true, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy2() {', ' testOneDimRangeQuery (false, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy3() {', ' testOneDimRangeQuery (true, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy4() {', ' testOneDimRangeQuery (false, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy5() {', ' testMultiDimRangeQuery (true, 1, 5, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy6() {', ' testMultiDimRangeQuery (false, 1, 10, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy7() {', ' testMultiDimRangeQuery (true, 1, 5, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy8() {', ' testMultiDimRangeQuery (false, 1, 15, 10000, 10000, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 2" TESTS', ' * NONE OF THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testMod1() {', ' testOneDimRangeQuery (true, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod2() {', ' testOneDimRangeQuery (false, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod3() {', ' testOneDimRangeQuery (true, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod4() {', ' testOneDimRangeQuery (false, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod5() {', ' testMultiDimRangeQuery (true, 2, 5, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod6() {', ' testMultiDimRangeQuery (false, 2, 10, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod7() {', ' testMultiDimRangeQuery (true, 2, 5, 10000, 100, 1000, 10);', ' }', ' ', ' public void testMod8() {', ' testMultiDimRangeQuery (false, 2, 15, 10000, 100, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 3" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testHard1() {', ' testOneDimRangeQuery (true, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard2() {', ' testOneDimRangeQuery (false, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard3() {', ' testOneDimRangeQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard4() {', ' testOneDimRangeQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard5() {', ' testMultiDimRangeQuery (true, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard6() {', ' testMultiDimRangeQuery (false, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard7() {', ' testMultiDimRangeQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard8() {', ' testMultiDimRangeQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', ' ', ' /**', ' * "TIER 4" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE AND THEY TEST THE TOPK FUNCTIONALITY', ' */', ' ', ' public void testTopK1() {', ' testOneDimTopKQuery (true, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK2() {', ' testOneDimTopKQuery (false, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK3() {', ' testOneDimTopKQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK4() {', ' testOneDimTopKQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK5() {', ' testMultiDimTopKQuery (true, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK6() {', ' testMultiDimTopKQuery (false, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK7() {', ' testMultiDimTopKQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK8() {', ' testMultiDimTopKQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', '}'] | [] | Global_Variable 'root' used at line 805 is defined at line 770 and has a Long-Range dependency. | {} | {'Global_Variable Long-Range': 1} |
infilling_java | FactorizationTester | 38 | 40 | ['import junit.framework.TestCase;', 'import java.io.ByteArrayOutputStream;', 'import java.io.PrintStream;', 'import java.lang.Math;', '', '/**', ' * This class implements a relatively simple algorithm for computing', ' * (and printing) the prime factors of a number. At initialization,', ' * a list of primes is computed. Given a number, this list is then', ' * used to efficiently print the prime factors of the number.', ' */', 'class PrimeFactorizer {', '', ' // this class will store all primes between 2 and upperBound', ' private int upperBound;', ' ', ' // this class will be able to factorize all primes between 1 and maxNumberToFactorize', ' private long maxNumberToFactorize;', ' ', ' // this is a list of all of the prime numbers between 2 and upperBound', ' private int [] allPrimes;', ' ', ' // this is the number of primes found between 2 and upperBound', ' private int numPrimes;', ' ', ' // this is the output stream that the factorization will be printed to', ' private PrintStream resultStream;', ' ', ' /**', ' * This prints the prime factorization of a number in a "pretty" fashion.', ' * If the number passed in exceeds "upperBound", then a nice error message', ' * is printed. ', ' */', ' public void printPrimeFactorization (long numToFactorize) {', ' ', " // If we are given a number that's too small/big to factor, tell the user", ' if (numToFactorize < 1) {'] | [' resultStream.format ("Can\'t factorize a number less than 1");', ' return;', ' }'] | [' if (numToFactorize > maxNumberToFactorize) {', ' resultStream.format ("%d is too large to factorize", numToFactorize);', ' return;', ' }', ' ', ' // Now get ready to print the factorization', ' resultStream.format ("Prime factorization of %d is: ", numToFactorize);', ' ', ' // our basic tactice will be to find all of the primes that divide evenly into', ' // our target. When we find one, print it out and reduce the target accrordingly.', ' // When the target gets down to one, we are done.', ' ', ' // this is the index of the next prime we need to try', ' int curPosInAllPrimes = 0;', ' ', ' // tells us we are still waiting to print the first prime... important so we', ' // don\'t print the "x" symbol before the first one', ' boolean firstOne = true;', ' ', ' while (numToFactorize > 1 && curPosInAllPrimes < numPrimes) {', ' ', " // if the current prime divides evenly into the target, we've got a prime factor", ' if (numToFactorize % allPrimes[curPosInAllPrimes] == 0) {', ' ', ' // if it\'s the first one, we don\'t need to print a "x"', ' // print the factor & reset the firstOne flag', ' if (firstOne) {', ' resultStream.format ("%d", allPrimes[curPosInAllPrimes]);', ' firstOne = false;', ' ', ' // otherwise, print the factor pre-pended with an "x"', ' } else {', ' resultStream.format (" x %d", allPrimes[curPosInAllPrimes]);', ' }', ' ', ' // remove that prime factor from the target', ' numToFactorize /= allPrimes[curPosInAllPrimes];', ' ', ' // if the current prime does not divde evenly, try the next one', ' } else {', ' curPosInAllPrimes++;', ' }', ' }', ' ', ' // if we never printed any factors, then display the number itself', ' if (firstOne) {', ' resultStream.format ("%d", numToFactorize);', " // Otherwsie print the factors connected by 'x'", ' } else if (numToFactorize > 1) {', ' resultStream.format (" x %d", numToFactorize);', ' }', ' }', ' ', ' ', ' /**', ' * This is the constructor. What it does is to fill the array allPrimes with all', ' * of the prime numbers from 2 through sqrt(maxNumberToFactorize). This array of primes', ' * can then subsequently be used by the printPrimeFactorization method to actually', ' * compute the prime factorization of a number. The method also sets upperBound', ' * (the largest number we checked for primality) and numPrimes (the number of primes', ' * in allPimes). The algorithm used to compute the primes is the classic "sieve of ', ' * Eratosthenes" algorithm.', ' */', ' public PrimeFactorizer (long maxNumberToFactorizeIn, PrintStream outputStream) {', ' ', ' resultStream = outputStream;', ' maxNumberToFactorize = maxNumberToFactorizeIn;', ' ', " // initialize the two class variables- 'upperBound' and 'allPrimes' note that the prime candidates are", ' // from 2 to upperBound, so there are upperBound prime candidates intially', ' upperBound = (int) Math.ceil (Math.sqrt (maxNumberToFactorize));', ' allPrimes = new int[upperBound - 1];', ' ', ' // numIntsInList is the number of ints currently in the list.', ' int numIntsInList = upperBound - 1;', ' ', ' // the number of primes so far is zero', ' numPrimes = 0;', ' ', ' // write all of the candidate numbers to the list... this is all of the numbers', ' // from two to upperBound', ' for (int i = 0; i < upperBound - 1; i++) {', ' allPrimes[i] = i + 2;', ' }', ' ', ' // now we keep removing numbers from the list until we have only primes', ' while (numIntsInList > numPrimes) {', ' ', ' // curPos tells us the last slot that has a "good" (still possibly prime) value.', ' int curPos = numPrimes + 1;', ' ', ' // the front of the list is a prime... kill everyone who is a multiple of it', ' for (int i = numPrimes + 1; i < numIntsInList; i++) {', ' ', ' // if the dude at position i is not a multiple of the current prime, then', " // we keep him; otherwise, he'll be lost", ' if (allPrimes[i] % allPrimes[numPrimes] != 0) {', ' allPrimes[curPos] = allPrimes[i];', ' curPos++;', ' }', ' }', ' ', ' // the number of ints in the list is now equal to the last slot we wrote a value to', ' numIntsInList = curPos;', ' ', ' // and the guy at the front of the list is now considered a prime', ' numPrimes++;', ' ', ' }', ' }', ' ', '', '}', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', ' ', 'public class FactorizationTester extends TestCase {', ' /**', ' * Stream to hold the result of each test.', ' */', ' private ByteArrayOutputStream result;', '', ' /**', ' * Wrapper to provide printing functionality.', ' */', ' private PrintStream outputStream;', '', ' /**', ' * Setup the output streams before each test.', ' */ ', ' protected void setUp () {', ' result = new ByteArrayOutputStream();', ' outputStream = new PrintStream(result);', ' } ', ' ', ' /**', ' * Print a nice message about each test.', ' */', ' private void printInfo(String description, String expected, String actual) {', ' System.out.format ("\\n%s\\n", description);', ' System.out.format ("output:\\t%s\\n", actual);', ' System.out.format ("correct:\\t%s\\n", expected);', ' }', '', ' /**', ' * These are the various test methods. The first 10 test factorizations', ' * using the object constructed to factorize numbers up to 100; the latter', ' * 7 use the object to factorize numbers up to 100000.', ' */', ' public void test100MaxFactorize1() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (1);', '', ' // Print Results', ' String expected = new String("Prime factorization of 1 is: 1");', ' printInfo("Factorizing 1 using max 100", expected, result.toString());', '', ' // Check if test passed by comparing the expected and actual results', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 7 ', ' public void test100MaxFactorize7() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (7);', '', ' // Print Results', ' String expected = new String("Prime factorization of 7 is: 7");', ' printInfo("Factorizing 7 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 5', ' public void test100MaxFactorize5() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (5);', '', ' // Print Results', ' String expected = new String("Prime factorization of 5 is: 5");', ' printInfo("Factorizing 5 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 30', ' public void test100MaxFactorize30() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (30);', '', ' // Print Results', ' String expected = new String("Prime factorization of 30 is: 2 x 3 x 5");', ' printInfo("Factorizing 30 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 81', ' public void test100MaxFactorize81() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (81);', '', ' // Print Results', ' String expected = new String("Prime factorization of 81 is: 3 x 3 x 3 x 3");', ' printInfo("Factorizing 81 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 71', ' public void test100MaxFactorize71() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (71);', '', ' // Print Results', ' String expected = new String("Prime factorization of 71 is: 71");', ' printInfo("Factorizing 71 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 100', ' public void test100MaxFactorize100() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (100);', '', ' // Print Results', ' String expected = new String("Prime factorization of 100 is: 2 x 2 x 5 x 5");', ' printInfo("Factorizing 100 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 101', ' public void test100MaxFactorize101() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (101);', '', ' // Print Results', ' String expected = new String("101 is too large to factorize");', ' printInfo("Factorizing 101 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 0', ' public void test100MaxFactorize0() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (0);', '', ' // Print Results', ' String expected = new String("Can\'t factorize a number less than 1");', ' printInfo("Factorizing 0 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' // Test the factorization of 97', ' public void test100MaxFactorize97() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (97);', '', ' // Print Results', ' String expected = new String("Prime factorization of 97 is: 97");', ' printInfo("Factorizing 97 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 34534', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize34534() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (34534);', '', ' // Print Results', ' String expected = new String("Prime factorization of 34534 is: 2 x 31 x 557");', ' printInfo("Factorizing 34534 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 4339', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize4339() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (4339);', '', ' // Print Results', ' String expected = new String("Prime factorization of 4339 is: 4339");', ' printInfo("Factorizing 4339 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 65536', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize65536() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (65536);', '', ' // Print Results', ' String expected = new String("Prime factorization of 65536 is: 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2");', ' printInfo("Factorizing 65536 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 99797', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize99797() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (99797);', '', ' // Print Results', ' String expected = new String("Prime factorization of 99797 is: 23 x 4339");', ' printInfo("Factorizing 99797 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 307', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize307() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (307);', '', ' // Print Results', ' String expected = new String("Prime factorization of 307 is: 307");', ' printInfo("Factorizing 307 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 38845248344', ' // factorize numbers up to 100000000000', ' public void test100000000000MaxFactorize38845248344() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000000 = new PrimeFactorizer(100000000000L, outputStream);', ' myFactorizerMax100000000000.printPrimeFactorization (38845248344L);', '', ' // Print Results', ' String expected = new String("Prime factorization of 38845248344 is: 2 x 2 x 2 x 7 x 693665149");', ' printInfo("Factorizing 38845248344 using max 100000000000", expected, result.toString());', ' ', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' ', ' result.reset ();', ' myFactorizerMax100000000000.printPrimeFactorization (24210833220L);', ' expected = new String("Prime factorization of 24210833220 is: 2 x 2 x 3 x 3 x 5 x 7 x 17 x 19 x 19 x 31 x 101");', ' printInfo("Factorizing 24210833220 using max 100000000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' public void test100000000000MaxFactorize5387457483444() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000000 = new PrimeFactorizer(100000000000L, outputStream);', ' myFactorizerMax100000000000.printPrimeFactorization (5387457483444L);', '', ' // Print Results', ' String expected = new String("5387457483444 is too large to factorize");', ' printInfo("Factorizing 5387457483444 using max 100000000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' public void testSpeed() {', ' ', ' // here we factorize 10,000 large numbers; make sure that the constructor correctly sets', " // up the array of primes just once... if it does not, it'll take too long to run", ' PrimeFactorizer myFactorizerMax100000000000 = new PrimeFactorizer(100000000000L, outputStream);', ' for (long i = 38845248344L; i < 38845248344L + 50000; i++) {', ' myFactorizerMax100000000000.printPrimeFactorization (i);', ' if (i == 38845248344L) {', ' // Compare the Prime factorization of 38845248344 to the expected result', ' String expected = new String("Prime factorization of 38845248344 is: 2 x 2 x 2 x 7 x 693665149"); ', ' assertEquals (expected, result.toString());', ' }', ' }', ' ', ' // if we make it here, we pass the test', ' assertTrue (true);', ' }', ' ', '}'] | [{'reason_category': 'If Body', 'usage_line': 38}, {'reason_category': 'If Body', 'usage_line': 39}, {'reason_category': 'If Body', 'usage_line': 40}] | Global_Variable 'resultStream' used at line 38 is defined at line 27 and has a Medium-Range dependency. | {'If Body': 3} | {'Global_Variable Medium-Range': 1} |
infilling_java | FactorizationTester | 63 | 83 | ['import junit.framework.TestCase;', 'import java.io.ByteArrayOutputStream;', 'import java.io.PrintStream;', 'import java.lang.Math;', '', '/**', ' * This class implements a relatively simple algorithm for computing', ' * (and printing) the prime factors of a number. At initialization,', ' * a list of primes is computed. Given a number, this list is then', ' * used to efficiently print the prime factors of the number.', ' */', 'class PrimeFactorizer {', '', ' // this class will store all primes between 2 and upperBound', ' private int upperBound;', ' ', ' // this class will be able to factorize all primes between 1 and maxNumberToFactorize', ' private long maxNumberToFactorize;', ' ', ' // this is a list of all of the prime numbers between 2 and upperBound', ' private int [] allPrimes;', ' ', ' // this is the number of primes found between 2 and upperBound', ' private int numPrimes;', ' ', ' // this is the output stream that the factorization will be printed to', ' private PrintStream resultStream;', ' ', ' /**', ' * This prints the prime factorization of a number in a "pretty" fashion.', ' * If the number passed in exceeds "upperBound", then a nice error message', ' * is printed. ', ' */', ' public void printPrimeFactorization (long numToFactorize) {', ' ', " // If we are given a number that's too small/big to factor, tell the user", ' if (numToFactorize < 1) {', ' resultStream.format ("Can\'t factorize a number less than 1");', ' return;', ' }', ' if (numToFactorize > maxNumberToFactorize) {', ' resultStream.format ("%d is too large to factorize", numToFactorize);', ' return;', ' }', ' ', ' // Now get ready to print the factorization', ' resultStream.format ("Prime factorization of %d is: ", numToFactorize);', ' ', ' // our basic tactice will be to find all of the primes that divide evenly into', ' // our target. When we find one, print it out and reduce the target accrordingly.', ' // When the target gets down to one, we are done.', ' ', ' // this is the index of the next prime we need to try', ' int curPosInAllPrimes = 0;', ' ', ' // tells us we are still waiting to print the first prime... important so we', ' // don\'t print the "x" symbol before the first one', ' boolean firstOne = true;', ' ', ' while (numToFactorize > 1 && curPosInAllPrimes < numPrimes) {', ' ', " // if the current prime divides evenly into the target, we've got a prime factor"] | [' if (numToFactorize % allPrimes[curPosInAllPrimes] == 0) {', ' ', ' // if it\'s the first one, we don\'t need to print a "x"', ' // print the factor & reset the firstOne flag', ' if (firstOne) {', ' resultStream.format ("%d", allPrimes[curPosInAllPrimes]);', ' firstOne = false;', ' ', ' // otherwise, print the factor pre-pended with an "x"', ' } else {', ' resultStream.format (" x %d", allPrimes[curPosInAllPrimes]);', ' }', ' ', ' // remove that prime factor from the target', ' numToFactorize /= allPrimes[curPosInAllPrimes];', ' ', ' // if the current prime does not divde evenly, try the next one', ' } else {', ' curPosInAllPrimes++;', ' }', ' }'] | [' ', ' // if we never printed any factors, then display the number itself', ' if (firstOne) {', ' resultStream.format ("%d", numToFactorize);', " // Otherwsie print the factors connected by 'x'", ' } else if (numToFactorize > 1) {', ' resultStream.format (" x %d", numToFactorize);', ' }', ' }', ' ', ' ', ' /**', ' * This is the constructor. What it does is to fill the array allPrimes with all', ' * of the prime numbers from 2 through sqrt(maxNumberToFactorize). This array of primes', ' * can then subsequently be used by the printPrimeFactorization method to actually', ' * compute the prime factorization of a number. The method also sets upperBound', ' * (the largest number we checked for primality) and numPrimes (the number of primes', ' * in allPimes). The algorithm used to compute the primes is the classic "sieve of ', ' * Eratosthenes" algorithm.', ' */', ' public PrimeFactorizer (long maxNumberToFactorizeIn, PrintStream outputStream) {', ' ', ' resultStream = outputStream;', ' maxNumberToFactorize = maxNumberToFactorizeIn;', ' ', " // initialize the two class variables- 'upperBound' and 'allPrimes' note that the prime candidates are", ' // from 2 to upperBound, so there are upperBound prime candidates intially', ' upperBound = (int) Math.ceil (Math.sqrt (maxNumberToFactorize));', ' allPrimes = new int[upperBound - 1];', ' ', ' // numIntsInList is the number of ints currently in the list.', ' int numIntsInList = upperBound - 1;', ' ', ' // the number of primes so far is zero', ' numPrimes = 0;', ' ', ' // write all of the candidate numbers to the list... this is all of the numbers', ' // from two to upperBound', ' for (int i = 0; i < upperBound - 1; i++) {', ' allPrimes[i] = i + 2;', ' }', ' ', ' // now we keep removing numbers from the list until we have only primes', ' while (numIntsInList > numPrimes) {', ' ', ' // curPos tells us the last slot that has a "good" (still possibly prime) value.', ' int curPos = numPrimes + 1;', ' ', ' // the front of the list is a prime... kill everyone who is a multiple of it', ' for (int i = numPrimes + 1; i < numIntsInList; i++) {', ' ', ' // if the dude at position i is not a multiple of the current prime, then', " // we keep him; otherwise, he'll be lost", ' if (allPrimes[i] % allPrimes[numPrimes] != 0) {', ' allPrimes[curPos] = allPrimes[i];', ' curPos++;', ' }', ' }', ' ', ' // the number of ints in the list is now equal to the last slot we wrote a value to', ' numIntsInList = curPos;', ' ', ' // and the guy at the front of the list is now considered a prime', ' numPrimes++;', ' ', ' }', ' }', ' ', '', '}', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', ' ', 'public class FactorizationTester extends TestCase {', ' /**', ' * Stream to hold the result of each test.', ' */', ' private ByteArrayOutputStream result;', '', ' /**', ' * Wrapper to provide printing functionality.', ' */', ' private PrintStream outputStream;', '', ' /**', ' * Setup the output streams before each test.', ' */ ', ' protected void setUp () {', ' result = new ByteArrayOutputStream();', ' outputStream = new PrintStream(result);', ' } ', ' ', ' /**', ' * Print a nice message about each test.', ' */', ' private void printInfo(String description, String expected, String actual) {', ' System.out.format ("\\n%s\\n", description);', ' System.out.format ("output:\\t%s\\n", actual);', ' System.out.format ("correct:\\t%s\\n", expected);', ' }', '', ' /**', ' * These are the various test methods. The first 10 test factorizations', ' * using the object constructed to factorize numbers up to 100; the latter', ' * 7 use the object to factorize numbers up to 100000.', ' */', ' public void test100MaxFactorize1() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (1);', '', ' // Print Results', ' String expected = new String("Prime factorization of 1 is: 1");', ' printInfo("Factorizing 1 using max 100", expected, result.toString());', '', ' // Check if test passed by comparing the expected and actual results', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 7 ', ' public void test100MaxFactorize7() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (7);', '', ' // Print Results', ' String expected = new String("Prime factorization of 7 is: 7");', ' printInfo("Factorizing 7 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 5', ' public void test100MaxFactorize5() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (5);', '', ' // Print Results', ' String expected = new String("Prime factorization of 5 is: 5");', ' printInfo("Factorizing 5 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 30', ' public void test100MaxFactorize30() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (30);', '', ' // Print Results', ' String expected = new String("Prime factorization of 30 is: 2 x 3 x 5");', ' printInfo("Factorizing 30 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 81', ' public void test100MaxFactorize81() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (81);', '', ' // Print Results', ' String expected = new String("Prime factorization of 81 is: 3 x 3 x 3 x 3");', ' printInfo("Factorizing 81 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 71', ' public void test100MaxFactorize71() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (71);', '', ' // Print Results', ' String expected = new String("Prime factorization of 71 is: 71");', ' printInfo("Factorizing 71 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 100', ' public void test100MaxFactorize100() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (100);', '', ' // Print Results', ' String expected = new String("Prime factorization of 100 is: 2 x 2 x 5 x 5");', ' printInfo("Factorizing 100 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 101', ' public void test100MaxFactorize101() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (101);', '', ' // Print Results', ' String expected = new String("101 is too large to factorize");', ' printInfo("Factorizing 101 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 0', ' public void test100MaxFactorize0() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (0);', '', ' // Print Results', ' String expected = new String("Can\'t factorize a number less than 1");', ' printInfo("Factorizing 0 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' // Test the factorization of 97', ' public void test100MaxFactorize97() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (97);', '', ' // Print Results', ' String expected = new String("Prime factorization of 97 is: 97");', ' printInfo("Factorizing 97 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 34534', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize34534() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (34534);', '', ' // Print Results', ' String expected = new String("Prime factorization of 34534 is: 2 x 31 x 557");', ' printInfo("Factorizing 34534 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 4339', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize4339() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (4339);', '', ' // Print Results', ' String expected = new String("Prime factorization of 4339 is: 4339");', ' printInfo("Factorizing 4339 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 65536', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize65536() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (65536);', '', ' // Print Results', ' String expected = new String("Prime factorization of 65536 is: 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2");', ' printInfo("Factorizing 65536 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 99797', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize99797() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (99797);', '', ' // Print Results', ' String expected = new String("Prime factorization of 99797 is: 23 x 4339");', ' printInfo("Factorizing 99797 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 307', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize307() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (307);', '', ' // Print Results', ' String expected = new String("Prime factorization of 307 is: 307");', ' printInfo("Factorizing 307 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 38845248344', ' // factorize numbers up to 100000000000', ' public void test100000000000MaxFactorize38845248344() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000000 = new PrimeFactorizer(100000000000L, outputStream);', ' myFactorizerMax100000000000.printPrimeFactorization (38845248344L);', '', ' // Print Results', ' String expected = new String("Prime factorization of 38845248344 is: 2 x 2 x 2 x 7 x 693665149");', ' printInfo("Factorizing 38845248344 using max 100000000000", expected, result.toString());', ' ', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' ', ' result.reset ();', ' myFactorizerMax100000000000.printPrimeFactorization (24210833220L);', ' expected = new String("Prime factorization of 24210833220 is: 2 x 2 x 3 x 3 x 5 x 7 x 17 x 19 x 19 x 31 x 101");', ' printInfo("Factorizing 24210833220 using max 100000000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' public void test100000000000MaxFactorize5387457483444() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000000 = new PrimeFactorizer(100000000000L, outputStream);', ' myFactorizerMax100000000000.printPrimeFactorization (5387457483444L);', '', ' // Print Results', ' String expected = new String("5387457483444 is too large to factorize");', ' printInfo("Factorizing 5387457483444 using max 100000000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' public void testSpeed() {', ' ', ' // here we factorize 10,000 large numbers; make sure that the constructor correctly sets', " // up the array of primes just once... if it does not, it'll take too long to run", ' PrimeFactorizer myFactorizerMax100000000000 = new PrimeFactorizer(100000000000L, outputStream);', ' for (long i = 38845248344L; i < 38845248344L + 50000; i++) {', ' myFactorizerMax100000000000.printPrimeFactorization (i);', ' if (i == 38845248344L) {', ' // Compare the Prime factorization of 38845248344 to the expected result', ' String expected = new String("Prime factorization of 38845248344 is: 2 x 2 x 2 x 7 x 693665149"); ', ' assertEquals (expected, result.toString());', ' }', ' }', ' ', ' // if we make it here, we pass the test', ' assertTrue (true);', ' }', ' ', '}'] | [{'reason_category': 'Loop Body', 'usage_line': 63}, {'reason_category': 'If Condition', 'usage_line': 63}, {'reason_category': 'Loop Body', 'usage_line': 64}, {'reason_category': 'If Body', 'usage_line': 64}, {'reason_category': 'Loop Body', 'usage_line': 65}, {'reason_category': 'If Body', 'usage_line': 65}, {'reason_category': 'Loop Body', 'usage_line': 66}, {'reason_category': 'If Body', 'usage_line': 66}, {'reason_category': 'Loop Body', 'usage_line': 67}, {'reason_category': 'If Body', 'usage_line': 67}, {'reason_category': 'If Condition', 'usage_line': 67}, {'reason_category': 'Loop Body', 'usage_line': 68}, {'reason_category': 'If Body', 'usage_line': 68}, {'reason_category': 'Loop Body', 'usage_line': 69}, {'reason_category': 'If Body', 'usage_line': 69}, {'reason_category': 'Loop Body', 'usage_line': 70}, {'reason_category': 'If Body', 'usage_line': 70}, {'reason_category': 'Loop Body', 'usage_line': 71}, {'reason_category': 'If Body', 'usage_line': 71}, {'reason_category': 'Loop Body', 'usage_line': 72}, {'reason_category': 'If Body', 'usage_line': 72}, {'reason_category': 'Else Reasoning', 'usage_line': 72}, {'reason_category': 'Loop Body', 'usage_line': 73}, {'reason_category': 'If Body', 'usage_line': 73}, {'reason_category': 'Else Reasoning', 'usage_line': 73}, {'reason_category': 'Loop Body', 'usage_line': 74}, {'reason_category': 'If Body', 'usage_line': 74}, {'reason_category': 'Else Reasoning', 'usage_line': 74}, {'reason_category': 'Loop Body', 'usage_line': 75}, {'reason_category': 'If Body', 'usage_line': 75}, {'reason_category': 'Loop Body', 'usage_line': 76}, {'reason_category': 'If Body', 'usage_line': 76}, {'reason_category': 'Loop Body', 'usage_line': 77}, {'reason_category': 'If Body', 'usage_line': 77}, {'reason_category': 'Loop Body', 'usage_line': 78}, {'reason_category': 'Loop Body', 'usage_line': 79}, {'reason_category': 'Loop Body', 'usage_line': 80}, {'reason_category': 'Else Reasoning', 'usage_line': 80}, {'reason_category': 'Loop Body', 'usage_line': 81}, {'reason_category': 'Else Reasoning', 'usage_line': 81}, {'reason_category': 'Loop Body', 'usage_line': 82}, {'reason_category': 'Else Reasoning', 'usage_line': 82}, {'reason_category': 'Loop Body', 'usage_line': 83}] | Variable 'numToFactorize' used at line 63 is defined at line 34 and has a Medium-Range dependency.
Global_Variable 'allPrimes' used at line 63 is defined at line 21 and has a Long-Range dependency.
Variable 'curPosInAllPrimes' used at line 63 is defined at line 54 and has a Short-Range dependency.
Variable 'firstOne' used at line 67 is defined at line 58 and has a Short-Range dependency.
Global_Variable 'resultStream' used at line 68 is defined at line 27 and has a Long-Range dependency.
Global_Variable 'allPrimes' used at line 68 is defined at line 21 and has a Long-Range dependency.
Variable 'curPosInAllPrimes' used at line 68 is defined at line 54 and has a Medium-Range dependency.
Variable 'firstOne' used at line 69 is defined at line 58 and has a Medium-Range dependency.
Global_Variable 'resultStream' used at line 73 is defined at line 27 and has a Long-Range dependency.
Global_Variable 'allPrimes' used at line 73 is defined at line 21 and has a Long-Range dependency.
Variable 'curPosInAllPrimes' used at line 73 is defined at line 54 and has a Medium-Range dependency.
Global_Variable 'allPrimes' used at line 77 is defined at line 21 and has a Long-Range dependency.
Variable 'curPosInAllPrimes' used at line 77 is defined at line 54 and has a Medium-Range dependency.
Variable 'numToFactorize' used at line 77 is defined at line 34 and has a Long-Range dependency.
Variable 'curPosInAllPrimes' used at line 81 is defined at line 54 and has a Medium-Range dependency. | {'Loop Body': 21, 'If Condition': 2, 'If Body': 14, 'Else Reasoning': 6} | {'Variable Medium-Range': 6, 'Global_Variable Long-Range': 6, 'Variable Short-Range': 2, 'Variable Long-Range': 1} |
infilling_java | FactorizationTester | 68 | 69 | ['import junit.framework.TestCase;', 'import java.io.ByteArrayOutputStream;', 'import java.io.PrintStream;', 'import java.lang.Math;', '', '/**', ' * This class implements a relatively simple algorithm for computing', ' * (and printing) the prime factors of a number. At initialization,', ' * a list of primes is computed. Given a number, this list is then', ' * used to efficiently print the prime factors of the number.', ' */', 'class PrimeFactorizer {', '', ' // this class will store all primes between 2 and upperBound', ' private int upperBound;', ' ', ' // this class will be able to factorize all primes between 1 and maxNumberToFactorize', ' private long maxNumberToFactorize;', ' ', ' // this is a list of all of the prime numbers between 2 and upperBound', ' private int [] allPrimes;', ' ', ' // this is the number of primes found between 2 and upperBound', ' private int numPrimes;', ' ', ' // this is the output stream that the factorization will be printed to', ' private PrintStream resultStream;', ' ', ' /**', ' * This prints the prime factorization of a number in a "pretty" fashion.', ' * If the number passed in exceeds "upperBound", then a nice error message', ' * is printed. ', ' */', ' public void printPrimeFactorization (long numToFactorize) {', ' ', " // If we are given a number that's too small/big to factor, tell the user", ' if (numToFactorize < 1) {', ' resultStream.format ("Can\'t factorize a number less than 1");', ' return;', ' }', ' if (numToFactorize > maxNumberToFactorize) {', ' resultStream.format ("%d is too large to factorize", numToFactorize);', ' return;', ' }', ' ', ' // Now get ready to print the factorization', ' resultStream.format ("Prime factorization of %d is: ", numToFactorize);', ' ', ' // our basic tactice will be to find all of the primes that divide evenly into', ' // our target. When we find one, print it out and reduce the target accrordingly.', ' // When the target gets down to one, we are done.', ' ', ' // this is the index of the next prime we need to try', ' int curPosInAllPrimes = 0;', ' ', ' // tells us we are still waiting to print the first prime... important so we', ' // don\'t print the "x" symbol before the first one', ' boolean firstOne = true;', ' ', ' while (numToFactorize > 1 && curPosInAllPrimes < numPrimes) {', ' ', " // if the current prime divides evenly into the target, we've got a prime factor", ' if (numToFactorize % allPrimes[curPosInAllPrimes] == 0) {', ' ', ' // if it\'s the first one, we don\'t need to print a "x"', ' // print the factor & reset the firstOne flag', ' if (firstOne) {'] | [' resultStream.format ("%d", allPrimes[curPosInAllPrimes]);', ' firstOne = false;'] | [' ', ' // otherwise, print the factor pre-pended with an "x"', ' } else {', ' resultStream.format (" x %d", allPrimes[curPosInAllPrimes]);', ' }', ' ', ' // remove that prime factor from the target', ' numToFactorize /= allPrimes[curPosInAllPrimes];', ' ', ' // if the current prime does not divde evenly, try the next one', ' } else {', ' curPosInAllPrimes++;', ' }', ' }', ' ', ' // if we never printed any factors, then display the number itself', ' if (firstOne) {', ' resultStream.format ("%d", numToFactorize);', " // Otherwsie print the factors connected by 'x'", ' } else if (numToFactorize > 1) {', ' resultStream.format (" x %d", numToFactorize);', ' }', ' }', ' ', ' ', ' /**', ' * This is the constructor. What it does is to fill the array allPrimes with all', ' * of the prime numbers from 2 through sqrt(maxNumberToFactorize). This array of primes', ' * can then subsequently be used by the printPrimeFactorization method to actually', ' * compute the prime factorization of a number. The method also sets upperBound', ' * (the largest number we checked for primality) and numPrimes (the number of primes', ' * in allPimes). The algorithm used to compute the primes is the classic "sieve of ', ' * Eratosthenes" algorithm.', ' */', ' public PrimeFactorizer (long maxNumberToFactorizeIn, PrintStream outputStream) {', ' ', ' resultStream = outputStream;', ' maxNumberToFactorize = maxNumberToFactorizeIn;', ' ', " // initialize the two class variables- 'upperBound' and 'allPrimes' note that the prime candidates are", ' // from 2 to upperBound, so there are upperBound prime candidates intially', ' upperBound = (int) Math.ceil (Math.sqrt (maxNumberToFactorize));', ' allPrimes = new int[upperBound - 1];', ' ', ' // numIntsInList is the number of ints currently in the list.', ' int numIntsInList = upperBound - 1;', ' ', ' // the number of primes so far is zero', ' numPrimes = 0;', ' ', ' // write all of the candidate numbers to the list... this is all of the numbers', ' // from two to upperBound', ' for (int i = 0; i < upperBound - 1; i++) {', ' allPrimes[i] = i + 2;', ' }', ' ', ' // now we keep removing numbers from the list until we have only primes', ' while (numIntsInList > numPrimes) {', ' ', ' // curPos tells us the last slot that has a "good" (still possibly prime) value.', ' int curPos = numPrimes + 1;', ' ', ' // the front of the list is a prime... kill everyone who is a multiple of it', ' for (int i = numPrimes + 1; i < numIntsInList; i++) {', ' ', ' // if the dude at position i is not a multiple of the current prime, then', " // we keep him; otherwise, he'll be lost", ' if (allPrimes[i] % allPrimes[numPrimes] != 0) {', ' allPrimes[curPos] = allPrimes[i];', ' curPos++;', ' }', ' }', ' ', ' // the number of ints in the list is now equal to the last slot we wrote a value to', ' numIntsInList = curPos;', ' ', ' // and the guy at the front of the list is now considered a prime', ' numPrimes++;', ' ', ' }', ' }', ' ', '', '}', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', ' ', 'public class FactorizationTester extends TestCase {', ' /**', ' * Stream to hold the result of each test.', ' */', ' private ByteArrayOutputStream result;', '', ' /**', ' * Wrapper to provide printing functionality.', ' */', ' private PrintStream outputStream;', '', ' /**', ' * Setup the output streams before each test.', ' */ ', ' protected void setUp () {', ' result = new ByteArrayOutputStream();', ' outputStream = new PrintStream(result);', ' } ', ' ', ' /**', ' * Print a nice message about each test.', ' */', ' private void printInfo(String description, String expected, String actual) {', ' System.out.format ("\\n%s\\n", description);', ' System.out.format ("output:\\t%s\\n", actual);', ' System.out.format ("correct:\\t%s\\n", expected);', ' }', '', ' /**', ' * These are the various test methods. The first 10 test factorizations', ' * using the object constructed to factorize numbers up to 100; the latter', ' * 7 use the object to factorize numbers up to 100000.', ' */', ' public void test100MaxFactorize1() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (1);', '', ' // Print Results', ' String expected = new String("Prime factorization of 1 is: 1");', ' printInfo("Factorizing 1 using max 100", expected, result.toString());', '', ' // Check if test passed by comparing the expected and actual results', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 7 ', ' public void test100MaxFactorize7() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (7);', '', ' // Print Results', ' String expected = new String("Prime factorization of 7 is: 7");', ' printInfo("Factorizing 7 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 5', ' public void test100MaxFactorize5() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (5);', '', ' // Print Results', ' String expected = new String("Prime factorization of 5 is: 5");', ' printInfo("Factorizing 5 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 30', ' public void test100MaxFactorize30() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (30);', '', ' // Print Results', ' String expected = new String("Prime factorization of 30 is: 2 x 3 x 5");', ' printInfo("Factorizing 30 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 81', ' public void test100MaxFactorize81() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (81);', '', ' // Print Results', ' String expected = new String("Prime factorization of 81 is: 3 x 3 x 3 x 3");', ' printInfo("Factorizing 81 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 71', ' public void test100MaxFactorize71() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (71);', '', ' // Print Results', ' String expected = new String("Prime factorization of 71 is: 71");', ' printInfo("Factorizing 71 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 100', ' public void test100MaxFactorize100() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (100);', '', ' // Print Results', ' String expected = new String("Prime factorization of 100 is: 2 x 2 x 5 x 5");', ' printInfo("Factorizing 100 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 101', ' public void test100MaxFactorize101() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (101);', '', ' // Print Results', ' String expected = new String("101 is too large to factorize");', ' printInfo("Factorizing 101 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 0', ' public void test100MaxFactorize0() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (0);', '', ' // Print Results', ' String expected = new String("Can\'t factorize a number less than 1");', ' printInfo("Factorizing 0 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' // Test the factorization of 97', ' public void test100MaxFactorize97() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (97);', '', ' // Print Results', ' String expected = new String("Prime factorization of 97 is: 97");', ' printInfo("Factorizing 97 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 34534', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize34534() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (34534);', '', ' // Print Results', ' String expected = new String("Prime factorization of 34534 is: 2 x 31 x 557");', ' printInfo("Factorizing 34534 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 4339', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize4339() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (4339);', '', ' // Print Results', ' String expected = new String("Prime factorization of 4339 is: 4339");', ' printInfo("Factorizing 4339 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 65536', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize65536() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (65536);', '', ' // Print Results', ' String expected = new String("Prime factorization of 65536 is: 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2");', ' printInfo("Factorizing 65536 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 99797', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize99797() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (99797);', '', ' // Print Results', ' String expected = new String("Prime factorization of 99797 is: 23 x 4339");', ' printInfo("Factorizing 99797 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 307', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize307() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (307);', '', ' // Print Results', ' String expected = new String("Prime factorization of 307 is: 307");', ' printInfo("Factorizing 307 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 38845248344', ' // factorize numbers up to 100000000000', ' public void test100000000000MaxFactorize38845248344() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000000 = new PrimeFactorizer(100000000000L, outputStream);', ' myFactorizerMax100000000000.printPrimeFactorization (38845248344L);', '', ' // Print Results', ' String expected = new String("Prime factorization of 38845248344 is: 2 x 2 x 2 x 7 x 693665149");', ' printInfo("Factorizing 38845248344 using max 100000000000", expected, result.toString());', ' ', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' ', ' result.reset ();', ' myFactorizerMax100000000000.printPrimeFactorization (24210833220L);', ' expected = new String("Prime factorization of 24210833220 is: 2 x 2 x 3 x 3 x 5 x 7 x 17 x 19 x 19 x 31 x 101");', ' printInfo("Factorizing 24210833220 using max 100000000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' public void test100000000000MaxFactorize5387457483444() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000000 = new PrimeFactorizer(100000000000L, outputStream);', ' myFactorizerMax100000000000.printPrimeFactorization (5387457483444L);', '', ' // Print Results', ' String expected = new String("5387457483444 is too large to factorize");', ' printInfo("Factorizing 5387457483444 using max 100000000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' public void testSpeed() {', ' ', ' // here we factorize 10,000 large numbers; make sure that the constructor correctly sets', " // up the array of primes just once... if it does not, it'll take too long to run", ' PrimeFactorizer myFactorizerMax100000000000 = new PrimeFactorizer(100000000000L, outputStream);', ' for (long i = 38845248344L; i < 38845248344L + 50000; i++) {', ' myFactorizerMax100000000000.printPrimeFactorization (i);', ' if (i == 38845248344L) {', ' // Compare the Prime factorization of 38845248344 to the expected result', ' String expected = new String("Prime factorization of 38845248344 is: 2 x 2 x 2 x 7 x 693665149"); ', ' assertEquals (expected, result.toString());', ' }', ' }', ' ', ' // if we make it here, we pass the test', ' assertTrue (true);', ' }', ' ', '}'] | [{'reason_category': 'Loop Body', 'usage_line': 68}, {'reason_category': 'If Body', 'usage_line': 68}, {'reason_category': 'Loop Body', 'usage_line': 69}, {'reason_category': 'If Body', 'usage_line': 69}] | Global_Variable 'resultStream' used at line 68 is defined at line 27 and has a Long-Range dependency.
Global_Variable 'allPrimes' used at line 68 is defined at line 21 and has a Long-Range dependency.
Variable 'curPosInAllPrimes' used at line 68 is defined at line 54 and has a Medium-Range dependency.
Variable 'firstOne' used at line 69 is defined at line 58 and has a Medium-Range dependency. | {'Loop Body': 2, 'If Body': 2} | {'Global_Variable Long-Range': 2, 'Variable Medium-Range': 2} |
infilling_java | FactorizationTester | 73 | 74 | ['import junit.framework.TestCase;', 'import java.io.ByteArrayOutputStream;', 'import java.io.PrintStream;', 'import java.lang.Math;', '', '/**', ' * This class implements a relatively simple algorithm for computing', ' * (and printing) the prime factors of a number. At initialization,', ' * a list of primes is computed. Given a number, this list is then', ' * used to efficiently print the prime factors of the number.', ' */', 'class PrimeFactorizer {', '', ' // this class will store all primes between 2 and upperBound', ' private int upperBound;', ' ', ' // this class will be able to factorize all primes between 1 and maxNumberToFactorize', ' private long maxNumberToFactorize;', ' ', ' // this is a list of all of the prime numbers between 2 and upperBound', ' private int [] allPrimes;', ' ', ' // this is the number of primes found between 2 and upperBound', ' private int numPrimes;', ' ', ' // this is the output stream that the factorization will be printed to', ' private PrintStream resultStream;', ' ', ' /**', ' * This prints the prime factorization of a number in a "pretty" fashion.', ' * If the number passed in exceeds "upperBound", then a nice error message', ' * is printed. ', ' */', ' public void printPrimeFactorization (long numToFactorize) {', ' ', " // If we are given a number that's too small/big to factor, tell the user", ' if (numToFactorize < 1) {', ' resultStream.format ("Can\'t factorize a number less than 1");', ' return;', ' }', ' if (numToFactorize > maxNumberToFactorize) {', ' resultStream.format ("%d is too large to factorize", numToFactorize);', ' return;', ' }', ' ', ' // Now get ready to print the factorization', ' resultStream.format ("Prime factorization of %d is: ", numToFactorize);', ' ', ' // our basic tactice will be to find all of the primes that divide evenly into', ' // our target. When we find one, print it out and reduce the target accrordingly.', ' // When the target gets down to one, we are done.', ' ', ' // this is the index of the next prime we need to try', ' int curPosInAllPrimes = 0;', ' ', ' // tells us we are still waiting to print the first prime... important so we', ' // don\'t print the "x" symbol before the first one', ' boolean firstOne = true;', ' ', ' while (numToFactorize > 1 && curPosInAllPrimes < numPrimes) {', ' ', " // if the current prime divides evenly into the target, we've got a prime factor", ' if (numToFactorize % allPrimes[curPosInAllPrimes] == 0) {', ' ', ' // if it\'s the first one, we don\'t need to print a "x"', ' // print the factor & reset the firstOne flag', ' if (firstOne) {', ' resultStream.format ("%d", allPrimes[curPosInAllPrimes]);', ' firstOne = false;', ' ', ' // otherwise, print the factor pre-pended with an "x"', ' } else {'] | [' resultStream.format (" x %d", allPrimes[curPosInAllPrimes]);', ' }'] | [' ', ' // remove that prime factor from the target', ' numToFactorize /= allPrimes[curPosInAllPrimes];', ' ', ' // if the current prime does not divde evenly, try the next one', ' } else {', ' curPosInAllPrimes++;', ' }', ' }', ' ', ' // if we never printed any factors, then display the number itself', ' if (firstOne) {', ' resultStream.format ("%d", numToFactorize);', " // Otherwsie print the factors connected by 'x'", ' } else if (numToFactorize > 1) {', ' resultStream.format (" x %d", numToFactorize);', ' }', ' }', ' ', ' ', ' /**', ' * This is the constructor. What it does is to fill the array allPrimes with all', ' * of the prime numbers from 2 through sqrt(maxNumberToFactorize). This array of primes', ' * can then subsequently be used by the printPrimeFactorization method to actually', ' * compute the prime factorization of a number. The method also sets upperBound', ' * (the largest number we checked for primality) and numPrimes (the number of primes', ' * in allPimes). The algorithm used to compute the primes is the classic "sieve of ', ' * Eratosthenes" algorithm.', ' */', ' public PrimeFactorizer (long maxNumberToFactorizeIn, PrintStream outputStream) {', ' ', ' resultStream = outputStream;', ' maxNumberToFactorize = maxNumberToFactorizeIn;', ' ', " // initialize the two class variables- 'upperBound' and 'allPrimes' note that the prime candidates are", ' // from 2 to upperBound, so there are upperBound prime candidates intially', ' upperBound = (int) Math.ceil (Math.sqrt (maxNumberToFactorize));', ' allPrimes = new int[upperBound - 1];', ' ', ' // numIntsInList is the number of ints currently in the list.', ' int numIntsInList = upperBound - 1;', ' ', ' // the number of primes so far is zero', ' numPrimes = 0;', ' ', ' // write all of the candidate numbers to the list... this is all of the numbers', ' // from two to upperBound', ' for (int i = 0; i < upperBound - 1; i++) {', ' allPrimes[i] = i + 2;', ' }', ' ', ' // now we keep removing numbers from the list until we have only primes', ' while (numIntsInList > numPrimes) {', ' ', ' // curPos tells us the last slot that has a "good" (still possibly prime) value.', ' int curPos = numPrimes + 1;', ' ', ' // the front of the list is a prime... kill everyone who is a multiple of it', ' for (int i = numPrimes + 1; i < numIntsInList; i++) {', ' ', ' // if the dude at position i is not a multiple of the current prime, then', " // we keep him; otherwise, he'll be lost", ' if (allPrimes[i] % allPrimes[numPrimes] != 0) {', ' allPrimes[curPos] = allPrimes[i];', ' curPos++;', ' }', ' }', ' ', ' // the number of ints in the list is now equal to the last slot we wrote a value to', ' numIntsInList = curPos;', ' ', ' // and the guy at the front of the list is now considered a prime', ' numPrimes++;', ' ', ' }', ' }', ' ', '', '}', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', ' ', 'public class FactorizationTester extends TestCase {', ' /**', ' * Stream to hold the result of each test.', ' */', ' private ByteArrayOutputStream result;', '', ' /**', ' * Wrapper to provide printing functionality.', ' */', ' private PrintStream outputStream;', '', ' /**', ' * Setup the output streams before each test.', ' */ ', ' protected void setUp () {', ' result = new ByteArrayOutputStream();', ' outputStream = new PrintStream(result);', ' } ', ' ', ' /**', ' * Print a nice message about each test.', ' */', ' private void printInfo(String description, String expected, String actual) {', ' System.out.format ("\\n%s\\n", description);', ' System.out.format ("output:\\t%s\\n", actual);', ' System.out.format ("correct:\\t%s\\n", expected);', ' }', '', ' /**', ' * These are the various test methods. The first 10 test factorizations', ' * using the object constructed to factorize numbers up to 100; the latter', ' * 7 use the object to factorize numbers up to 100000.', ' */', ' public void test100MaxFactorize1() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (1);', '', ' // Print Results', ' String expected = new String("Prime factorization of 1 is: 1");', ' printInfo("Factorizing 1 using max 100", expected, result.toString());', '', ' // Check if test passed by comparing the expected and actual results', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 7 ', ' public void test100MaxFactorize7() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (7);', '', ' // Print Results', ' String expected = new String("Prime factorization of 7 is: 7");', ' printInfo("Factorizing 7 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 5', ' public void test100MaxFactorize5() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (5);', '', ' // Print Results', ' String expected = new String("Prime factorization of 5 is: 5");', ' printInfo("Factorizing 5 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 30', ' public void test100MaxFactorize30() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (30);', '', ' // Print Results', ' String expected = new String("Prime factorization of 30 is: 2 x 3 x 5");', ' printInfo("Factorizing 30 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 81', ' public void test100MaxFactorize81() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (81);', '', ' // Print Results', ' String expected = new String("Prime factorization of 81 is: 3 x 3 x 3 x 3");', ' printInfo("Factorizing 81 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 71', ' public void test100MaxFactorize71() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (71);', '', ' // Print Results', ' String expected = new String("Prime factorization of 71 is: 71");', ' printInfo("Factorizing 71 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 100', ' public void test100MaxFactorize100() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (100);', '', ' // Print Results', ' String expected = new String("Prime factorization of 100 is: 2 x 2 x 5 x 5");', ' printInfo("Factorizing 100 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 101', ' public void test100MaxFactorize101() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (101);', '', ' // Print Results', ' String expected = new String("101 is too large to factorize");', ' printInfo("Factorizing 101 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 0', ' public void test100MaxFactorize0() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (0);', '', ' // Print Results', ' String expected = new String("Can\'t factorize a number less than 1");', ' printInfo("Factorizing 0 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' // Test the factorization of 97', ' public void test100MaxFactorize97() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (97);', '', ' // Print Results', ' String expected = new String("Prime factorization of 97 is: 97");', ' printInfo("Factorizing 97 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 34534', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize34534() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (34534);', '', ' // Print Results', ' String expected = new String("Prime factorization of 34534 is: 2 x 31 x 557");', ' printInfo("Factorizing 34534 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 4339', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize4339() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (4339);', '', ' // Print Results', ' String expected = new String("Prime factorization of 4339 is: 4339");', ' printInfo("Factorizing 4339 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 65536', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize65536() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (65536);', '', ' // Print Results', ' String expected = new String("Prime factorization of 65536 is: 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2");', ' printInfo("Factorizing 65536 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 99797', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize99797() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (99797);', '', ' // Print Results', ' String expected = new String("Prime factorization of 99797 is: 23 x 4339");', ' printInfo("Factorizing 99797 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 307', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize307() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (307);', '', ' // Print Results', ' String expected = new String("Prime factorization of 307 is: 307");', ' printInfo("Factorizing 307 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 38845248344', ' // factorize numbers up to 100000000000', ' public void test100000000000MaxFactorize38845248344() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000000 = new PrimeFactorizer(100000000000L, outputStream);', ' myFactorizerMax100000000000.printPrimeFactorization (38845248344L);', '', ' // Print Results', ' String expected = new String("Prime factorization of 38845248344 is: 2 x 2 x 2 x 7 x 693665149");', ' printInfo("Factorizing 38845248344 using max 100000000000", expected, result.toString());', ' ', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' ', ' result.reset ();', ' myFactorizerMax100000000000.printPrimeFactorization (24210833220L);', ' expected = new String("Prime factorization of 24210833220 is: 2 x 2 x 3 x 3 x 5 x 7 x 17 x 19 x 19 x 31 x 101");', ' printInfo("Factorizing 24210833220 using max 100000000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' public void test100000000000MaxFactorize5387457483444() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000000 = new PrimeFactorizer(100000000000L, outputStream);', ' myFactorizerMax100000000000.printPrimeFactorization (5387457483444L);', '', ' // Print Results', ' String expected = new String("5387457483444 is too large to factorize");', ' printInfo("Factorizing 5387457483444 using max 100000000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' public void testSpeed() {', ' ', ' // here we factorize 10,000 large numbers; make sure that the constructor correctly sets', " // up the array of primes just once... if it does not, it'll take too long to run", ' PrimeFactorizer myFactorizerMax100000000000 = new PrimeFactorizer(100000000000L, outputStream);', ' for (long i = 38845248344L; i < 38845248344L + 50000; i++) {', ' myFactorizerMax100000000000.printPrimeFactorization (i);', ' if (i == 38845248344L) {', ' // Compare the Prime factorization of 38845248344 to the expected result', ' String expected = new String("Prime factorization of 38845248344 is: 2 x 2 x 2 x 7 x 693665149"); ', ' assertEquals (expected, result.toString());', ' }', ' }', ' ', ' // if we make it here, we pass the test', ' assertTrue (true);', ' }', ' ', '}'] | [{'reason_category': 'Loop Body', 'usage_line': 73}, {'reason_category': 'If Body', 'usage_line': 73}, {'reason_category': 'Else Reasoning', 'usage_line': 73}, {'reason_category': 'Loop Body', 'usage_line': 74}, {'reason_category': 'If Body', 'usage_line': 74}, {'reason_category': 'Else Reasoning', 'usage_line': 74}] | Global_Variable 'resultStream' used at line 73 is defined at line 27 and has a Long-Range dependency.
Global_Variable 'allPrimes' used at line 73 is defined at line 21 and has a Long-Range dependency.
Variable 'curPosInAllPrimes' used at line 73 is defined at line 54 and has a Medium-Range dependency. | {'Loop Body': 2, 'If Body': 2, 'Else Reasoning': 2} | {'Global_Variable Long-Range': 2, 'Variable Medium-Range': 1} |
infilling_java | FactorizationTester | 81 | 82 | ['import junit.framework.TestCase;', 'import java.io.ByteArrayOutputStream;', 'import java.io.PrintStream;', 'import java.lang.Math;', '', '/**', ' * This class implements a relatively simple algorithm for computing', ' * (and printing) the prime factors of a number. At initialization,', ' * a list of primes is computed. Given a number, this list is then', ' * used to efficiently print the prime factors of the number.', ' */', 'class PrimeFactorizer {', '', ' // this class will store all primes between 2 and upperBound', ' private int upperBound;', ' ', ' // this class will be able to factorize all primes between 1 and maxNumberToFactorize', ' private long maxNumberToFactorize;', ' ', ' // this is a list of all of the prime numbers between 2 and upperBound', ' private int [] allPrimes;', ' ', ' // this is the number of primes found between 2 and upperBound', ' private int numPrimes;', ' ', ' // this is the output stream that the factorization will be printed to', ' private PrintStream resultStream;', ' ', ' /**', ' * This prints the prime factorization of a number in a "pretty" fashion.', ' * If the number passed in exceeds "upperBound", then a nice error message', ' * is printed. ', ' */', ' public void printPrimeFactorization (long numToFactorize) {', ' ', " // If we are given a number that's too small/big to factor, tell the user", ' if (numToFactorize < 1) {', ' resultStream.format ("Can\'t factorize a number less than 1");', ' return;', ' }', ' if (numToFactorize > maxNumberToFactorize) {', ' resultStream.format ("%d is too large to factorize", numToFactorize);', ' return;', ' }', ' ', ' // Now get ready to print the factorization', ' resultStream.format ("Prime factorization of %d is: ", numToFactorize);', ' ', ' // our basic tactice will be to find all of the primes that divide evenly into', ' // our target. When we find one, print it out and reduce the target accrordingly.', ' // When the target gets down to one, we are done.', ' ', ' // this is the index of the next prime we need to try', ' int curPosInAllPrimes = 0;', ' ', ' // tells us we are still waiting to print the first prime... important so we', ' // don\'t print the "x" symbol before the first one', ' boolean firstOne = true;', ' ', ' while (numToFactorize > 1 && curPosInAllPrimes < numPrimes) {', ' ', " // if the current prime divides evenly into the target, we've got a prime factor", ' if (numToFactorize % allPrimes[curPosInAllPrimes] == 0) {', ' ', ' // if it\'s the first one, we don\'t need to print a "x"', ' // print the factor & reset the firstOne flag', ' if (firstOne) {', ' resultStream.format ("%d", allPrimes[curPosInAllPrimes]);', ' firstOne = false;', ' ', ' // otherwise, print the factor pre-pended with an "x"', ' } else {', ' resultStream.format (" x %d", allPrimes[curPosInAllPrimes]);', ' }', ' ', ' // remove that prime factor from the target', ' numToFactorize /= allPrimes[curPosInAllPrimes];', ' ', ' // if the current prime does not divde evenly, try the next one', ' } else {'] | [' curPosInAllPrimes++;', ' }'] | [' }', ' ', ' // if we never printed any factors, then display the number itself', ' if (firstOne) {', ' resultStream.format ("%d", numToFactorize);', " // Otherwsie print the factors connected by 'x'", ' } else if (numToFactorize > 1) {', ' resultStream.format (" x %d", numToFactorize);', ' }', ' }', ' ', ' ', ' /**', ' * This is the constructor. What it does is to fill the array allPrimes with all', ' * of the prime numbers from 2 through sqrt(maxNumberToFactorize). This array of primes', ' * can then subsequently be used by the printPrimeFactorization method to actually', ' * compute the prime factorization of a number. The method also sets upperBound', ' * (the largest number we checked for primality) and numPrimes (the number of primes', ' * in allPimes). The algorithm used to compute the primes is the classic "sieve of ', ' * Eratosthenes" algorithm.', ' */', ' public PrimeFactorizer (long maxNumberToFactorizeIn, PrintStream outputStream) {', ' ', ' resultStream = outputStream;', ' maxNumberToFactorize = maxNumberToFactorizeIn;', ' ', " // initialize the two class variables- 'upperBound' and 'allPrimes' note that the prime candidates are", ' // from 2 to upperBound, so there are upperBound prime candidates intially', ' upperBound = (int) Math.ceil (Math.sqrt (maxNumberToFactorize));', ' allPrimes = new int[upperBound - 1];', ' ', ' // numIntsInList is the number of ints currently in the list.', ' int numIntsInList = upperBound - 1;', ' ', ' // the number of primes so far is zero', ' numPrimes = 0;', ' ', ' // write all of the candidate numbers to the list... this is all of the numbers', ' // from two to upperBound', ' for (int i = 0; i < upperBound - 1; i++) {', ' allPrimes[i] = i + 2;', ' }', ' ', ' // now we keep removing numbers from the list until we have only primes', ' while (numIntsInList > numPrimes) {', ' ', ' // curPos tells us the last slot that has a "good" (still possibly prime) value.', ' int curPos = numPrimes + 1;', ' ', ' // the front of the list is a prime... kill everyone who is a multiple of it', ' for (int i = numPrimes + 1; i < numIntsInList; i++) {', ' ', ' // if the dude at position i is not a multiple of the current prime, then', " // we keep him; otherwise, he'll be lost", ' if (allPrimes[i] % allPrimes[numPrimes] != 0) {', ' allPrimes[curPos] = allPrimes[i];', ' curPos++;', ' }', ' }', ' ', ' // the number of ints in the list is now equal to the last slot we wrote a value to', ' numIntsInList = curPos;', ' ', ' // and the guy at the front of the list is now considered a prime', ' numPrimes++;', ' ', ' }', ' }', ' ', '', '}', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', ' ', 'public class FactorizationTester extends TestCase {', ' /**', ' * Stream to hold the result of each test.', ' */', ' private ByteArrayOutputStream result;', '', ' /**', ' * Wrapper to provide printing functionality.', ' */', ' private PrintStream outputStream;', '', ' /**', ' * Setup the output streams before each test.', ' */ ', ' protected void setUp () {', ' result = new ByteArrayOutputStream();', ' outputStream = new PrintStream(result);', ' } ', ' ', ' /**', ' * Print a nice message about each test.', ' */', ' private void printInfo(String description, String expected, String actual) {', ' System.out.format ("\\n%s\\n", description);', ' System.out.format ("output:\\t%s\\n", actual);', ' System.out.format ("correct:\\t%s\\n", expected);', ' }', '', ' /**', ' * These are the various test methods. The first 10 test factorizations', ' * using the object constructed to factorize numbers up to 100; the latter', ' * 7 use the object to factorize numbers up to 100000.', ' */', ' public void test100MaxFactorize1() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (1);', '', ' // Print Results', ' String expected = new String("Prime factorization of 1 is: 1");', ' printInfo("Factorizing 1 using max 100", expected, result.toString());', '', ' // Check if test passed by comparing the expected and actual results', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 7 ', ' public void test100MaxFactorize7() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (7);', '', ' // Print Results', ' String expected = new String("Prime factorization of 7 is: 7");', ' printInfo("Factorizing 7 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 5', ' public void test100MaxFactorize5() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (5);', '', ' // Print Results', ' String expected = new String("Prime factorization of 5 is: 5");', ' printInfo("Factorizing 5 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 30', ' public void test100MaxFactorize30() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (30);', '', ' // Print Results', ' String expected = new String("Prime factorization of 30 is: 2 x 3 x 5");', ' printInfo("Factorizing 30 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 81', ' public void test100MaxFactorize81() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (81);', '', ' // Print Results', ' String expected = new String("Prime factorization of 81 is: 3 x 3 x 3 x 3");', ' printInfo("Factorizing 81 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 71', ' public void test100MaxFactorize71() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (71);', '', ' // Print Results', ' String expected = new String("Prime factorization of 71 is: 71");', ' printInfo("Factorizing 71 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 100', ' public void test100MaxFactorize100() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (100);', '', ' // Print Results', ' String expected = new String("Prime factorization of 100 is: 2 x 2 x 5 x 5");', ' printInfo("Factorizing 100 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 101', ' public void test100MaxFactorize101() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (101);', '', ' // Print Results', ' String expected = new String("101 is too large to factorize");', ' printInfo("Factorizing 101 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 0', ' public void test100MaxFactorize0() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (0);', '', ' // Print Results', ' String expected = new String("Can\'t factorize a number less than 1");', ' printInfo("Factorizing 0 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' // Test the factorization of 97', ' public void test100MaxFactorize97() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (97);', '', ' // Print Results', ' String expected = new String("Prime factorization of 97 is: 97");', ' printInfo("Factorizing 97 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 34534', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize34534() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (34534);', '', ' // Print Results', ' String expected = new String("Prime factorization of 34534 is: 2 x 31 x 557");', ' printInfo("Factorizing 34534 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 4339', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize4339() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (4339);', '', ' // Print Results', ' String expected = new String("Prime factorization of 4339 is: 4339");', ' printInfo("Factorizing 4339 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 65536', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize65536() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (65536);', '', ' // Print Results', ' String expected = new String("Prime factorization of 65536 is: 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2");', ' printInfo("Factorizing 65536 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 99797', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize99797() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (99797);', '', ' // Print Results', ' String expected = new String("Prime factorization of 99797 is: 23 x 4339");', ' printInfo("Factorizing 99797 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 307', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize307() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (307);', '', ' // Print Results', ' String expected = new String("Prime factorization of 307 is: 307");', ' printInfo("Factorizing 307 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 38845248344', ' // factorize numbers up to 100000000000', ' public void test100000000000MaxFactorize38845248344() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000000 = new PrimeFactorizer(100000000000L, outputStream);', ' myFactorizerMax100000000000.printPrimeFactorization (38845248344L);', '', ' // Print Results', ' String expected = new String("Prime factorization of 38845248344 is: 2 x 2 x 2 x 7 x 693665149");', ' printInfo("Factorizing 38845248344 using max 100000000000", expected, result.toString());', ' ', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' ', ' result.reset ();', ' myFactorizerMax100000000000.printPrimeFactorization (24210833220L);', ' expected = new String("Prime factorization of 24210833220 is: 2 x 2 x 3 x 3 x 5 x 7 x 17 x 19 x 19 x 31 x 101");', ' printInfo("Factorizing 24210833220 using max 100000000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' public void test100000000000MaxFactorize5387457483444() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000000 = new PrimeFactorizer(100000000000L, outputStream);', ' myFactorizerMax100000000000.printPrimeFactorization (5387457483444L);', '', ' // Print Results', ' String expected = new String("5387457483444 is too large to factorize");', ' printInfo("Factorizing 5387457483444 using max 100000000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' public void testSpeed() {', ' ', ' // here we factorize 10,000 large numbers; make sure that the constructor correctly sets', " // up the array of primes just once... if it does not, it'll take too long to run", ' PrimeFactorizer myFactorizerMax100000000000 = new PrimeFactorizer(100000000000L, outputStream);', ' for (long i = 38845248344L; i < 38845248344L + 50000; i++) {', ' myFactorizerMax100000000000.printPrimeFactorization (i);', ' if (i == 38845248344L) {', ' // Compare the Prime factorization of 38845248344 to the expected result', ' String expected = new String("Prime factorization of 38845248344 is: 2 x 2 x 2 x 7 x 693665149"); ', ' assertEquals (expected, result.toString());', ' }', ' }', ' ', ' // if we make it here, we pass the test', ' assertTrue (true);', ' }', ' ', '}'] | [{'reason_category': 'Loop Body', 'usage_line': 81}, {'reason_category': 'Else Reasoning', 'usage_line': 81}, {'reason_category': 'Loop Body', 'usage_line': 82}, {'reason_category': 'Else Reasoning', 'usage_line': 82}] | Variable 'curPosInAllPrimes' used at line 81 is defined at line 54 and has a Medium-Range dependency. | {'Loop Body': 2, 'Else Reasoning': 2} | {'Variable Medium-Range': 1} |
infilling_java | FactorizationTester | 87 | 87 | ['import junit.framework.TestCase;', 'import java.io.ByteArrayOutputStream;', 'import java.io.PrintStream;', 'import java.lang.Math;', '', '/**', ' * This class implements a relatively simple algorithm for computing', ' * (and printing) the prime factors of a number. At initialization,', ' * a list of primes is computed. Given a number, this list is then', ' * used to efficiently print the prime factors of the number.', ' */', 'class PrimeFactorizer {', '', ' // this class will store all primes between 2 and upperBound', ' private int upperBound;', ' ', ' // this class will be able to factorize all primes between 1 and maxNumberToFactorize', ' private long maxNumberToFactorize;', ' ', ' // this is a list of all of the prime numbers between 2 and upperBound', ' private int [] allPrimes;', ' ', ' // this is the number of primes found between 2 and upperBound', ' private int numPrimes;', ' ', ' // this is the output stream that the factorization will be printed to', ' private PrintStream resultStream;', ' ', ' /**', ' * This prints the prime factorization of a number in a "pretty" fashion.', ' * If the number passed in exceeds "upperBound", then a nice error message', ' * is printed. ', ' */', ' public void printPrimeFactorization (long numToFactorize) {', ' ', " // If we are given a number that's too small/big to factor, tell the user", ' if (numToFactorize < 1) {', ' resultStream.format ("Can\'t factorize a number less than 1");', ' return;', ' }', ' if (numToFactorize > maxNumberToFactorize) {', ' resultStream.format ("%d is too large to factorize", numToFactorize);', ' return;', ' }', ' ', ' // Now get ready to print the factorization', ' resultStream.format ("Prime factorization of %d is: ", numToFactorize);', ' ', ' // our basic tactice will be to find all of the primes that divide evenly into', ' // our target. When we find one, print it out and reduce the target accrordingly.', ' // When the target gets down to one, we are done.', ' ', ' // this is the index of the next prime we need to try', ' int curPosInAllPrimes = 0;', ' ', ' // tells us we are still waiting to print the first prime... important so we', ' // don\'t print the "x" symbol before the first one', ' boolean firstOne = true;', ' ', ' while (numToFactorize > 1 && curPosInAllPrimes < numPrimes) {', ' ', " // if the current prime divides evenly into the target, we've got a prime factor", ' if (numToFactorize % allPrimes[curPosInAllPrimes] == 0) {', ' ', ' // if it\'s the first one, we don\'t need to print a "x"', ' // print the factor & reset the firstOne flag', ' if (firstOne) {', ' resultStream.format ("%d", allPrimes[curPosInAllPrimes]);', ' firstOne = false;', ' ', ' // otherwise, print the factor pre-pended with an "x"', ' } else {', ' resultStream.format (" x %d", allPrimes[curPosInAllPrimes]);', ' }', ' ', ' // remove that prime factor from the target', ' numToFactorize /= allPrimes[curPosInAllPrimes];', ' ', ' // if the current prime does not divde evenly, try the next one', ' } else {', ' curPosInAllPrimes++;', ' }', ' }', ' ', ' // if we never printed any factors, then display the number itself', ' if (firstOne) {'] | [' resultStream.format ("%d", numToFactorize);'] | [" // Otherwsie print the factors connected by 'x'", ' } else if (numToFactorize > 1) {', ' resultStream.format (" x %d", numToFactorize);', ' }', ' }', ' ', ' ', ' /**', ' * This is the constructor. What it does is to fill the array allPrimes with all', ' * of the prime numbers from 2 through sqrt(maxNumberToFactorize). This array of primes', ' * can then subsequently be used by the printPrimeFactorization method to actually', ' * compute the prime factorization of a number. The method also sets upperBound', ' * (the largest number we checked for primality) and numPrimes (the number of primes', ' * in allPimes). The algorithm used to compute the primes is the classic "sieve of ', ' * Eratosthenes" algorithm.', ' */', ' public PrimeFactorizer (long maxNumberToFactorizeIn, PrintStream outputStream) {', ' ', ' resultStream = outputStream;', ' maxNumberToFactorize = maxNumberToFactorizeIn;', ' ', " // initialize the two class variables- 'upperBound' and 'allPrimes' note that the prime candidates are", ' // from 2 to upperBound, so there are upperBound prime candidates intially', ' upperBound = (int) Math.ceil (Math.sqrt (maxNumberToFactorize));', ' allPrimes = new int[upperBound - 1];', ' ', ' // numIntsInList is the number of ints currently in the list.', ' int numIntsInList = upperBound - 1;', ' ', ' // the number of primes so far is zero', ' numPrimes = 0;', ' ', ' // write all of the candidate numbers to the list... this is all of the numbers', ' // from two to upperBound', ' for (int i = 0; i < upperBound - 1; i++) {', ' allPrimes[i] = i + 2;', ' }', ' ', ' // now we keep removing numbers from the list until we have only primes', ' while (numIntsInList > numPrimes) {', ' ', ' // curPos tells us the last slot that has a "good" (still possibly prime) value.', ' int curPos = numPrimes + 1;', ' ', ' // the front of the list is a prime... kill everyone who is a multiple of it', ' for (int i = numPrimes + 1; i < numIntsInList; i++) {', ' ', ' // if the dude at position i is not a multiple of the current prime, then', " // we keep him; otherwise, he'll be lost", ' if (allPrimes[i] % allPrimes[numPrimes] != 0) {', ' allPrimes[curPos] = allPrimes[i];', ' curPos++;', ' }', ' }', ' ', ' // the number of ints in the list is now equal to the last slot we wrote a value to', ' numIntsInList = curPos;', ' ', ' // and the guy at the front of the list is now considered a prime', ' numPrimes++;', ' ', ' }', ' }', ' ', '', '}', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', ' ', 'public class FactorizationTester extends TestCase {', ' /**', ' * Stream to hold the result of each test.', ' */', ' private ByteArrayOutputStream result;', '', ' /**', ' * Wrapper to provide printing functionality.', ' */', ' private PrintStream outputStream;', '', ' /**', ' * Setup the output streams before each test.', ' */ ', ' protected void setUp () {', ' result = new ByteArrayOutputStream();', ' outputStream = new PrintStream(result);', ' } ', ' ', ' /**', ' * Print a nice message about each test.', ' */', ' private void printInfo(String description, String expected, String actual) {', ' System.out.format ("\\n%s\\n", description);', ' System.out.format ("output:\\t%s\\n", actual);', ' System.out.format ("correct:\\t%s\\n", expected);', ' }', '', ' /**', ' * These are the various test methods. The first 10 test factorizations', ' * using the object constructed to factorize numbers up to 100; the latter', ' * 7 use the object to factorize numbers up to 100000.', ' */', ' public void test100MaxFactorize1() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (1);', '', ' // Print Results', ' String expected = new String("Prime factorization of 1 is: 1");', ' printInfo("Factorizing 1 using max 100", expected, result.toString());', '', ' // Check if test passed by comparing the expected and actual results', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 7 ', ' public void test100MaxFactorize7() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (7);', '', ' // Print Results', ' String expected = new String("Prime factorization of 7 is: 7");', ' printInfo("Factorizing 7 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 5', ' public void test100MaxFactorize5() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (5);', '', ' // Print Results', ' String expected = new String("Prime factorization of 5 is: 5");', ' printInfo("Factorizing 5 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 30', ' public void test100MaxFactorize30() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (30);', '', ' // Print Results', ' String expected = new String("Prime factorization of 30 is: 2 x 3 x 5");', ' printInfo("Factorizing 30 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 81', ' public void test100MaxFactorize81() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (81);', '', ' // Print Results', ' String expected = new String("Prime factorization of 81 is: 3 x 3 x 3 x 3");', ' printInfo("Factorizing 81 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 71', ' public void test100MaxFactorize71() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (71);', '', ' // Print Results', ' String expected = new String("Prime factorization of 71 is: 71");', ' printInfo("Factorizing 71 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 100', ' public void test100MaxFactorize100() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (100);', '', ' // Print Results', ' String expected = new String("Prime factorization of 100 is: 2 x 2 x 5 x 5");', ' printInfo("Factorizing 100 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 101', ' public void test100MaxFactorize101() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (101);', '', ' // Print Results', ' String expected = new String("101 is too large to factorize");', ' printInfo("Factorizing 101 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 0', ' public void test100MaxFactorize0() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (0);', '', ' // Print Results', ' String expected = new String("Can\'t factorize a number less than 1");', ' printInfo("Factorizing 0 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' // Test the factorization of 97', ' public void test100MaxFactorize97() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (97);', '', ' // Print Results', ' String expected = new String("Prime factorization of 97 is: 97");', ' printInfo("Factorizing 97 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 34534', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize34534() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (34534);', '', ' // Print Results', ' String expected = new String("Prime factorization of 34534 is: 2 x 31 x 557");', ' printInfo("Factorizing 34534 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 4339', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize4339() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (4339);', '', ' // Print Results', ' String expected = new String("Prime factorization of 4339 is: 4339");', ' printInfo("Factorizing 4339 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 65536', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize65536() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (65536);', '', ' // Print Results', ' String expected = new String("Prime factorization of 65536 is: 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2");', ' printInfo("Factorizing 65536 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 99797', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize99797() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (99797);', '', ' // Print Results', ' String expected = new String("Prime factorization of 99797 is: 23 x 4339");', ' printInfo("Factorizing 99797 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 307', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize307() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (307);', '', ' // Print Results', ' String expected = new String("Prime factorization of 307 is: 307");', ' printInfo("Factorizing 307 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 38845248344', ' // factorize numbers up to 100000000000', ' public void test100000000000MaxFactorize38845248344() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000000 = new PrimeFactorizer(100000000000L, outputStream);', ' myFactorizerMax100000000000.printPrimeFactorization (38845248344L);', '', ' // Print Results', ' String expected = new String("Prime factorization of 38845248344 is: 2 x 2 x 2 x 7 x 693665149");', ' printInfo("Factorizing 38845248344 using max 100000000000", expected, result.toString());', ' ', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' ', ' result.reset ();', ' myFactorizerMax100000000000.printPrimeFactorization (24210833220L);', ' expected = new String("Prime factorization of 24210833220 is: 2 x 2 x 3 x 3 x 5 x 7 x 17 x 19 x 19 x 31 x 101");', ' printInfo("Factorizing 24210833220 using max 100000000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' public void test100000000000MaxFactorize5387457483444() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000000 = new PrimeFactorizer(100000000000L, outputStream);', ' myFactorizerMax100000000000.printPrimeFactorization (5387457483444L);', '', ' // Print Results', ' String expected = new String("5387457483444 is too large to factorize");', ' printInfo("Factorizing 5387457483444 using max 100000000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' public void testSpeed() {', ' ', ' // here we factorize 10,000 large numbers; make sure that the constructor correctly sets', " // up the array of primes just once... if it does not, it'll take too long to run", ' PrimeFactorizer myFactorizerMax100000000000 = new PrimeFactorizer(100000000000L, outputStream);', ' for (long i = 38845248344L; i < 38845248344L + 50000; i++) {', ' myFactorizerMax100000000000.printPrimeFactorization (i);', ' if (i == 38845248344L) {', ' // Compare the Prime factorization of 38845248344 to the expected result', ' String expected = new String("Prime factorization of 38845248344 is: 2 x 2 x 2 x 7 x 693665149"); ', ' assertEquals (expected, result.toString());', ' }', ' }', ' ', ' // if we make it here, we pass the test', ' assertTrue (true);', ' }', ' ', '}'] | [{'reason_category': 'If Body', 'usage_line': 87}] | Global_Variable 'resultStream' used at line 87 is defined at line 27 and has a Long-Range dependency.
Variable 'numToFactorize' used at line 87 is defined at line 77 and has a Short-Range dependency. | {'If Body': 1} | {'Global_Variable Long-Range': 1, 'Variable Short-Range': 1} |
infilling_java | FactorizationTester | 90 | 91 | ['import junit.framework.TestCase;', 'import java.io.ByteArrayOutputStream;', 'import java.io.PrintStream;', 'import java.lang.Math;', '', '/**', ' * This class implements a relatively simple algorithm for computing', ' * (and printing) the prime factors of a number. At initialization,', ' * a list of primes is computed. Given a number, this list is then', ' * used to efficiently print the prime factors of the number.', ' */', 'class PrimeFactorizer {', '', ' // this class will store all primes between 2 and upperBound', ' private int upperBound;', ' ', ' // this class will be able to factorize all primes between 1 and maxNumberToFactorize', ' private long maxNumberToFactorize;', ' ', ' // this is a list of all of the prime numbers between 2 and upperBound', ' private int [] allPrimes;', ' ', ' // this is the number of primes found between 2 and upperBound', ' private int numPrimes;', ' ', ' // this is the output stream that the factorization will be printed to', ' private PrintStream resultStream;', ' ', ' /**', ' * This prints the prime factorization of a number in a "pretty" fashion.', ' * If the number passed in exceeds "upperBound", then a nice error message', ' * is printed. ', ' */', ' public void printPrimeFactorization (long numToFactorize) {', ' ', " // If we are given a number that's too small/big to factor, tell the user", ' if (numToFactorize < 1) {', ' resultStream.format ("Can\'t factorize a number less than 1");', ' return;', ' }', ' if (numToFactorize > maxNumberToFactorize) {', ' resultStream.format ("%d is too large to factorize", numToFactorize);', ' return;', ' }', ' ', ' // Now get ready to print the factorization', ' resultStream.format ("Prime factorization of %d is: ", numToFactorize);', ' ', ' // our basic tactice will be to find all of the primes that divide evenly into', ' // our target. When we find one, print it out and reduce the target accrordingly.', ' // When the target gets down to one, we are done.', ' ', ' // this is the index of the next prime we need to try', ' int curPosInAllPrimes = 0;', ' ', ' // tells us we are still waiting to print the first prime... important so we', ' // don\'t print the "x" symbol before the first one', ' boolean firstOne = true;', ' ', ' while (numToFactorize > 1 && curPosInAllPrimes < numPrimes) {', ' ', " // if the current prime divides evenly into the target, we've got a prime factor", ' if (numToFactorize % allPrimes[curPosInAllPrimes] == 0) {', ' ', ' // if it\'s the first one, we don\'t need to print a "x"', ' // print the factor & reset the firstOne flag', ' if (firstOne) {', ' resultStream.format ("%d", allPrimes[curPosInAllPrimes]);', ' firstOne = false;', ' ', ' // otherwise, print the factor pre-pended with an "x"', ' } else {', ' resultStream.format (" x %d", allPrimes[curPosInAllPrimes]);', ' }', ' ', ' // remove that prime factor from the target', ' numToFactorize /= allPrimes[curPosInAllPrimes];', ' ', ' // if the current prime does not divde evenly, try the next one', ' } else {', ' curPosInAllPrimes++;', ' }', ' }', ' ', ' // if we never printed any factors, then display the number itself', ' if (firstOne) {', ' resultStream.format ("%d", numToFactorize);', " // Otherwsie print the factors connected by 'x'", ' } else if (numToFactorize > 1) {'] | [' resultStream.format (" x %d", numToFactorize);', ' }'] | [' }', ' ', ' ', ' /**', ' * This is the constructor. What it does is to fill the array allPrimes with all', ' * of the prime numbers from 2 through sqrt(maxNumberToFactorize). This array of primes', ' * can then subsequently be used by the printPrimeFactorization method to actually', ' * compute the prime factorization of a number. The method also sets upperBound', ' * (the largest number we checked for primality) and numPrimes (the number of primes', ' * in allPimes). The algorithm used to compute the primes is the classic "sieve of ', ' * Eratosthenes" algorithm.', ' */', ' public PrimeFactorizer (long maxNumberToFactorizeIn, PrintStream outputStream) {', ' ', ' resultStream = outputStream;', ' maxNumberToFactorize = maxNumberToFactorizeIn;', ' ', " // initialize the two class variables- 'upperBound' and 'allPrimes' note that the prime candidates are", ' // from 2 to upperBound, so there are upperBound prime candidates intially', ' upperBound = (int) Math.ceil (Math.sqrt (maxNumberToFactorize));', ' allPrimes = new int[upperBound - 1];', ' ', ' // numIntsInList is the number of ints currently in the list.', ' int numIntsInList = upperBound - 1;', ' ', ' // the number of primes so far is zero', ' numPrimes = 0;', ' ', ' // write all of the candidate numbers to the list... this is all of the numbers', ' // from two to upperBound', ' for (int i = 0; i < upperBound - 1; i++) {', ' allPrimes[i] = i + 2;', ' }', ' ', ' // now we keep removing numbers from the list until we have only primes', ' while (numIntsInList > numPrimes) {', ' ', ' // curPos tells us the last slot that has a "good" (still possibly prime) value.', ' int curPos = numPrimes + 1;', ' ', ' // the front of the list is a prime... kill everyone who is a multiple of it', ' for (int i = numPrimes + 1; i < numIntsInList; i++) {', ' ', ' // if the dude at position i is not a multiple of the current prime, then', " // we keep him; otherwise, he'll be lost", ' if (allPrimes[i] % allPrimes[numPrimes] != 0) {', ' allPrimes[curPos] = allPrimes[i];', ' curPos++;', ' }', ' }', ' ', ' // the number of ints in the list is now equal to the last slot we wrote a value to', ' numIntsInList = curPos;', ' ', ' // and the guy at the front of the list is now considered a prime', ' numPrimes++;', ' ', ' }', ' }', ' ', '', '}', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', ' ', 'public class FactorizationTester extends TestCase {', ' /**', ' * Stream to hold the result of each test.', ' */', ' private ByteArrayOutputStream result;', '', ' /**', ' * Wrapper to provide printing functionality.', ' */', ' private PrintStream outputStream;', '', ' /**', ' * Setup the output streams before each test.', ' */ ', ' protected void setUp () {', ' result = new ByteArrayOutputStream();', ' outputStream = new PrintStream(result);', ' } ', ' ', ' /**', ' * Print a nice message about each test.', ' */', ' private void printInfo(String description, String expected, String actual) {', ' System.out.format ("\\n%s\\n", description);', ' System.out.format ("output:\\t%s\\n", actual);', ' System.out.format ("correct:\\t%s\\n", expected);', ' }', '', ' /**', ' * These are the various test methods. The first 10 test factorizations', ' * using the object constructed to factorize numbers up to 100; the latter', ' * 7 use the object to factorize numbers up to 100000.', ' */', ' public void test100MaxFactorize1() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (1);', '', ' // Print Results', ' String expected = new String("Prime factorization of 1 is: 1");', ' printInfo("Factorizing 1 using max 100", expected, result.toString());', '', ' // Check if test passed by comparing the expected and actual results', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 7 ', ' public void test100MaxFactorize7() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (7);', '', ' // Print Results', ' String expected = new String("Prime factorization of 7 is: 7");', ' printInfo("Factorizing 7 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 5', ' public void test100MaxFactorize5() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (5);', '', ' // Print Results', ' String expected = new String("Prime factorization of 5 is: 5");', ' printInfo("Factorizing 5 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 30', ' public void test100MaxFactorize30() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (30);', '', ' // Print Results', ' String expected = new String("Prime factorization of 30 is: 2 x 3 x 5");', ' printInfo("Factorizing 30 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 81', ' public void test100MaxFactorize81() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (81);', '', ' // Print Results', ' String expected = new String("Prime factorization of 81 is: 3 x 3 x 3 x 3");', ' printInfo("Factorizing 81 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 71', ' public void test100MaxFactorize71() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (71);', '', ' // Print Results', ' String expected = new String("Prime factorization of 71 is: 71");', ' printInfo("Factorizing 71 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 100', ' public void test100MaxFactorize100() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (100);', '', ' // Print Results', ' String expected = new String("Prime factorization of 100 is: 2 x 2 x 5 x 5");', ' printInfo("Factorizing 100 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 101', ' public void test100MaxFactorize101() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (101);', '', ' // Print Results', ' String expected = new String("101 is too large to factorize");', ' printInfo("Factorizing 101 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 0', ' public void test100MaxFactorize0() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (0);', '', ' // Print Results', ' String expected = new String("Can\'t factorize a number less than 1");', ' printInfo("Factorizing 0 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' // Test the factorization of 97', ' public void test100MaxFactorize97() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (97);', '', ' // Print Results', ' String expected = new String("Prime factorization of 97 is: 97");', ' printInfo("Factorizing 97 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 34534', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize34534() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (34534);', '', ' // Print Results', ' String expected = new String("Prime factorization of 34534 is: 2 x 31 x 557");', ' printInfo("Factorizing 34534 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 4339', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize4339() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (4339);', '', ' // Print Results', ' String expected = new String("Prime factorization of 4339 is: 4339");', ' printInfo("Factorizing 4339 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 65536', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize65536() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (65536);', '', ' // Print Results', ' String expected = new String("Prime factorization of 65536 is: 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2");', ' printInfo("Factorizing 65536 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 99797', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize99797() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (99797);', '', ' // Print Results', ' String expected = new String("Prime factorization of 99797 is: 23 x 4339");', ' printInfo("Factorizing 99797 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 307', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize307() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (307);', '', ' // Print Results', ' String expected = new String("Prime factorization of 307 is: 307");', ' printInfo("Factorizing 307 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 38845248344', ' // factorize numbers up to 100000000000', ' public void test100000000000MaxFactorize38845248344() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000000 = new PrimeFactorizer(100000000000L, outputStream);', ' myFactorizerMax100000000000.printPrimeFactorization (38845248344L);', '', ' // Print Results', ' String expected = new String("Prime factorization of 38845248344 is: 2 x 2 x 2 x 7 x 693665149");', ' printInfo("Factorizing 38845248344 using max 100000000000", expected, result.toString());', ' ', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' ', ' result.reset ();', ' myFactorizerMax100000000000.printPrimeFactorization (24210833220L);', ' expected = new String("Prime factorization of 24210833220 is: 2 x 2 x 3 x 3 x 5 x 7 x 17 x 19 x 19 x 31 x 101");', ' printInfo("Factorizing 24210833220 using max 100000000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' public void test100000000000MaxFactorize5387457483444() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000000 = new PrimeFactorizer(100000000000L, outputStream);', ' myFactorizerMax100000000000.printPrimeFactorization (5387457483444L);', '', ' // Print Results', ' String expected = new String("5387457483444 is too large to factorize");', ' printInfo("Factorizing 5387457483444 using max 100000000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' public void testSpeed() {', ' ', ' // here we factorize 10,000 large numbers; make sure that the constructor correctly sets', " // up the array of primes just once... if it does not, it'll take too long to run", ' PrimeFactorizer myFactorizerMax100000000000 = new PrimeFactorizer(100000000000L, outputStream);', ' for (long i = 38845248344L; i < 38845248344L + 50000; i++) {', ' myFactorizerMax100000000000.printPrimeFactorization (i);', ' if (i == 38845248344L) {', ' // Compare the Prime factorization of 38845248344 to the expected result', ' String expected = new String("Prime factorization of 38845248344 is: 2 x 2 x 2 x 7 x 693665149"); ', ' assertEquals (expected, result.toString());', ' }', ' }', ' ', ' // if we make it here, we pass the test', ' assertTrue (true);', ' }', ' ', '}'] | [{'reason_category': 'Else Reasoning', 'usage_line': 90}, {'reason_category': 'Else Reasoning', 'usage_line': 91}] | Global_Variable 'resultStream' used at line 90 is defined at line 27 and has a Long-Range dependency.
Variable 'numToFactorize' used at line 90 is defined at line 77 and has a Medium-Range dependency. | {'Else Reasoning': 2} | {'Global_Variable Long-Range': 1, 'Variable Medium-Range': 1} |
infilling_java | FactorizationTester | 123 | 124 | ['import junit.framework.TestCase;', 'import java.io.ByteArrayOutputStream;', 'import java.io.PrintStream;', 'import java.lang.Math;', '', '/**', ' * This class implements a relatively simple algorithm for computing', ' * (and printing) the prime factors of a number. At initialization,', ' * a list of primes is computed. Given a number, this list is then', ' * used to efficiently print the prime factors of the number.', ' */', 'class PrimeFactorizer {', '', ' // this class will store all primes between 2 and upperBound', ' private int upperBound;', ' ', ' // this class will be able to factorize all primes between 1 and maxNumberToFactorize', ' private long maxNumberToFactorize;', ' ', ' // this is a list of all of the prime numbers between 2 and upperBound', ' private int [] allPrimes;', ' ', ' // this is the number of primes found between 2 and upperBound', ' private int numPrimes;', ' ', ' // this is the output stream that the factorization will be printed to', ' private PrintStream resultStream;', ' ', ' /**', ' * This prints the prime factorization of a number in a "pretty" fashion.', ' * If the number passed in exceeds "upperBound", then a nice error message', ' * is printed. ', ' */', ' public void printPrimeFactorization (long numToFactorize) {', ' ', " // If we are given a number that's too small/big to factor, tell the user", ' if (numToFactorize < 1) {', ' resultStream.format ("Can\'t factorize a number less than 1");', ' return;', ' }', ' if (numToFactorize > maxNumberToFactorize) {', ' resultStream.format ("%d is too large to factorize", numToFactorize);', ' return;', ' }', ' ', ' // Now get ready to print the factorization', ' resultStream.format ("Prime factorization of %d is: ", numToFactorize);', ' ', ' // our basic tactice will be to find all of the primes that divide evenly into', ' // our target. When we find one, print it out and reduce the target accrordingly.', ' // When the target gets down to one, we are done.', ' ', ' // this is the index of the next prime we need to try', ' int curPosInAllPrimes = 0;', ' ', ' // tells us we are still waiting to print the first prime... important so we', ' // don\'t print the "x" symbol before the first one', ' boolean firstOne = true;', ' ', ' while (numToFactorize > 1 && curPosInAllPrimes < numPrimes) {', ' ', " // if the current prime divides evenly into the target, we've got a prime factor", ' if (numToFactorize % allPrimes[curPosInAllPrimes] == 0) {', ' ', ' // if it\'s the first one, we don\'t need to print a "x"', ' // print the factor & reset the firstOne flag', ' if (firstOne) {', ' resultStream.format ("%d", allPrimes[curPosInAllPrimes]);', ' firstOne = false;', ' ', ' // otherwise, print the factor pre-pended with an "x"', ' } else {', ' resultStream.format (" x %d", allPrimes[curPosInAllPrimes]);', ' }', ' ', ' // remove that prime factor from the target', ' numToFactorize /= allPrimes[curPosInAllPrimes];', ' ', ' // if the current prime does not divde evenly, try the next one', ' } else {', ' curPosInAllPrimes++;', ' }', ' }', ' ', ' // if we never printed any factors, then display the number itself', ' if (firstOne) {', ' resultStream.format ("%d", numToFactorize);', " // Otherwsie print the factors connected by 'x'", ' } else if (numToFactorize > 1) {', ' resultStream.format (" x %d", numToFactorize);', ' }', ' }', ' ', ' ', ' /**', ' * This is the constructor. What it does is to fill the array allPrimes with all', ' * of the prime numbers from 2 through sqrt(maxNumberToFactorize). This array of primes', ' * can then subsequently be used by the printPrimeFactorization method to actually', ' * compute the prime factorization of a number. The method also sets upperBound', ' * (the largest number we checked for primality) and numPrimes (the number of primes', ' * in allPimes). The algorithm used to compute the primes is the classic "sieve of ', ' * Eratosthenes" algorithm.', ' */', ' public PrimeFactorizer (long maxNumberToFactorizeIn, PrintStream outputStream) {', ' ', ' resultStream = outputStream;', ' maxNumberToFactorize = maxNumberToFactorizeIn;', ' ', " // initialize the two class variables- 'upperBound' and 'allPrimes' note that the prime candidates are", ' // from 2 to upperBound, so there are upperBound prime candidates intially', ' upperBound = (int) Math.ceil (Math.sqrt (maxNumberToFactorize));', ' allPrimes = new int[upperBound - 1];', ' ', ' // numIntsInList is the number of ints currently in the list.', ' int numIntsInList = upperBound - 1;', ' ', ' // the number of primes so far is zero', ' numPrimes = 0;', ' ', ' // write all of the candidate numbers to the list... this is all of the numbers', ' // from two to upperBound', ' for (int i = 0; i < upperBound - 1; i++) {'] | [' allPrimes[i] = i + 2;', ' }'] | [' ', ' // now we keep removing numbers from the list until we have only primes', ' while (numIntsInList > numPrimes) {', ' ', ' // curPos tells us the last slot that has a "good" (still possibly prime) value.', ' int curPos = numPrimes + 1;', ' ', ' // the front of the list is a prime... kill everyone who is a multiple of it', ' for (int i = numPrimes + 1; i < numIntsInList; i++) {', ' ', ' // if the dude at position i is not a multiple of the current prime, then', " // we keep him; otherwise, he'll be lost", ' if (allPrimes[i] % allPrimes[numPrimes] != 0) {', ' allPrimes[curPos] = allPrimes[i];', ' curPos++;', ' }', ' }', ' ', ' // the number of ints in the list is now equal to the last slot we wrote a value to', ' numIntsInList = curPos;', ' ', ' // and the guy at the front of the list is now considered a prime', ' numPrimes++;', ' ', ' }', ' }', ' ', '', '}', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', ' ', 'public class FactorizationTester extends TestCase {', ' /**', ' * Stream to hold the result of each test.', ' */', ' private ByteArrayOutputStream result;', '', ' /**', ' * Wrapper to provide printing functionality.', ' */', ' private PrintStream outputStream;', '', ' /**', ' * Setup the output streams before each test.', ' */ ', ' protected void setUp () {', ' result = new ByteArrayOutputStream();', ' outputStream = new PrintStream(result);', ' } ', ' ', ' /**', ' * Print a nice message about each test.', ' */', ' private void printInfo(String description, String expected, String actual) {', ' System.out.format ("\\n%s\\n", description);', ' System.out.format ("output:\\t%s\\n", actual);', ' System.out.format ("correct:\\t%s\\n", expected);', ' }', '', ' /**', ' * These are the various test methods. The first 10 test factorizations', ' * using the object constructed to factorize numbers up to 100; the latter', ' * 7 use the object to factorize numbers up to 100000.', ' */', ' public void test100MaxFactorize1() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (1);', '', ' // Print Results', ' String expected = new String("Prime factorization of 1 is: 1");', ' printInfo("Factorizing 1 using max 100", expected, result.toString());', '', ' // Check if test passed by comparing the expected and actual results', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 7 ', ' public void test100MaxFactorize7() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (7);', '', ' // Print Results', ' String expected = new String("Prime factorization of 7 is: 7");', ' printInfo("Factorizing 7 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 5', ' public void test100MaxFactorize5() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (5);', '', ' // Print Results', ' String expected = new String("Prime factorization of 5 is: 5");', ' printInfo("Factorizing 5 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 30', ' public void test100MaxFactorize30() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (30);', '', ' // Print Results', ' String expected = new String("Prime factorization of 30 is: 2 x 3 x 5");', ' printInfo("Factorizing 30 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 81', ' public void test100MaxFactorize81() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (81);', '', ' // Print Results', ' String expected = new String("Prime factorization of 81 is: 3 x 3 x 3 x 3");', ' printInfo("Factorizing 81 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 71', ' public void test100MaxFactorize71() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (71);', '', ' // Print Results', ' String expected = new String("Prime factorization of 71 is: 71");', ' printInfo("Factorizing 71 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 100', ' public void test100MaxFactorize100() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (100);', '', ' // Print Results', ' String expected = new String("Prime factorization of 100 is: 2 x 2 x 5 x 5");', ' printInfo("Factorizing 100 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 101', ' public void test100MaxFactorize101() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (101);', '', ' // Print Results', ' String expected = new String("101 is too large to factorize");', ' printInfo("Factorizing 101 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 0', ' public void test100MaxFactorize0() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (0);', '', ' // Print Results', ' String expected = new String("Can\'t factorize a number less than 1");', ' printInfo("Factorizing 0 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' // Test the factorization of 97', ' public void test100MaxFactorize97() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (97);', '', ' // Print Results', ' String expected = new String("Prime factorization of 97 is: 97");', ' printInfo("Factorizing 97 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 34534', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize34534() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (34534);', '', ' // Print Results', ' String expected = new String("Prime factorization of 34534 is: 2 x 31 x 557");', ' printInfo("Factorizing 34534 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 4339', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize4339() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (4339);', '', ' // Print Results', ' String expected = new String("Prime factorization of 4339 is: 4339");', ' printInfo("Factorizing 4339 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 65536', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize65536() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (65536);', '', ' // Print Results', ' String expected = new String("Prime factorization of 65536 is: 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2");', ' printInfo("Factorizing 65536 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 99797', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize99797() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (99797);', '', ' // Print Results', ' String expected = new String("Prime factorization of 99797 is: 23 x 4339");', ' printInfo("Factorizing 99797 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 307', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize307() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (307);', '', ' // Print Results', ' String expected = new String("Prime factorization of 307 is: 307");', ' printInfo("Factorizing 307 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 38845248344', ' // factorize numbers up to 100000000000', ' public void test100000000000MaxFactorize38845248344() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000000 = new PrimeFactorizer(100000000000L, outputStream);', ' myFactorizerMax100000000000.printPrimeFactorization (38845248344L);', '', ' // Print Results', ' String expected = new String("Prime factorization of 38845248344 is: 2 x 2 x 2 x 7 x 693665149");', ' printInfo("Factorizing 38845248344 using max 100000000000", expected, result.toString());', ' ', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' ', ' result.reset ();', ' myFactorizerMax100000000000.printPrimeFactorization (24210833220L);', ' expected = new String("Prime factorization of 24210833220 is: 2 x 2 x 3 x 3 x 5 x 7 x 17 x 19 x 19 x 31 x 101");', ' printInfo("Factorizing 24210833220 using max 100000000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' public void test100000000000MaxFactorize5387457483444() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000000 = new PrimeFactorizer(100000000000L, outputStream);', ' myFactorizerMax100000000000.printPrimeFactorization (5387457483444L);', '', ' // Print Results', ' String expected = new String("5387457483444 is too large to factorize");', ' printInfo("Factorizing 5387457483444 using max 100000000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' public void testSpeed() {', ' ', ' // here we factorize 10,000 large numbers; make sure that the constructor correctly sets', " // up the array of primes just once... if it does not, it'll take too long to run", ' PrimeFactorizer myFactorizerMax100000000000 = new PrimeFactorizer(100000000000L, outputStream);', ' for (long i = 38845248344L; i < 38845248344L + 50000; i++) {', ' myFactorizerMax100000000000.printPrimeFactorization (i);', ' if (i == 38845248344L) {', ' // Compare the Prime factorization of 38845248344 to the expected result', ' String expected = new String("Prime factorization of 38845248344 is: 2 x 2 x 2 x 7 x 693665149"); ', ' assertEquals (expected, result.toString());', ' }', ' }', ' ', ' // if we make it here, we pass the test', ' assertTrue (true);', ' }', ' ', '}'] | [{'reason_category': 'Loop Body', 'usage_line': 123}, {'reason_category': 'Loop Body', 'usage_line': 124}] | Variable 'i' used at line 123 is defined at line 122 and has a Short-Range dependency.
Global_Variable 'allPrimes' used at line 123 is defined at line 112 and has a Medium-Range dependency. | {'Loop Body': 2} | {'Variable Short-Range': 1, 'Global_Variable Medium-Range': 1} |
infilling_java | FactorizationTester | 135 | 141 | ['import junit.framework.TestCase;', 'import java.io.ByteArrayOutputStream;', 'import java.io.PrintStream;', 'import java.lang.Math;', '', '/**', ' * This class implements a relatively simple algorithm for computing', ' * (and printing) the prime factors of a number. At initialization,', ' * a list of primes is computed. Given a number, this list is then', ' * used to efficiently print the prime factors of the number.', ' */', 'class PrimeFactorizer {', '', ' // this class will store all primes between 2 and upperBound', ' private int upperBound;', ' ', ' // this class will be able to factorize all primes between 1 and maxNumberToFactorize', ' private long maxNumberToFactorize;', ' ', ' // this is a list of all of the prime numbers between 2 and upperBound', ' private int [] allPrimes;', ' ', ' // this is the number of primes found between 2 and upperBound', ' private int numPrimes;', ' ', ' // this is the output stream that the factorization will be printed to', ' private PrintStream resultStream;', ' ', ' /**', ' * This prints the prime factorization of a number in a "pretty" fashion.', ' * If the number passed in exceeds "upperBound", then a nice error message', ' * is printed. ', ' */', ' public void printPrimeFactorization (long numToFactorize) {', ' ', " // If we are given a number that's too small/big to factor, tell the user", ' if (numToFactorize < 1) {', ' resultStream.format ("Can\'t factorize a number less than 1");', ' return;', ' }', ' if (numToFactorize > maxNumberToFactorize) {', ' resultStream.format ("%d is too large to factorize", numToFactorize);', ' return;', ' }', ' ', ' // Now get ready to print the factorization', ' resultStream.format ("Prime factorization of %d is: ", numToFactorize);', ' ', ' // our basic tactice will be to find all of the primes that divide evenly into', ' // our target. When we find one, print it out and reduce the target accrordingly.', ' // When the target gets down to one, we are done.', ' ', ' // this is the index of the next prime we need to try', ' int curPosInAllPrimes = 0;', ' ', ' // tells us we are still waiting to print the first prime... important so we', ' // don\'t print the "x" symbol before the first one', ' boolean firstOne = true;', ' ', ' while (numToFactorize > 1 && curPosInAllPrimes < numPrimes) {', ' ', " // if the current prime divides evenly into the target, we've got a prime factor", ' if (numToFactorize % allPrimes[curPosInAllPrimes] == 0) {', ' ', ' // if it\'s the first one, we don\'t need to print a "x"', ' // print the factor & reset the firstOne flag', ' if (firstOne) {', ' resultStream.format ("%d", allPrimes[curPosInAllPrimes]);', ' firstOne = false;', ' ', ' // otherwise, print the factor pre-pended with an "x"', ' } else {', ' resultStream.format (" x %d", allPrimes[curPosInAllPrimes]);', ' }', ' ', ' // remove that prime factor from the target', ' numToFactorize /= allPrimes[curPosInAllPrimes];', ' ', ' // if the current prime does not divde evenly, try the next one', ' } else {', ' curPosInAllPrimes++;', ' }', ' }', ' ', ' // if we never printed any factors, then display the number itself', ' if (firstOne) {', ' resultStream.format ("%d", numToFactorize);', " // Otherwsie print the factors connected by 'x'", ' } else if (numToFactorize > 1) {', ' resultStream.format (" x %d", numToFactorize);', ' }', ' }', ' ', ' ', ' /**', ' * This is the constructor. What it does is to fill the array allPrimes with all', ' * of the prime numbers from 2 through sqrt(maxNumberToFactorize). This array of primes', ' * can then subsequently be used by the printPrimeFactorization method to actually', ' * compute the prime factorization of a number. The method also sets upperBound', ' * (the largest number we checked for primality) and numPrimes (the number of primes', ' * in allPimes). The algorithm used to compute the primes is the classic "sieve of ', ' * Eratosthenes" algorithm.', ' */', ' public PrimeFactorizer (long maxNumberToFactorizeIn, PrintStream outputStream) {', ' ', ' resultStream = outputStream;', ' maxNumberToFactorize = maxNumberToFactorizeIn;', ' ', " // initialize the two class variables- 'upperBound' and 'allPrimes' note that the prime candidates are", ' // from 2 to upperBound, so there are upperBound prime candidates intially', ' upperBound = (int) Math.ceil (Math.sqrt (maxNumberToFactorize));', ' allPrimes = new int[upperBound - 1];', ' ', ' // numIntsInList is the number of ints currently in the list.', ' int numIntsInList = upperBound - 1;', ' ', ' // the number of primes so far is zero', ' numPrimes = 0;', ' ', ' // write all of the candidate numbers to the list... this is all of the numbers', ' // from two to upperBound', ' for (int i = 0; i < upperBound - 1; i++) {', ' allPrimes[i] = i + 2;', ' }', ' ', ' // now we keep removing numbers from the list until we have only primes', ' while (numIntsInList > numPrimes) {', ' ', ' // curPos tells us the last slot that has a "good" (still possibly prime) value.', ' int curPos = numPrimes + 1;', ' ', ' // the front of the list is a prime... kill everyone who is a multiple of it', ' for (int i = numPrimes + 1; i < numIntsInList; i++) {', ' '] | [' // if the dude at position i is not a multiple of the current prime, then', " // we keep him; otherwise, he'll be lost", ' if (allPrimes[i] % allPrimes[numPrimes] != 0) {', ' allPrimes[curPos] = allPrimes[i];', ' curPos++;', ' }', ' }'] | [' ', ' // the number of ints in the list is now equal to the last slot we wrote a value to', ' numIntsInList = curPos;', ' ', ' // and the guy at the front of the list is now considered a prime', ' numPrimes++;', ' ', ' }', ' }', ' ', '', '}', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', ' ', 'public class FactorizationTester extends TestCase {', ' /**', ' * Stream to hold the result of each test.', ' */', ' private ByteArrayOutputStream result;', '', ' /**', ' * Wrapper to provide printing functionality.', ' */', ' private PrintStream outputStream;', '', ' /**', ' * Setup the output streams before each test.', ' */ ', ' protected void setUp () {', ' result = new ByteArrayOutputStream();', ' outputStream = new PrintStream(result);', ' } ', ' ', ' /**', ' * Print a nice message about each test.', ' */', ' private void printInfo(String description, String expected, String actual) {', ' System.out.format ("\\n%s\\n", description);', ' System.out.format ("output:\\t%s\\n", actual);', ' System.out.format ("correct:\\t%s\\n", expected);', ' }', '', ' /**', ' * These are the various test methods. The first 10 test factorizations', ' * using the object constructed to factorize numbers up to 100; the latter', ' * 7 use the object to factorize numbers up to 100000.', ' */', ' public void test100MaxFactorize1() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (1);', '', ' // Print Results', ' String expected = new String("Prime factorization of 1 is: 1");', ' printInfo("Factorizing 1 using max 100", expected, result.toString());', '', ' // Check if test passed by comparing the expected and actual results', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 7 ', ' public void test100MaxFactorize7() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (7);', '', ' // Print Results', ' String expected = new String("Prime factorization of 7 is: 7");', ' printInfo("Factorizing 7 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 5', ' public void test100MaxFactorize5() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (5);', '', ' // Print Results', ' String expected = new String("Prime factorization of 5 is: 5");', ' printInfo("Factorizing 5 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 30', ' public void test100MaxFactorize30() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (30);', '', ' // Print Results', ' String expected = new String("Prime factorization of 30 is: 2 x 3 x 5");', ' printInfo("Factorizing 30 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 81', ' public void test100MaxFactorize81() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (81);', '', ' // Print Results', ' String expected = new String("Prime factorization of 81 is: 3 x 3 x 3 x 3");', ' printInfo("Factorizing 81 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 71', ' public void test100MaxFactorize71() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (71);', '', ' // Print Results', ' String expected = new String("Prime factorization of 71 is: 71");', ' printInfo("Factorizing 71 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 100', ' public void test100MaxFactorize100() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (100);', '', ' // Print Results', ' String expected = new String("Prime factorization of 100 is: 2 x 2 x 5 x 5");', ' printInfo("Factorizing 100 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 101', ' public void test100MaxFactorize101() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (101);', '', ' // Print Results', ' String expected = new String("101 is too large to factorize");', ' printInfo("Factorizing 101 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 0', ' public void test100MaxFactorize0() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (0);', '', ' // Print Results', ' String expected = new String("Can\'t factorize a number less than 1");', ' printInfo("Factorizing 0 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' // Test the factorization of 97', ' public void test100MaxFactorize97() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (97);', '', ' // Print Results', ' String expected = new String("Prime factorization of 97 is: 97");', ' printInfo("Factorizing 97 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 34534', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize34534() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (34534);', '', ' // Print Results', ' String expected = new String("Prime factorization of 34534 is: 2 x 31 x 557");', ' printInfo("Factorizing 34534 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 4339', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize4339() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (4339);', '', ' // Print Results', ' String expected = new String("Prime factorization of 4339 is: 4339");', ' printInfo("Factorizing 4339 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 65536', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize65536() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (65536);', '', ' // Print Results', ' String expected = new String("Prime factorization of 65536 is: 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2");', ' printInfo("Factorizing 65536 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 99797', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize99797() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (99797);', '', ' // Print Results', ' String expected = new String("Prime factorization of 99797 is: 23 x 4339");', ' printInfo("Factorizing 99797 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 307', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize307() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (307);', '', ' // Print Results', ' String expected = new String("Prime factorization of 307 is: 307");', ' printInfo("Factorizing 307 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 38845248344', ' // factorize numbers up to 100000000000', ' public void test100000000000MaxFactorize38845248344() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000000 = new PrimeFactorizer(100000000000L, outputStream);', ' myFactorizerMax100000000000.printPrimeFactorization (38845248344L);', '', ' // Print Results', ' String expected = new String("Prime factorization of 38845248344 is: 2 x 2 x 2 x 7 x 693665149");', ' printInfo("Factorizing 38845248344 using max 100000000000", expected, result.toString());', ' ', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' ', ' result.reset ();', ' myFactorizerMax100000000000.printPrimeFactorization (24210833220L);', ' expected = new String("Prime factorization of 24210833220 is: 2 x 2 x 3 x 3 x 5 x 7 x 17 x 19 x 19 x 31 x 101");', ' printInfo("Factorizing 24210833220 using max 100000000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' public void test100000000000MaxFactorize5387457483444() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000000 = new PrimeFactorizer(100000000000L, outputStream);', ' myFactorizerMax100000000000.printPrimeFactorization (5387457483444L);', '', ' // Print Results', ' String expected = new String("5387457483444 is too large to factorize");', ' printInfo("Factorizing 5387457483444 using max 100000000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' public void testSpeed() {', ' ', ' // here we factorize 10,000 large numbers; make sure that the constructor correctly sets', " // up the array of primes just once... if it does not, it'll take too long to run", ' PrimeFactorizer myFactorizerMax100000000000 = new PrimeFactorizer(100000000000L, outputStream);', ' for (long i = 38845248344L; i < 38845248344L + 50000; i++) {', ' myFactorizerMax100000000000.printPrimeFactorization (i);', ' if (i == 38845248344L) {', ' // Compare the Prime factorization of 38845248344 to the expected result', ' String expected = new String("Prime factorization of 38845248344 is: 2 x 2 x 2 x 7 x 693665149"); ', ' assertEquals (expected, result.toString());', ' }', ' }', ' ', ' // if we make it here, we pass the test', ' assertTrue (true);', ' }', ' ', '}'] | [{'reason_category': 'Loop Body', 'usage_line': 135}, {'reason_category': 'Loop Body', 'usage_line': 136}, {'reason_category': 'Loop Body', 'usage_line': 137}, {'reason_category': 'If Condition', 'usage_line': 137}, {'reason_category': 'Loop Body', 'usage_line': 138}, {'reason_category': 'If Body', 'usage_line': 138}, {'reason_category': 'Loop Body', 'usage_line': 139}, {'reason_category': 'If Body', 'usage_line': 139}, {'reason_category': 'Loop Body', 'usage_line': 140}, {'reason_category': 'If Body', 'usage_line': 140}, {'reason_category': 'Loop Body', 'usage_line': 141}] | Global_Variable 'allPrimes' used at line 137 is defined at line 112 and has a Medium-Range dependency.
Variable 'i' used at line 137 is defined at line 133 and has a Short-Range dependency.
Global_Variable 'numPrimes' used at line 137 is defined at line 118 and has a Medium-Range dependency.
Global_Variable 'allPrimes' used at line 138 is defined at line 112 and has a Medium-Range dependency.
Variable 'i' used at line 138 is defined at line 133 and has a Short-Range dependency.
Variable 'curPos' used at line 138 is defined at line 130 and has a Short-Range dependency.
Variable 'curPos' used at line 139 is defined at line 130 and has a Short-Range dependency. | {'Loop Body': 7, 'If Condition': 1, 'If Body': 3} | {'Global_Variable Medium-Range': 3, 'Variable Short-Range': 4} |
infilling_java | FactorizationTester | 137 | 141 | ['import junit.framework.TestCase;', 'import java.io.ByteArrayOutputStream;', 'import java.io.PrintStream;', 'import java.lang.Math;', '', '/**', ' * This class implements a relatively simple algorithm for computing', ' * (and printing) the prime factors of a number. At initialization,', ' * a list of primes is computed. Given a number, this list is then', ' * used to efficiently print the prime factors of the number.', ' */', 'class PrimeFactorizer {', '', ' // this class will store all primes between 2 and upperBound', ' private int upperBound;', ' ', ' // this class will be able to factorize all primes between 1 and maxNumberToFactorize', ' private long maxNumberToFactorize;', ' ', ' // this is a list of all of the prime numbers between 2 and upperBound', ' private int [] allPrimes;', ' ', ' // this is the number of primes found between 2 and upperBound', ' private int numPrimes;', ' ', ' // this is the output stream that the factorization will be printed to', ' private PrintStream resultStream;', ' ', ' /**', ' * This prints the prime factorization of a number in a "pretty" fashion.', ' * If the number passed in exceeds "upperBound", then a nice error message', ' * is printed. ', ' */', ' public void printPrimeFactorization (long numToFactorize) {', ' ', " // If we are given a number that's too small/big to factor, tell the user", ' if (numToFactorize < 1) {', ' resultStream.format ("Can\'t factorize a number less than 1");', ' return;', ' }', ' if (numToFactorize > maxNumberToFactorize) {', ' resultStream.format ("%d is too large to factorize", numToFactorize);', ' return;', ' }', ' ', ' // Now get ready to print the factorization', ' resultStream.format ("Prime factorization of %d is: ", numToFactorize);', ' ', ' // our basic tactice will be to find all of the primes that divide evenly into', ' // our target. When we find one, print it out and reduce the target accrordingly.', ' // When the target gets down to one, we are done.', ' ', ' // this is the index of the next prime we need to try', ' int curPosInAllPrimes = 0;', ' ', ' // tells us we are still waiting to print the first prime... important so we', ' // don\'t print the "x" symbol before the first one', ' boolean firstOne = true;', ' ', ' while (numToFactorize > 1 && curPosInAllPrimes < numPrimes) {', ' ', " // if the current prime divides evenly into the target, we've got a prime factor", ' if (numToFactorize % allPrimes[curPosInAllPrimes] == 0) {', ' ', ' // if it\'s the first one, we don\'t need to print a "x"', ' // print the factor & reset the firstOne flag', ' if (firstOne) {', ' resultStream.format ("%d", allPrimes[curPosInAllPrimes]);', ' firstOne = false;', ' ', ' // otherwise, print the factor pre-pended with an "x"', ' } else {', ' resultStream.format (" x %d", allPrimes[curPosInAllPrimes]);', ' }', ' ', ' // remove that prime factor from the target', ' numToFactorize /= allPrimes[curPosInAllPrimes];', ' ', ' // if the current prime does not divde evenly, try the next one', ' } else {', ' curPosInAllPrimes++;', ' }', ' }', ' ', ' // if we never printed any factors, then display the number itself', ' if (firstOne) {', ' resultStream.format ("%d", numToFactorize);', " // Otherwsie print the factors connected by 'x'", ' } else if (numToFactorize > 1) {', ' resultStream.format (" x %d", numToFactorize);', ' }', ' }', ' ', ' ', ' /**', ' * This is the constructor. What it does is to fill the array allPrimes with all', ' * of the prime numbers from 2 through sqrt(maxNumberToFactorize). This array of primes', ' * can then subsequently be used by the printPrimeFactorization method to actually', ' * compute the prime factorization of a number. The method also sets upperBound', ' * (the largest number we checked for primality) and numPrimes (the number of primes', ' * in allPimes). The algorithm used to compute the primes is the classic "sieve of ', ' * Eratosthenes" algorithm.', ' */', ' public PrimeFactorizer (long maxNumberToFactorizeIn, PrintStream outputStream) {', ' ', ' resultStream = outputStream;', ' maxNumberToFactorize = maxNumberToFactorizeIn;', ' ', " // initialize the two class variables- 'upperBound' and 'allPrimes' note that the prime candidates are", ' // from 2 to upperBound, so there are upperBound prime candidates intially', ' upperBound = (int) Math.ceil (Math.sqrt (maxNumberToFactorize));', ' allPrimes = new int[upperBound - 1];', ' ', ' // numIntsInList is the number of ints currently in the list.', ' int numIntsInList = upperBound - 1;', ' ', ' // the number of primes so far is zero', ' numPrimes = 0;', ' ', ' // write all of the candidate numbers to the list... this is all of the numbers', ' // from two to upperBound', ' for (int i = 0; i < upperBound - 1; i++) {', ' allPrimes[i] = i + 2;', ' }', ' ', ' // now we keep removing numbers from the list until we have only primes', ' while (numIntsInList > numPrimes) {', ' ', ' // curPos tells us the last slot that has a "good" (still possibly prime) value.', ' int curPos = numPrimes + 1;', ' ', ' // the front of the list is a prime... kill everyone who is a multiple of it', ' for (int i = numPrimes + 1; i < numIntsInList; i++) {', ' ', ' // if the dude at position i is not a multiple of the current prime, then', " // we keep him; otherwise, he'll be lost"] | [' if (allPrimes[i] % allPrimes[numPrimes] != 0) {', ' allPrimes[curPos] = allPrimes[i];', ' curPos++;', ' }', ' }'] | [' ', ' // the number of ints in the list is now equal to the last slot we wrote a value to', ' numIntsInList = curPos;', ' ', ' // and the guy at the front of the list is now considered a prime', ' numPrimes++;', ' ', ' }', ' }', ' ', '', '}', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', ' ', 'public class FactorizationTester extends TestCase {', ' /**', ' * Stream to hold the result of each test.', ' */', ' private ByteArrayOutputStream result;', '', ' /**', ' * Wrapper to provide printing functionality.', ' */', ' private PrintStream outputStream;', '', ' /**', ' * Setup the output streams before each test.', ' */ ', ' protected void setUp () {', ' result = new ByteArrayOutputStream();', ' outputStream = new PrintStream(result);', ' } ', ' ', ' /**', ' * Print a nice message about each test.', ' */', ' private void printInfo(String description, String expected, String actual) {', ' System.out.format ("\\n%s\\n", description);', ' System.out.format ("output:\\t%s\\n", actual);', ' System.out.format ("correct:\\t%s\\n", expected);', ' }', '', ' /**', ' * These are the various test methods. The first 10 test factorizations', ' * using the object constructed to factorize numbers up to 100; the latter', ' * 7 use the object to factorize numbers up to 100000.', ' */', ' public void test100MaxFactorize1() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (1);', '', ' // Print Results', ' String expected = new String("Prime factorization of 1 is: 1");', ' printInfo("Factorizing 1 using max 100", expected, result.toString());', '', ' // Check if test passed by comparing the expected and actual results', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 7 ', ' public void test100MaxFactorize7() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (7);', '', ' // Print Results', ' String expected = new String("Prime factorization of 7 is: 7");', ' printInfo("Factorizing 7 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 5', ' public void test100MaxFactorize5() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (5);', '', ' // Print Results', ' String expected = new String("Prime factorization of 5 is: 5");', ' printInfo("Factorizing 5 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 30', ' public void test100MaxFactorize30() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (30);', '', ' // Print Results', ' String expected = new String("Prime factorization of 30 is: 2 x 3 x 5");', ' printInfo("Factorizing 30 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 81', ' public void test100MaxFactorize81() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (81);', '', ' // Print Results', ' String expected = new String("Prime factorization of 81 is: 3 x 3 x 3 x 3");', ' printInfo("Factorizing 81 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 71', ' public void test100MaxFactorize71() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (71);', '', ' // Print Results', ' String expected = new String("Prime factorization of 71 is: 71");', ' printInfo("Factorizing 71 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 100', ' public void test100MaxFactorize100() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (100);', '', ' // Print Results', ' String expected = new String("Prime factorization of 100 is: 2 x 2 x 5 x 5");', ' printInfo("Factorizing 100 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 101', ' public void test100MaxFactorize101() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (101);', '', ' // Print Results', ' String expected = new String("101 is too large to factorize");', ' printInfo("Factorizing 101 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 0', ' public void test100MaxFactorize0() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (0);', '', ' // Print Results', ' String expected = new String("Can\'t factorize a number less than 1");', ' printInfo("Factorizing 0 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' // Test the factorization of 97', ' public void test100MaxFactorize97() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (97);', '', ' // Print Results', ' String expected = new String("Prime factorization of 97 is: 97");', ' printInfo("Factorizing 97 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 34534', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize34534() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (34534);', '', ' // Print Results', ' String expected = new String("Prime factorization of 34534 is: 2 x 31 x 557");', ' printInfo("Factorizing 34534 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 4339', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize4339() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (4339);', '', ' // Print Results', ' String expected = new String("Prime factorization of 4339 is: 4339");', ' printInfo("Factorizing 4339 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 65536', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize65536() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (65536);', '', ' // Print Results', ' String expected = new String("Prime factorization of 65536 is: 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2");', ' printInfo("Factorizing 65536 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 99797', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize99797() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (99797);', '', ' // Print Results', ' String expected = new String("Prime factorization of 99797 is: 23 x 4339");', ' printInfo("Factorizing 99797 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 307', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize307() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (307);', '', ' // Print Results', ' String expected = new String("Prime factorization of 307 is: 307");', ' printInfo("Factorizing 307 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 38845248344', ' // factorize numbers up to 100000000000', ' public void test100000000000MaxFactorize38845248344() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000000 = new PrimeFactorizer(100000000000L, outputStream);', ' myFactorizerMax100000000000.printPrimeFactorization (38845248344L);', '', ' // Print Results', ' String expected = new String("Prime factorization of 38845248344 is: 2 x 2 x 2 x 7 x 693665149");', ' printInfo("Factorizing 38845248344 using max 100000000000", expected, result.toString());', ' ', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' ', ' result.reset ();', ' myFactorizerMax100000000000.printPrimeFactorization (24210833220L);', ' expected = new String("Prime factorization of 24210833220 is: 2 x 2 x 3 x 3 x 5 x 7 x 17 x 19 x 19 x 31 x 101");', ' printInfo("Factorizing 24210833220 using max 100000000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' public void test100000000000MaxFactorize5387457483444() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000000 = new PrimeFactorizer(100000000000L, outputStream);', ' myFactorizerMax100000000000.printPrimeFactorization (5387457483444L);', '', ' // Print Results', ' String expected = new String("5387457483444 is too large to factorize");', ' printInfo("Factorizing 5387457483444 using max 100000000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' public void testSpeed() {', ' ', ' // here we factorize 10,000 large numbers; make sure that the constructor correctly sets', " // up the array of primes just once... if it does not, it'll take too long to run", ' PrimeFactorizer myFactorizerMax100000000000 = new PrimeFactorizer(100000000000L, outputStream);', ' for (long i = 38845248344L; i < 38845248344L + 50000; i++) {', ' myFactorizerMax100000000000.printPrimeFactorization (i);', ' if (i == 38845248344L) {', ' // Compare the Prime factorization of 38845248344 to the expected result', ' String expected = new String("Prime factorization of 38845248344 is: 2 x 2 x 2 x 7 x 693665149"); ', ' assertEquals (expected, result.toString());', ' }', ' }', ' ', ' // if we make it here, we pass the test', ' assertTrue (true);', ' }', ' ', '}'] | [{'reason_category': 'Loop Body', 'usage_line': 137}, {'reason_category': 'If Condition', 'usage_line': 137}, {'reason_category': 'Loop Body', 'usage_line': 138}, {'reason_category': 'If Body', 'usage_line': 138}, {'reason_category': 'Loop Body', 'usage_line': 139}, {'reason_category': 'If Body', 'usage_line': 139}, {'reason_category': 'Loop Body', 'usage_line': 140}, {'reason_category': 'If Body', 'usage_line': 140}, {'reason_category': 'Loop Body', 'usage_line': 141}] | Global_Variable 'allPrimes' used at line 137 is defined at line 112 and has a Medium-Range dependency.
Variable 'i' used at line 137 is defined at line 133 and has a Short-Range dependency.
Global_Variable 'numPrimes' used at line 137 is defined at line 118 and has a Medium-Range dependency.
Global_Variable 'allPrimes' used at line 138 is defined at line 112 and has a Medium-Range dependency.
Variable 'i' used at line 138 is defined at line 133 and has a Short-Range dependency.
Variable 'curPos' used at line 138 is defined at line 130 and has a Short-Range dependency.
Variable 'curPos' used at line 139 is defined at line 130 and has a Short-Range dependency. | {'Loop Body': 5, 'If Condition': 1, 'If Body': 3} | {'Global_Variable Medium-Range': 3, 'Variable Short-Range': 4} |
infilling_java | FactorizationTester | 138 | 140 | ['import junit.framework.TestCase;', 'import java.io.ByteArrayOutputStream;', 'import java.io.PrintStream;', 'import java.lang.Math;', '', '/**', ' * This class implements a relatively simple algorithm for computing', ' * (and printing) the prime factors of a number. At initialization,', ' * a list of primes is computed. Given a number, this list is then', ' * used to efficiently print the prime factors of the number.', ' */', 'class PrimeFactorizer {', '', ' // this class will store all primes between 2 and upperBound', ' private int upperBound;', ' ', ' // this class will be able to factorize all primes between 1 and maxNumberToFactorize', ' private long maxNumberToFactorize;', ' ', ' // this is a list of all of the prime numbers between 2 and upperBound', ' private int [] allPrimes;', ' ', ' // this is the number of primes found between 2 and upperBound', ' private int numPrimes;', ' ', ' // this is the output stream that the factorization will be printed to', ' private PrintStream resultStream;', ' ', ' /**', ' * This prints the prime factorization of a number in a "pretty" fashion.', ' * If the number passed in exceeds "upperBound", then a nice error message', ' * is printed. ', ' */', ' public void printPrimeFactorization (long numToFactorize) {', ' ', " // If we are given a number that's too small/big to factor, tell the user", ' if (numToFactorize < 1) {', ' resultStream.format ("Can\'t factorize a number less than 1");', ' return;', ' }', ' if (numToFactorize > maxNumberToFactorize) {', ' resultStream.format ("%d is too large to factorize", numToFactorize);', ' return;', ' }', ' ', ' // Now get ready to print the factorization', ' resultStream.format ("Prime factorization of %d is: ", numToFactorize);', ' ', ' // our basic tactice will be to find all of the primes that divide evenly into', ' // our target. When we find one, print it out and reduce the target accrordingly.', ' // When the target gets down to one, we are done.', ' ', ' // this is the index of the next prime we need to try', ' int curPosInAllPrimes = 0;', ' ', ' // tells us we are still waiting to print the first prime... important so we', ' // don\'t print the "x" symbol before the first one', ' boolean firstOne = true;', ' ', ' while (numToFactorize > 1 && curPosInAllPrimes < numPrimes) {', ' ', " // if the current prime divides evenly into the target, we've got a prime factor", ' if (numToFactorize % allPrimes[curPosInAllPrimes] == 0) {', ' ', ' // if it\'s the first one, we don\'t need to print a "x"', ' // print the factor & reset the firstOne flag', ' if (firstOne) {', ' resultStream.format ("%d", allPrimes[curPosInAllPrimes]);', ' firstOne = false;', ' ', ' // otherwise, print the factor pre-pended with an "x"', ' } else {', ' resultStream.format (" x %d", allPrimes[curPosInAllPrimes]);', ' }', ' ', ' // remove that prime factor from the target', ' numToFactorize /= allPrimes[curPosInAllPrimes];', ' ', ' // if the current prime does not divde evenly, try the next one', ' } else {', ' curPosInAllPrimes++;', ' }', ' }', ' ', ' // if we never printed any factors, then display the number itself', ' if (firstOne) {', ' resultStream.format ("%d", numToFactorize);', " // Otherwsie print the factors connected by 'x'", ' } else if (numToFactorize > 1) {', ' resultStream.format (" x %d", numToFactorize);', ' }', ' }', ' ', ' ', ' /**', ' * This is the constructor. What it does is to fill the array allPrimes with all', ' * of the prime numbers from 2 through sqrt(maxNumberToFactorize). This array of primes', ' * can then subsequently be used by the printPrimeFactorization method to actually', ' * compute the prime factorization of a number. The method also sets upperBound', ' * (the largest number we checked for primality) and numPrimes (the number of primes', ' * in allPimes). The algorithm used to compute the primes is the classic "sieve of ', ' * Eratosthenes" algorithm.', ' */', ' public PrimeFactorizer (long maxNumberToFactorizeIn, PrintStream outputStream) {', ' ', ' resultStream = outputStream;', ' maxNumberToFactorize = maxNumberToFactorizeIn;', ' ', " // initialize the two class variables- 'upperBound' and 'allPrimes' note that the prime candidates are", ' // from 2 to upperBound, so there are upperBound prime candidates intially', ' upperBound = (int) Math.ceil (Math.sqrt (maxNumberToFactorize));', ' allPrimes = new int[upperBound - 1];', ' ', ' // numIntsInList is the number of ints currently in the list.', ' int numIntsInList = upperBound - 1;', ' ', ' // the number of primes so far is zero', ' numPrimes = 0;', ' ', ' // write all of the candidate numbers to the list... this is all of the numbers', ' // from two to upperBound', ' for (int i = 0; i < upperBound - 1; i++) {', ' allPrimes[i] = i + 2;', ' }', ' ', ' // now we keep removing numbers from the list until we have only primes', ' while (numIntsInList > numPrimes) {', ' ', ' // curPos tells us the last slot that has a "good" (still possibly prime) value.', ' int curPos = numPrimes + 1;', ' ', ' // the front of the list is a prime... kill everyone who is a multiple of it', ' for (int i = numPrimes + 1; i < numIntsInList; i++) {', ' ', ' // if the dude at position i is not a multiple of the current prime, then', " // we keep him; otherwise, he'll be lost", ' if (allPrimes[i] % allPrimes[numPrimes] != 0) {'] | [' allPrimes[curPos] = allPrimes[i];', ' curPos++;', ' }'] | [' }', ' ', ' // the number of ints in the list is now equal to the last slot we wrote a value to', ' numIntsInList = curPos;', ' ', ' // and the guy at the front of the list is now considered a prime', ' numPrimes++;', ' ', ' }', ' }', ' ', '', '}', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', ' ', 'public class FactorizationTester extends TestCase {', ' /**', ' * Stream to hold the result of each test.', ' */', ' private ByteArrayOutputStream result;', '', ' /**', ' * Wrapper to provide printing functionality.', ' */', ' private PrintStream outputStream;', '', ' /**', ' * Setup the output streams before each test.', ' */ ', ' protected void setUp () {', ' result = new ByteArrayOutputStream();', ' outputStream = new PrintStream(result);', ' } ', ' ', ' /**', ' * Print a nice message about each test.', ' */', ' private void printInfo(String description, String expected, String actual) {', ' System.out.format ("\\n%s\\n", description);', ' System.out.format ("output:\\t%s\\n", actual);', ' System.out.format ("correct:\\t%s\\n", expected);', ' }', '', ' /**', ' * These are the various test methods. The first 10 test factorizations', ' * using the object constructed to factorize numbers up to 100; the latter', ' * 7 use the object to factorize numbers up to 100000.', ' */', ' public void test100MaxFactorize1() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (1);', '', ' // Print Results', ' String expected = new String("Prime factorization of 1 is: 1");', ' printInfo("Factorizing 1 using max 100", expected, result.toString());', '', ' // Check if test passed by comparing the expected and actual results', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 7 ', ' public void test100MaxFactorize7() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (7);', '', ' // Print Results', ' String expected = new String("Prime factorization of 7 is: 7");', ' printInfo("Factorizing 7 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 5', ' public void test100MaxFactorize5() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (5);', '', ' // Print Results', ' String expected = new String("Prime factorization of 5 is: 5");', ' printInfo("Factorizing 5 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 30', ' public void test100MaxFactorize30() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (30);', '', ' // Print Results', ' String expected = new String("Prime factorization of 30 is: 2 x 3 x 5");', ' printInfo("Factorizing 30 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 81', ' public void test100MaxFactorize81() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (81);', '', ' // Print Results', ' String expected = new String("Prime factorization of 81 is: 3 x 3 x 3 x 3");', ' printInfo("Factorizing 81 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 71', ' public void test100MaxFactorize71() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (71);', '', ' // Print Results', ' String expected = new String("Prime factorization of 71 is: 71");', ' printInfo("Factorizing 71 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 100', ' public void test100MaxFactorize100() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (100);', '', ' // Print Results', ' String expected = new String("Prime factorization of 100 is: 2 x 2 x 5 x 5");', ' printInfo("Factorizing 100 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 101', ' public void test100MaxFactorize101() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (101);', '', ' // Print Results', ' String expected = new String("101 is too large to factorize");', ' printInfo("Factorizing 101 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 0', ' public void test100MaxFactorize0() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (0);', '', ' // Print Results', ' String expected = new String("Can\'t factorize a number less than 1");', ' printInfo("Factorizing 0 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' // Test the factorization of 97', ' public void test100MaxFactorize97() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (97);', '', ' // Print Results', ' String expected = new String("Prime factorization of 97 is: 97");', ' printInfo("Factorizing 97 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 34534', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize34534() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (34534);', '', ' // Print Results', ' String expected = new String("Prime factorization of 34534 is: 2 x 31 x 557");', ' printInfo("Factorizing 34534 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 4339', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize4339() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (4339);', '', ' // Print Results', ' String expected = new String("Prime factorization of 4339 is: 4339");', ' printInfo("Factorizing 4339 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 65536', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize65536() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (65536);', '', ' // Print Results', ' String expected = new String("Prime factorization of 65536 is: 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2");', ' printInfo("Factorizing 65536 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 99797', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize99797() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (99797);', '', ' // Print Results', ' String expected = new String("Prime factorization of 99797 is: 23 x 4339");', ' printInfo("Factorizing 99797 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 307', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize307() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (307);', '', ' // Print Results', ' String expected = new String("Prime factorization of 307 is: 307");', ' printInfo("Factorizing 307 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 38845248344', ' // factorize numbers up to 100000000000', ' public void test100000000000MaxFactorize38845248344() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000000 = new PrimeFactorizer(100000000000L, outputStream);', ' myFactorizerMax100000000000.printPrimeFactorization (38845248344L);', '', ' // Print Results', ' String expected = new String("Prime factorization of 38845248344 is: 2 x 2 x 2 x 7 x 693665149");', ' printInfo("Factorizing 38845248344 using max 100000000000", expected, result.toString());', ' ', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' ', ' result.reset ();', ' myFactorizerMax100000000000.printPrimeFactorization (24210833220L);', ' expected = new String("Prime factorization of 24210833220 is: 2 x 2 x 3 x 3 x 5 x 7 x 17 x 19 x 19 x 31 x 101");', ' printInfo("Factorizing 24210833220 using max 100000000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' public void test100000000000MaxFactorize5387457483444() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000000 = new PrimeFactorizer(100000000000L, outputStream);', ' myFactorizerMax100000000000.printPrimeFactorization (5387457483444L);', '', ' // Print Results', ' String expected = new String("5387457483444 is too large to factorize");', ' printInfo("Factorizing 5387457483444 using max 100000000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' public void testSpeed() {', ' ', ' // here we factorize 10,000 large numbers; make sure that the constructor correctly sets', " // up the array of primes just once... if it does not, it'll take too long to run", ' PrimeFactorizer myFactorizerMax100000000000 = new PrimeFactorizer(100000000000L, outputStream);', ' for (long i = 38845248344L; i < 38845248344L + 50000; i++) {', ' myFactorizerMax100000000000.printPrimeFactorization (i);', ' if (i == 38845248344L) {', ' // Compare the Prime factorization of 38845248344 to the expected result', ' String expected = new String("Prime factorization of 38845248344 is: 2 x 2 x 2 x 7 x 693665149"); ', ' assertEquals (expected, result.toString());', ' }', ' }', ' ', ' // if we make it here, we pass the test', ' assertTrue (true);', ' }', ' ', '}'] | [{'reason_category': 'Loop Body', 'usage_line': 138}, {'reason_category': 'If Body', 'usage_line': 138}, {'reason_category': 'Loop Body', 'usage_line': 139}, {'reason_category': 'If Body', 'usage_line': 139}, {'reason_category': 'Loop Body', 'usage_line': 140}, {'reason_category': 'If Body', 'usage_line': 140}] | Global_Variable 'allPrimes' used at line 138 is defined at line 112 and has a Medium-Range dependency.
Variable 'i' used at line 138 is defined at line 133 and has a Short-Range dependency.
Variable 'curPos' used at line 138 is defined at line 130 and has a Short-Range dependency.
Variable 'curPos' used at line 139 is defined at line 130 and has a Short-Range dependency. | {'Loop Body': 3, 'If Body': 3} | {'Global_Variable Medium-Range': 1, 'Variable Short-Range': 3} |
infilling_java | FactorizationTester | 176 | 178 | ['import junit.framework.TestCase;', 'import java.io.ByteArrayOutputStream;', 'import java.io.PrintStream;', 'import java.lang.Math;', '', '/**', ' * This class implements a relatively simple algorithm for computing', ' * (and printing) the prime factors of a number. At initialization,', ' * a list of primes is computed. Given a number, this list is then', ' * used to efficiently print the prime factors of the number.', ' */', 'class PrimeFactorizer {', '', ' // this class will store all primes between 2 and upperBound', ' private int upperBound;', ' ', ' // this class will be able to factorize all primes between 1 and maxNumberToFactorize', ' private long maxNumberToFactorize;', ' ', ' // this is a list of all of the prime numbers between 2 and upperBound', ' private int [] allPrimes;', ' ', ' // this is the number of primes found between 2 and upperBound', ' private int numPrimes;', ' ', ' // this is the output stream that the factorization will be printed to', ' private PrintStream resultStream;', ' ', ' /**', ' * This prints the prime factorization of a number in a "pretty" fashion.', ' * If the number passed in exceeds "upperBound", then a nice error message', ' * is printed. ', ' */', ' public void printPrimeFactorization (long numToFactorize) {', ' ', " // If we are given a number that's too small/big to factor, tell the user", ' if (numToFactorize < 1) {', ' resultStream.format ("Can\'t factorize a number less than 1");', ' return;', ' }', ' if (numToFactorize > maxNumberToFactorize) {', ' resultStream.format ("%d is too large to factorize", numToFactorize);', ' return;', ' }', ' ', ' // Now get ready to print the factorization', ' resultStream.format ("Prime factorization of %d is: ", numToFactorize);', ' ', ' // our basic tactice will be to find all of the primes that divide evenly into', ' // our target. When we find one, print it out and reduce the target accrordingly.', ' // When the target gets down to one, we are done.', ' ', ' // this is the index of the next prime we need to try', ' int curPosInAllPrimes = 0;', ' ', ' // tells us we are still waiting to print the first prime... important so we', ' // don\'t print the "x" symbol before the first one', ' boolean firstOne = true;', ' ', ' while (numToFactorize > 1 && curPosInAllPrimes < numPrimes) {', ' ', " // if the current prime divides evenly into the target, we've got a prime factor", ' if (numToFactorize % allPrimes[curPosInAllPrimes] == 0) {', ' ', ' // if it\'s the first one, we don\'t need to print a "x"', ' // print the factor & reset the firstOne flag', ' if (firstOne) {', ' resultStream.format ("%d", allPrimes[curPosInAllPrimes]);', ' firstOne = false;', ' ', ' // otherwise, print the factor pre-pended with an "x"', ' } else {', ' resultStream.format (" x %d", allPrimes[curPosInAllPrimes]);', ' }', ' ', ' // remove that prime factor from the target', ' numToFactorize /= allPrimes[curPosInAllPrimes];', ' ', ' // if the current prime does not divde evenly, try the next one', ' } else {', ' curPosInAllPrimes++;', ' }', ' }', ' ', ' // if we never printed any factors, then display the number itself', ' if (firstOne) {', ' resultStream.format ("%d", numToFactorize);', " // Otherwsie print the factors connected by 'x'", ' } else if (numToFactorize > 1) {', ' resultStream.format (" x %d", numToFactorize);', ' }', ' }', ' ', ' ', ' /**', ' * This is the constructor. What it does is to fill the array allPrimes with all', ' * of the prime numbers from 2 through sqrt(maxNumberToFactorize). This array of primes', ' * can then subsequently be used by the printPrimeFactorization method to actually', ' * compute the prime factorization of a number. The method also sets upperBound', ' * (the largest number we checked for primality) and numPrimes (the number of primes', ' * in allPimes). The algorithm used to compute the primes is the classic "sieve of ', ' * Eratosthenes" algorithm.', ' */', ' public PrimeFactorizer (long maxNumberToFactorizeIn, PrintStream outputStream) {', ' ', ' resultStream = outputStream;', ' maxNumberToFactorize = maxNumberToFactorizeIn;', ' ', " // initialize the two class variables- 'upperBound' and 'allPrimes' note that the prime candidates are", ' // from 2 to upperBound, so there are upperBound prime candidates intially', ' upperBound = (int) Math.ceil (Math.sqrt (maxNumberToFactorize));', ' allPrimes = new int[upperBound - 1];', ' ', ' // numIntsInList is the number of ints currently in the list.', ' int numIntsInList = upperBound - 1;', ' ', ' // the number of primes so far is zero', ' numPrimes = 0;', ' ', ' // write all of the candidate numbers to the list... this is all of the numbers', ' // from two to upperBound', ' for (int i = 0; i < upperBound - 1; i++) {', ' allPrimes[i] = i + 2;', ' }', ' ', ' // now we keep removing numbers from the list until we have only primes', ' while (numIntsInList > numPrimes) {', ' ', ' // curPos tells us the last slot that has a "good" (still possibly prime) value.', ' int curPos = numPrimes + 1;', ' ', ' // the front of the list is a prime... kill everyone who is a multiple of it', ' for (int i = numPrimes + 1; i < numIntsInList; i++) {', ' ', ' // if the dude at position i is not a multiple of the current prime, then', " // we keep him; otherwise, he'll be lost", ' if (allPrimes[i] % allPrimes[numPrimes] != 0) {', ' allPrimes[curPos] = allPrimes[i];', ' curPos++;', ' }', ' }', ' ', ' // the number of ints in the list is now equal to the last slot we wrote a value to', ' numIntsInList = curPos;', ' ', ' // and the guy at the front of the list is now considered a prime', ' numPrimes++;', ' ', ' }', ' }', ' ', '', '}', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', ' ', 'public class FactorizationTester extends TestCase {', ' /**', ' * Stream to hold the result of each test.', ' */', ' private ByteArrayOutputStream result;', '', ' /**', ' * Wrapper to provide printing functionality.', ' */', ' private PrintStream outputStream;', '', ' /**', ' * Setup the output streams before each test.', ' */ ', ' protected void setUp () {'] | [' result = new ByteArrayOutputStream();', ' outputStream = new PrintStream(result);', ' } '] | [' ', ' /**', ' * Print a nice message about each test.', ' */', ' private void printInfo(String description, String expected, String actual) {', ' System.out.format ("\\n%s\\n", description);', ' System.out.format ("output:\\t%s\\n", actual);', ' System.out.format ("correct:\\t%s\\n", expected);', ' }', '', ' /**', ' * These are the various test methods. The first 10 test factorizations', ' * using the object constructed to factorize numbers up to 100; the latter', ' * 7 use the object to factorize numbers up to 100000.', ' */', ' public void test100MaxFactorize1() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (1);', '', ' // Print Results', ' String expected = new String("Prime factorization of 1 is: 1");', ' printInfo("Factorizing 1 using max 100", expected, result.toString());', '', ' // Check if test passed by comparing the expected and actual results', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 7 ', ' public void test100MaxFactorize7() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (7);', '', ' // Print Results', ' String expected = new String("Prime factorization of 7 is: 7");', ' printInfo("Factorizing 7 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 5', ' public void test100MaxFactorize5() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (5);', '', ' // Print Results', ' String expected = new String("Prime factorization of 5 is: 5");', ' printInfo("Factorizing 5 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 30', ' public void test100MaxFactorize30() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (30);', '', ' // Print Results', ' String expected = new String("Prime factorization of 30 is: 2 x 3 x 5");', ' printInfo("Factorizing 30 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 81', ' public void test100MaxFactorize81() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (81);', '', ' // Print Results', ' String expected = new String("Prime factorization of 81 is: 3 x 3 x 3 x 3");', ' printInfo("Factorizing 81 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 71', ' public void test100MaxFactorize71() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (71);', '', ' // Print Results', ' String expected = new String("Prime factorization of 71 is: 71");', ' printInfo("Factorizing 71 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 100', ' public void test100MaxFactorize100() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (100);', '', ' // Print Results', ' String expected = new String("Prime factorization of 100 is: 2 x 2 x 5 x 5");', ' printInfo("Factorizing 100 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 101', ' public void test100MaxFactorize101() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (101);', '', ' // Print Results', ' String expected = new String("101 is too large to factorize");', ' printInfo("Factorizing 101 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 0', ' public void test100MaxFactorize0() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (0);', '', ' // Print Results', ' String expected = new String("Can\'t factorize a number less than 1");', ' printInfo("Factorizing 0 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' // Test the factorization of 97', ' public void test100MaxFactorize97() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (97);', '', ' // Print Results', ' String expected = new String("Prime factorization of 97 is: 97");', ' printInfo("Factorizing 97 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 34534', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize34534() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (34534);', '', ' // Print Results', ' String expected = new String("Prime factorization of 34534 is: 2 x 31 x 557");', ' printInfo("Factorizing 34534 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 4339', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize4339() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (4339);', '', ' // Print Results', ' String expected = new String("Prime factorization of 4339 is: 4339");', ' printInfo("Factorizing 4339 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 65536', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize65536() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (65536);', '', ' // Print Results', ' String expected = new String("Prime factorization of 65536 is: 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2");', ' printInfo("Factorizing 65536 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 99797', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize99797() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (99797);', '', ' // Print Results', ' String expected = new String("Prime factorization of 99797 is: 23 x 4339");', ' printInfo("Factorizing 99797 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 307', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize307() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (307);', '', ' // Print Results', ' String expected = new String("Prime factorization of 307 is: 307");', ' printInfo("Factorizing 307 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 38845248344', ' // factorize numbers up to 100000000000', ' public void test100000000000MaxFactorize38845248344() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000000 = new PrimeFactorizer(100000000000L, outputStream);', ' myFactorizerMax100000000000.printPrimeFactorization (38845248344L);', '', ' // Print Results', ' String expected = new String("Prime factorization of 38845248344 is: 2 x 2 x 2 x 7 x 693665149");', ' printInfo("Factorizing 38845248344 using max 100000000000", expected, result.toString());', ' ', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' ', ' result.reset ();', ' myFactorizerMax100000000000.printPrimeFactorization (24210833220L);', ' expected = new String("Prime factorization of 24210833220 is: 2 x 2 x 3 x 3 x 5 x 7 x 17 x 19 x 19 x 31 x 101");', ' printInfo("Factorizing 24210833220 using max 100000000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' public void test100000000000MaxFactorize5387457483444() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000000 = new PrimeFactorizer(100000000000L, outputStream);', ' myFactorizerMax100000000000.printPrimeFactorization (5387457483444L);', '', ' // Print Results', ' String expected = new String("5387457483444 is too large to factorize");', ' printInfo("Factorizing 5387457483444 using max 100000000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' public void testSpeed() {', ' ', ' // here we factorize 10,000 large numbers; make sure that the constructor correctly sets', " // up the array of primes just once... if it does not, it'll take too long to run", ' PrimeFactorizer myFactorizerMax100000000000 = new PrimeFactorizer(100000000000L, outputStream);', ' for (long i = 38845248344L; i < 38845248344L + 50000; i++) {', ' myFactorizerMax100000000000.printPrimeFactorization (i);', ' if (i == 38845248344L) {', ' // Compare the Prime factorization of 38845248344 to the expected result', ' String expected = new String("Prime factorization of 38845248344 is: 2 x 2 x 2 x 7 x 693665149"); ', ' assertEquals (expected, result.toString());', ' }', ' }', ' ', ' // if we make it here, we pass the test', ' assertTrue (true);', ' }', ' ', '}'] | [] | Global_Variable 'result' used at line 176 is defined at line 165 and has a Medium-Range dependency.
Global_Variable 'result' used at line 177 is defined at line 176 and has a Short-Range dependency.
Global_Variable 'outputStream' used at line 177 is defined at line 170 and has a Short-Range dependency. | {} | {'Global_Variable Medium-Range': 1, 'Global_Variable Short-Range': 2} |
infilling_java | FactorizationTester | 210 | 219 | ['import junit.framework.TestCase;', 'import java.io.ByteArrayOutputStream;', 'import java.io.PrintStream;', 'import java.lang.Math;', '', '/**', ' * This class implements a relatively simple algorithm for computing', ' * (and printing) the prime factors of a number. At initialization,', ' * a list of primes is computed. Given a number, this list is then', ' * used to efficiently print the prime factors of the number.', ' */', 'class PrimeFactorizer {', '', ' // this class will store all primes between 2 and upperBound', ' private int upperBound;', ' ', ' // this class will be able to factorize all primes between 1 and maxNumberToFactorize', ' private long maxNumberToFactorize;', ' ', ' // this is a list of all of the prime numbers between 2 and upperBound', ' private int [] allPrimes;', ' ', ' // this is the number of primes found between 2 and upperBound', ' private int numPrimes;', ' ', ' // this is the output stream that the factorization will be printed to', ' private PrintStream resultStream;', ' ', ' /**', ' * This prints the prime factorization of a number in a "pretty" fashion.', ' * If the number passed in exceeds "upperBound", then a nice error message', ' * is printed. ', ' */', ' public void printPrimeFactorization (long numToFactorize) {', ' ', " // If we are given a number that's too small/big to factor, tell the user", ' if (numToFactorize < 1) {', ' resultStream.format ("Can\'t factorize a number less than 1");', ' return;', ' }', ' if (numToFactorize > maxNumberToFactorize) {', ' resultStream.format ("%d is too large to factorize", numToFactorize);', ' return;', ' }', ' ', ' // Now get ready to print the factorization', ' resultStream.format ("Prime factorization of %d is: ", numToFactorize);', ' ', ' // our basic tactice will be to find all of the primes that divide evenly into', ' // our target. When we find one, print it out and reduce the target accrordingly.', ' // When the target gets down to one, we are done.', ' ', ' // this is the index of the next prime we need to try', ' int curPosInAllPrimes = 0;', ' ', ' // tells us we are still waiting to print the first prime... important so we', ' // don\'t print the "x" symbol before the first one', ' boolean firstOne = true;', ' ', ' while (numToFactorize > 1 && curPosInAllPrimes < numPrimes) {', ' ', " // if the current prime divides evenly into the target, we've got a prime factor", ' if (numToFactorize % allPrimes[curPosInAllPrimes] == 0) {', ' ', ' // if it\'s the first one, we don\'t need to print a "x"', ' // print the factor & reset the firstOne flag', ' if (firstOne) {', ' resultStream.format ("%d", allPrimes[curPosInAllPrimes]);', ' firstOne = false;', ' ', ' // otherwise, print the factor pre-pended with an "x"', ' } else {', ' resultStream.format (" x %d", allPrimes[curPosInAllPrimes]);', ' }', ' ', ' // remove that prime factor from the target', ' numToFactorize /= allPrimes[curPosInAllPrimes];', ' ', ' // if the current prime does not divde evenly, try the next one', ' } else {', ' curPosInAllPrimes++;', ' }', ' }', ' ', ' // if we never printed any factors, then display the number itself', ' if (firstOne) {', ' resultStream.format ("%d", numToFactorize);', " // Otherwsie print the factors connected by 'x'", ' } else if (numToFactorize > 1) {', ' resultStream.format (" x %d", numToFactorize);', ' }', ' }', ' ', ' ', ' /**', ' * This is the constructor. What it does is to fill the array allPrimes with all', ' * of the prime numbers from 2 through sqrt(maxNumberToFactorize). This array of primes', ' * can then subsequently be used by the printPrimeFactorization method to actually', ' * compute the prime factorization of a number. The method also sets upperBound', ' * (the largest number we checked for primality) and numPrimes (the number of primes', ' * in allPimes). The algorithm used to compute the primes is the classic "sieve of ', ' * Eratosthenes" algorithm.', ' */', ' public PrimeFactorizer (long maxNumberToFactorizeIn, PrintStream outputStream) {', ' ', ' resultStream = outputStream;', ' maxNumberToFactorize = maxNumberToFactorizeIn;', ' ', " // initialize the two class variables- 'upperBound' and 'allPrimes' note that the prime candidates are", ' // from 2 to upperBound, so there are upperBound prime candidates intially', ' upperBound = (int) Math.ceil (Math.sqrt (maxNumberToFactorize));', ' allPrimes = new int[upperBound - 1];', ' ', ' // numIntsInList is the number of ints currently in the list.', ' int numIntsInList = upperBound - 1;', ' ', ' // the number of primes so far is zero', ' numPrimes = 0;', ' ', ' // write all of the candidate numbers to the list... this is all of the numbers', ' // from two to upperBound', ' for (int i = 0; i < upperBound - 1; i++) {', ' allPrimes[i] = i + 2;', ' }', ' ', ' // now we keep removing numbers from the list until we have only primes', ' while (numIntsInList > numPrimes) {', ' ', ' // curPos tells us the last slot that has a "good" (still possibly prime) value.', ' int curPos = numPrimes + 1;', ' ', ' // the front of the list is a prime... kill everyone who is a multiple of it', ' for (int i = numPrimes + 1; i < numIntsInList; i++) {', ' ', ' // if the dude at position i is not a multiple of the current prime, then', " // we keep him; otherwise, he'll be lost", ' if (allPrimes[i] % allPrimes[numPrimes] != 0) {', ' allPrimes[curPos] = allPrimes[i];', ' curPos++;', ' }', ' }', ' ', ' // the number of ints in the list is now equal to the last slot we wrote a value to', ' numIntsInList = curPos;', ' ', ' // and the guy at the front of the list is now considered a prime', ' numPrimes++;', ' ', ' }', ' }', ' ', '', '}', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', ' ', 'public class FactorizationTester extends TestCase {', ' /**', ' * Stream to hold the result of each test.', ' */', ' private ByteArrayOutputStream result;', '', ' /**', ' * Wrapper to provide printing functionality.', ' */', ' private PrintStream outputStream;', '', ' /**', ' * Setup the output streams before each test.', ' */ ', ' protected void setUp () {', ' result = new ByteArrayOutputStream();', ' outputStream = new PrintStream(result);', ' } ', ' ', ' /**', ' * Print a nice message about each test.', ' */', ' private void printInfo(String description, String expected, String actual) {', ' System.out.format ("\\n%s\\n", description);', ' System.out.format ("output:\\t%s\\n", actual);', ' System.out.format ("correct:\\t%s\\n", expected);', ' }', '', ' /**', ' * These are the various test methods. The first 10 test factorizations', ' * using the object constructed to factorize numbers up to 100; the latter', ' * 7 use the object to factorize numbers up to 100000.', ' */', ' public void test100MaxFactorize1() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (1);', '', ' // Print Results', ' String expected = new String("Prime factorization of 1 is: 1");', ' printInfo("Factorizing 1 using max 100", expected, result.toString());', '', ' // Check if test passed by comparing the expected and actual results', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 7 ', ' public void test100MaxFactorize7() {', ' // Factorize the number'] | [' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (7);', '', ' // Print Results', ' String expected = new String("Prime factorization of 7 is: 7");', ' printInfo("Factorizing 7 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }'] | ['', ' // Test the factorization of 5', ' public void test100MaxFactorize5() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (5);', '', ' // Print Results', ' String expected = new String("Prime factorization of 5 is: 5");', ' printInfo("Factorizing 5 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 30', ' public void test100MaxFactorize30() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (30);', '', ' // Print Results', ' String expected = new String("Prime factorization of 30 is: 2 x 3 x 5");', ' printInfo("Factorizing 30 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 81', ' public void test100MaxFactorize81() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (81);', '', ' // Print Results', ' String expected = new String("Prime factorization of 81 is: 3 x 3 x 3 x 3");', ' printInfo("Factorizing 81 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 71', ' public void test100MaxFactorize71() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (71);', '', ' // Print Results', ' String expected = new String("Prime factorization of 71 is: 71");', ' printInfo("Factorizing 71 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 100', ' public void test100MaxFactorize100() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (100);', '', ' // Print Results', ' String expected = new String("Prime factorization of 100 is: 2 x 2 x 5 x 5");', ' printInfo("Factorizing 100 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 101', ' public void test100MaxFactorize101() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (101);', '', ' // Print Results', ' String expected = new String("101 is too large to factorize");', ' printInfo("Factorizing 101 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 0', ' public void test100MaxFactorize0() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (0);', '', ' // Print Results', ' String expected = new String("Can\'t factorize a number less than 1");', ' printInfo("Factorizing 0 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' // Test the factorization of 97', ' public void test100MaxFactorize97() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (97);', '', ' // Print Results', ' String expected = new String("Prime factorization of 97 is: 97");', ' printInfo("Factorizing 97 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 34534', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize34534() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (34534);', '', ' // Print Results', ' String expected = new String("Prime factorization of 34534 is: 2 x 31 x 557");', ' printInfo("Factorizing 34534 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 4339', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize4339() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (4339);', '', ' // Print Results', ' String expected = new String("Prime factorization of 4339 is: 4339");', ' printInfo("Factorizing 4339 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 65536', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize65536() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (65536);', '', ' // Print Results', ' String expected = new String("Prime factorization of 65536 is: 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2");', ' printInfo("Factorizing 65536 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 99797', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize99797() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (99797);', '', ' // Print Results', ' String expected = new String("Prime factorization of 99797 is: 23 x 4339");', ' printInfo("Factorizing 99797 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 307', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize307() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (307);', '', ' // Print Results', ' String expected = new String("Prime factorization of 307 is: 307");', ' printInfo("Factorizing 307 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 38845248344', ' // factorize numbers up to 100000000000', ' public void test100000000000MaxFactorize38845248344() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000000 = new PrimeFactorizer(100000000000L, outputStream);', ' myFactorizerMax100000000000.printPrimeFactorization (38845248344L);', '', ' // Print Results', ' String expected = new String("Prime factorization of 38845248344 is: 2 x 2 x 2 x 7 x 693665149");', ' printInfo("Factorizing 38845248344 using max 100000000000", expected, result.toString());', ' ', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' ', ' result.reset ();', ' myFactorizerMax100000000000.printPrimeFactorization (24210833220L);', ' expected = new String("Prime factorization of 24210833220 is: 2 x 2 x 3 x 3 x 5 x 7 x 17 x 19 x 19 x 31 x 101");', ' printInfo("Factorizing 24210833220 using max 100000000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' public void test100000000000MaxFactorize5387457483444() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000000 = new PrimeFactorizer(100000000000L, outputStream);', ' myFactorizerMax100000000000.printPrimeFactorization (5387457483444L);', '', ' // Print Results', ' String expected = new String("5387457483444 is too large to factorize");', ' printInfo("Factorizing 5387457483444 using max 100000000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' public void testSpeed() {', ' ', ' // here we factorize 10,000 large numbers; make sure that the constructor correctly sets', " // up the array of primes just once... if it does not, it'll take too long to run", ' PrimeFactorizer myFactorizerMax100000000000 = new PrimeFactorizer(100000000000L, outputStream);', ' for (long i = 38845248344L; i < 38845248344L + 50000; i++) {', ' myFactorizerMax100000000000.printPrimeFactorization (i);', ' if (i == 38845248344L) {', ' // Compare the Prime factorization of 38845248344 to the expected result', ' String expected = new String("Prime factorization of 38845248344 is: 2 x 2 x 2 x 7 x 693665149"); ', ' assertEquals (expected, result.toString());', ' }', ' }', ' ', ' // if we make it here, we pass the test', ' assertTrue (true);', ' }', ' ', '}'] | [] | Class 'PrimeFactorizer' used at line 210 is defined at line 12 and has a Long-Range dependency.
Global_Variable 'outputStream' used at line 210 is defined at line 170 and has a Long-Range dependency.
Function 'PrimeFactorizer.printPrimeFactorization' used at line 211 is defined at line 34 and has a Long-Range dependency.
Function 'printInfo' used at line 215 is defined at line 183 and has a Long-Range dependency.
Variable 'expected' used at line 215 is defined at line 214 and has a Short-Range dependency.
Global_Variable 'result' used at line 215 is defined at line 165 and has a Long-Range dependency.
Variable 'expected' used at line 218 is defined at line 214 and has a Short-Range dependency.
Global_Variable 'result' used at line 218 is defined at line 165 and has a Long-Range dependency. | {} | {'Class Long-Range': 1, 'Global_Variable Long-Range': 3, 'Function Long-Range': 2, 'Variable Short-Range': 2} |
infilling_java | FactorizationTester | 224 | 233 | ['import junit.framework.TestCase;', 'import java.io.ByteArrayOutputStream;', 'import java.io.PrintStream;', 'import java.lang.Math;', '', '/**', ' * This class implements a relatively simple algorithm for computing', ' * (and printing) the prime factors of a number. At initialization,', ' * a list of primes is computed. Given a number, this list is then', ' * used to efficiently print the prime factors of the number.', ' */', 'class PrimeFactorizer {', '', ' // this class will store all primes between 2 and upperBound', ' private int upperBound;', ' ', ' // this class will be able to factorize all primes between 1 and maxNumberToFactorize', ' private long maxNumberToFactorize;', ' ', ' // this is a list of all of the prime numbers between 2 and upperBound', ' private int [] allPrimes;', ' ', ' // this is the number of primes found between 2 and upperBound', ' private int numPrimes;', ' ', ' // this is the output stream that the factorization will be printed to', ' private PrintStream resultStream;', ' ', ' /**', ' * This prints the prime factorization of a number in a "pretty" fashion.', ' * If the number passed in exceeds "upperBound", then a nice error message', ' * is printed. ', ' */', ' public void printPrimeFactorization (long numToFactorize) {', ' ', " // If we are given a number that's too small/big to factor, tell the user", ' if (numToFactorize < 1) {', ' resultStream.format ("Can\'t factorize a number less than 1");', ' return;', ' }', ' if (numToFactorize > maxNumberToFactorize) {', ' resultStream.format ("%d is too large to factorize", numToFactorize);', ' return;', ' }', ' ', ' // Now get ready to print the factorization', ' resultStream.format ("Prime factorization of %d is: ", numToFactorize);', ' ', ' // our basic tactice will be to find all of the primes that divide evenly into', ' // our target. When we find one, print it out and reduce the target accrordingly.', ' // When the target gets down to one, we are done.', ' ', ' // this is the index of the next prime we need to try', ' int curPosInAllPrimes = 0;', ' ', ' // tells us we are still waiting to print the first prime... important so we', ' // don\'t print the "x" symbol before the first one', ' boolean firstOne = true;', ' ', ' while (numToFactorize > 1 && curPosInAllPrimes < numPrimes) {', ' ', " // if the current prime divides evenly into the target, we've got a prime factor", ' if (numToFactorize % allPrimes[curPosInAllPrimes] == 0) {', ' ', ' // if it\'s the first one, we don\'t need to print a "x"', ' // print the factor & reset the firstOne flag', ' if (firstOne) {', ' resultStream.format ("%d", allPrimes[curPosInAllPrimes]);', ' firstOne = false;', ' ', ' // otherwise, print the factor pre-pended with an "x"', ' } else {', ' resultStream.format (" x %d", allPrimes[curPosInAllPrimes]);', ' }', ' ', ' // remove that prime factor from the target', ' numToFactorize /= allPrimes[curPosInAllPrimes];', ' ', ' // if the current prime does not divde evenly, try the next one', ' } else {', ' curPosInAllPrimes++;', ' }', ' }', ' ', ' // if we never printed any factors, then display the number itself', ' if (firstOne) {', ' resultStream.format ("%d", numToFactorize);', " // Otherwsie print the factors connected by 'x'", ' } else if (numToFactorize > 1) {', ' resultStream.format (" x %d", numToFactorize);', ' }', ' }', ' ', ' ', ' /**', ' * This is the constructor. What it does is to fill the array allPrimes with all', ' * of the prime numbers from 2 through sqrt(maxNumberToFactorize). This array of primes', ' * can then subsequently be used by the printPrimeFactorization method to actually', ' * compute the prime factorization of a number. The method also sets upperBound', ' * (the largest number we checked for primality) and numPrimes (the number of primes', ' * in allPimes). The algorithm used to compute the primes is the classic "sieve of ', ' * Eratosthenes" algorithm.', ' */', ' public PrimeFactorizer (long maxNumberToFactorizeIn, PrintStream outputStream) {', ' ', ' resultStream = outputStream;', ' maxNumberToFactorize = maxNumberToFactorizeIn;', ' ', " // initialize the two class variables- 'upperBound' and 'allPrimes' note that the prime candidates are", ' // from 2 to upperBound, so there are upperBound prime candidates intially', ' upperBound = (int) Math.ceil (Math.sqrt (maxNumberToFactorize));', ' allPrimes = new int[upperBound - 1];', ' ', ' // numIntsInList is the number of ints currently in the list.', ' int numIntsInList = upperBound - 1;', ' ', ' // the number of primes so far is zero', ' numPrimes = 0;', ' ', ' // write all of the candidate numbers to the list... this is all of the numbers', ' // from two to upperBound', ' for (int i = 0; i < upperBound - 1; i++) {', ' allPrimes[i] = i + 2;', ' }', ' ', ' // now we keep removing numbers from the list until we have only primes', ' while (numIntsInList > numPrimes) {', ' ', ' // curPos tells us the last slot that has a "good" (still possibly prime) value.', ' int curPos = numPrimes + 1;', ' ', ' // the front of the list is a prime... kill everyone who is a multiple of it', ' for (int i = numPrimes + 1; i < numIntsInList; i++) {', ' ', ' // if the dude at position i is not a multiple of the current prime, then', " // we keep him; otherwise, he'll be lost", ' if (allPrimes[i] % allPrimes[numPrimes] != 0) {', ' allPrimes[curPos] = allPrimes[i];', ' curPos++;', ' }', ' }', ' ', ' // the number of ints in the list is now equal to the last slot we wrote a value to', ' numIntsInList = curPos;', ' ', ' // and the guy at the front of the list is now considered a prime', ' numPrimes++;', ' ', ' }', ' }', ' ', '', '}', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', ' ', 'public class FactorizationTester extends TestCase {', ' /**', ' * Stream to hold the result of each test.', ' */', ' private ByteArrayOutputStream result;', '', ' /**', ' * Wrapper to provide printing functionality.', ' */', ' private PrintStream outputStream;', '', ' /**', ' * Setup the output streams before each test.', ' */ ', ' protected void setUp () {', ' result = new ByteArrayOutputStream();', ' outputStream = new PrintStream(result);', ' } ', ' ', ' /**', ' * Print a nice message about each test.', ' */', ' private void printInfo(String description, String expected, String actual) {', ' System.out.format ("\\n%s\\n", description);', ' System.out.format ("output:\\t%s\\n", actual);', ' System.out.format ("correct:\\t%s\\n", expected);', ' }', '', ' /**', ' * These are the various test methods. The first 10 test factorizations', ' * using the object constructed to factorize numbers up to 100; the latter', ' * 7 use the object to factorize numbers up to 100000.', ' */', ' public void test100MaxFactorize1() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (1);', '', ' // Print Results', ' String expected = new String("Prime factorization of 1 is: 1");', ' printInfo("Factorizing 1 using max 100", expected, result.toString());', '', ' // Check if test passed by comparing the expected and actual results', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 7 ', ' public void test100MaxFactorize7() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (7);', '', ' // Print Results', ' String expected = new String("Prime factorization of 7 is: 7");', ' printInfo("Factorizing 7 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 5', ' public void test100MaxFactorize5() {', ' // Factorize the number'] | [' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (5);', '', ' // Print Results', ' String expected = new String("Prime factorization of 5 is: 5");', ' printInfo("Factorizing 5 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }'] | [' ', ' // Test the factorization of 30', ' public void test100MaxFactorize30() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (30);', '', ' // Print Results', ' String expected = new String("Prime factorization of 30 is: 2 x 3 x 5");', ' printInfo("Factorizing 30 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 81', ' public void test100MaxFactorize81() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (81);', '', ' // Print Results', ' String expected = new String("Prime factorization of 81 is: 3 x 3 x 3 x 3");', ' printInfo("Factorizing 81 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 71', ' public void test100MaxFactorize71() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (71);', '', ' // Print Results', ' String expected = new String("Prime factorization of 71 is: 71");', ' printInfo("Factorizing 71 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 100', ' public void test100MaxFactorize100() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (100);', '', ' // Print Results', ' String expected = new String("Prime factorization of 100 is: 2 x 2 x 5 x 5");', ' printInfo("Factorizing 100 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 101', ' public void test100MaxFactorize101() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (101);', '', ' // Print Results', ' String expected = new String("101 is too large to factorize");', ' printInfo("Factorizing 101 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 0', ' public void test100MaxFactorize0() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (0);', '', ' // Print Results', ' String expected = new String("Can\'t factorize a number less than 1");', ' printInfo("Factorizing 0 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' // Test the factorization of 97', ' public void test100MaxFactorize97() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (97);', '', ' // Print Results', ' String expected = new String("Prime factorization of 97 is: 97");', ' printInfo("Factorizing 97 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 34534', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize34534() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (34534);', '', ' // Print Results', ' String expected = new String("Prime factorization of 34534 is: 2 x 31 x 557");', ' printInfo("Factorizing 34534 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 4339', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize4339() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (4339);', '', ' // Print Results', ' String expected = new String("Prime factorization of 4339 is: 4339");', ' printInfo("Factorizing 4339 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 65536', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize65536() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (65536);', '', ' // Print Results', ' String expected = new String("Prime factorization of 65536 is: 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2");', ' printInfo("Factorizing 65536 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 99797', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize99797() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (99797);', '', ' // Print Results', ' String expected = new String("Prime factorization of 99797 is: 23 x 4339");', ' printInfo("Factorizing 99797 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 307', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize307() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (307);', '', ' // Print Results', ' String expected = new String("Prime factorization of 307 is: 307");', ' printInfo("Factorizing 307 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 38845248344', ' // factorize numbers up to 100000000000', ' public void test100000000000MaxFactorize38845248344() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000000 = new PrimeFactorizer(100000000000L, outputStream);', ' myFactorizerMax100000000000.printPrimeFactorization (38845248344L);', '', ' // Print Results', ' String expected = new String("Prime factorization of 38845248344 is: 2 x 2 x 2 x 7 x 693665149");', ' printInfo("Factorizing 38845248344 using max 100000000000", expected, result.toString());', ' ', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' ', ' result.reset ();', ' myFactorizerMax100000000000.printPrimeFactorization (24210833220L);', ' expected = new String("Prime factorization of 24210833220 is: 2 x 2 x 3 x 3 x 5 x 7 x 17 x 19 x 19 x 31 x 101");', ' printInfo("Factorizing 24210833220 using max 100000000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' public void test100000000000MaxFactorize5387457483444() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000000 = new PrimeFactorizer(100000000000L, outputStream);', ' myFactorizerMax100000000000.printPrimeFactorization (5387457483444L);', '', ' // Print Results', ' String expected = new String("5387457483444 is too large to factorize");', ' printInfo("Factorizing 5387457483444 using max 100000000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' public void testSpeed() {', ' ', ' // here we factorize 10,000 large numbers; make sure that the constructor correctly sets', " // up the array of primes just once... if it does not, it'll take too long to run", ' PrimeFactorizer myFactorizerMax100000000000 = new PrimeFactorizer(100000000000L, outputStream);', ' for (long i = 38845248344L; i < 38845248344L + 50000; i++) {', ' myFactorizerMax100000000000.printPrimeFactorization (i);', ' if (i == 38845248344L) {', ' // Compare the Prime factorization of 38845248344 to the expected result', ' String expected = new String("Prime factorization of 38845248344 is: 2 x 2 x 2 x 7 x 693665149"); ', ' assertEquals (expected, result.toString());', ' }', ' }', ' ', ' // if we make it here, we pass the test', ' assertTrue (true);', ' }', ' ', '}'] | [] | Class 'PrimeFactorizer' used at line 224 is defined at line 12 and has a Long-Range dependency.
Global_Variable 'outputStream' used at line 224 is defined at line 170 and has a Long-Range dependency.
Function 'PrimeFactorizer.printPrimeFactorization' used at line 225 is defined at line 34 and has a Long-Range dependency.
Function 'printInfo' used at line 229 is defined at line 183 and has a Long-Range dependency.
Variable 'expected' used at line 229 is defined at line 228 and has a Short-Range dependency.
Global_Variable 'result' used at line 229 is defined at line 165 and has a Long-Range dependency.
Variable 'expected' used at line 232 is defined at line 228 and has a Short-Range dependency.
Global_Variable 'result' used at line 232 is defined at line 165 and has a Long-Range dependency. | {} | {'Class Long-Range': 1, 'Global_Variable Long-Range': 3, 'Function Long-Range': 2, 'Variable Short-Range': 2} |
infilling_java | FactorizationTester | 321 | 330 | ['import junit.framework.TestCase;', 'import java.io.ByteArrayOutputStream;', 'import java.io.PrintStream;', 'import java.lang.Math;', '', '/**', ' * This class implements a relatively simple algorithm for computing', ' * (and printing) the prime factors of a number. At initialization,', ' * a list of primes is computed. Given a number, this list is then', ' * used to efficiently print the prime factors of the number.', ' */', 'class PrimeFactorizer {', '', ' // this class will store all primes between 2 and upperBound', ' private int upperBound;', ' ', ' // this class will be able to factorize all primes between 1 and maxNumberToFactorize', ' private long maxNumberToFactorize;', ' ', ' // this is a list of all of the prime numbers between 2 and upperBound', ' private int [] allPrimes;', ' ', ' // this is the number of primes found between 2 and upperBound', ' private int numPrimes;', ' ', ' // this is the output stream that the factorization will be printed to', ' private PrintStream resultStream;', ' ', ' /**', ' * This prints the prime factorization of a number in a "pretty" fashion.', ' * If the number passed in exceeds "upperBound", then a nice error message', ' * is printed. ', ' */', ' public void printPrimeFactorization (long numToFactorize) {', ' ', " // If we are given a number that's too small/big to factor, tell the user", ' if (numToFactorize < 1) {', ' resultStream.format ("Can\'t factorize a number less than 1");', ' return;', ' }', ' if (numToFactorize > maxNumberToFactorize) {', ' resultStream.format ("%d is too large to factorize", numToFactorize);', ' return;', ' }', ' ', ' // Now get ready to print the factorization', ' resultStream.format ("Prime factorization of %d is: ", numToFactorize);', ' ', ' // our basic tactice will be to find all of the primes that divide evenly into', ' // our target. When we find one, print it out and reduce the target accrordingly.', ' // When the target gets down to one, we are done.', ' ', ' // this is the index of the next prime we need to try', ' int curPosInAllPrimes = 0;', ' ', ' // tells us we are still waiting to print the first prime... important so we', ' // don\'t print the "x" symbol before the first one', ' boolean firstOne = true;', ' ', ' while (numToFactorize > 1 && curPosInAllPrimes < numPrimes) {', ' ', " // if the current prime divides evenly into the target, we've got a prime factor", ' if (numToFactorize % allPrimes[curPosInAllPrimes] == 0) {', ' ', ' // if it\'s the first one, we don\'t need to print a "x"', ' // print the factor & reset the firstOne flag', ' if (firstOne) {', ' resultStream.format ("%d", allPrimes[curPosInAllPrimes]);', ' firstOne = false;', ' ', ' // otherwise, print the factor pre-pended with an "x"', ' } else {', ' resultStream.format (" x %d", allPrimes[curPosInAllPrimes]);', ' }', ' ', ' // remove that prime factor from the target', ' numToFactorize /= allPrimes[curPosInAllPrimes];', ' ', ' // if the current prime does not divde evenly, try the next one', ' } else {', ' curPosInAllPrimes++;', ' }', ' }', ' ', ' // if we never printed any factors, then display the number itself', ' if (firstOne) {', ' resultStream.format ("%d", numToFactorize);', " // Otherwsie print the factors connected by 'x'", ' } else if (numToFactorize > 1) {', ' resultStream.format (" x %d", numToFactorize);', ' }', ' }', ' ', ' ', ' /**', ' * This is the constructor. What it does is to fill the array allPrimes with all', ' * of the prime numbers from 2 through sqrt(maxNumberToFactorize). This array of primes', ' * can then subsequently be used by the printPrimeFactorization method to actually', ' * compute the prime factorization of a number. The method also sets upperBound', ' * (the largest number we checked for primality) and numPrimes (the number of primes', ' * in allPimes). The algorithm used to compute the primes is the classic "sieve of ', ' * Eratosthenes" algorithm.', ' */', ' public PrimeFactorizer (long maxNumberToFactorizeIn, PrintStream outputStream) {', ' ', ' resultStream = outputStream;', ' maxNumberToFactorize = maxNumberToFactorizeIn;', ' ', " // initialize the two class variables- 'upperBound' and 'allPrimes' note that the prime candidates are", ' // from 2 to upperBound, so there are upperBound prime candidates intially', ' upperBound = (int) Math.ceil (Math.sqrt (maxNumberToFactorize));', ' allPrimes = new int[upperBound - 1];', ' ', ' // numIntsInList is the number of ints currently in the list.', ' int numIntsInList = upperBound - 1;', ' ', ' // the number of primes so far is zero', ' numPrimes = 0;', ' ', ' // write all of the candidate numbers to the list... this is all of the numbers', ' // from two to upperBound', ' for (int i = 0; i < upperBound - 1; i++) {', ' allPrimes[i] = i + 2;', ' }', ' ', ' // now we keep removing numbers from the list until we have only primes', ' while (numIntsInList > numPrimes) {', ' ', ' // curPos tells us the last slot that has a "good" (still possibly prime) value.', ' int curPos = numPrimes + 1;', ' ', ' // the front of the list is a prime... kill everyone who is a multiple of it', ' for (int i = numPrimes + 1; i < numIntsInList; i++) {', ' ', ' // if the dude at position i is not a multiple of the current prime, then', " // we keep him; otherwise, he'll be lost", ' if (allPrimes[i] % allPrimes[numPrimes] != 0) {', ' allPrimes[curPos] = allPrimes[i];', ' curPos++;', ' }', ' }', ' ', ' // the number of ints in the list is now equal to the last slot we wrote a value to', ' numIntsInList = curPos;', ' ', ' // and the guy at the front of the list is now considered a prime', ' numPrimes++;', ' ', ' }', ' }', ' ', '', '}', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', ' ', 'public class FactorizationTester extends TestCase {', ' /**', ' * Stream to hold the result of each test.', ' */', ' private ByteArrayOutputStream result;', '', ' /**', ' * Wrapper to provide printing functionality.', ' */', ' private PrintStream outputStream;', '', ' /**', ' * Setup the output streams before each test.', ' */ ', ' protected void setUp () {', ' result = new ByteArrayOutputStream();', ' outputStream = new PrintStream(result);', ' } ', ' ', ' /**', ' * Print a nice message about each test.', ' */', ' private void printInfo(String description, String expected, String actual) {', ' System.out.format ("\\n%s\\n", description);', ' System.out.format ("output:\\t%s\\n", actual);', ' System.out.format ("correct:\\t%s\\n", expected);', ' }', '', ' /**', ' * These are the various test methods. The first 10 test factorizations', ' * using the object constructed to factorize numbers up to 100; the latter', ' * 7 use the object to factorize numbers up to 100000.', ' */', ' public void test100MaxFactorize1() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (1);', '', ' // Print Results', ' String expected = new String("Prime factorization of 1 is: 1");', ' printInfo("Factorizing 1 using max 100", expected, result.toString());', '', ' // Check if test passed by comparing the expected and actual results', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 7 ', ' public void test100MaxFactorize7() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (7);', '', ' // Print Results', ' String expected = new String("Prime factorization of 7 is: 7");', ' printInfo("Factorizing 7 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 5', ' public void test100MaxFactorize5() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (5);', '', ' // Print Results', ' String expected = new String("Prime factorization of 5 is: 5");', ' printInfo("Factorizing 5 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 30', ' public void test100MaxFactorize30() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (30);', '', ' // Print Results', ' String expected = new String("Prime factorization of 30 is: 2 x 3 x 5");', ' printInfo("Factorizing 30 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 81', ' public void test100MaxFactorize81() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (81);', '', ' // Print Results', ' String expected = new String("Prime factorization of 81 is: 3 x 3 x 3 x 3");', ' printInfo("Factorizing 81 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 71', ' public void test100MaxFactorize71() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (71);', '', ' // Print Results', ' String expected = new String("Prime factorization of 71 is: 71");', ' printInfo("Factorizing 71 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 100', ' public void test100MaxFactorize100() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (100);', '', ' // Print Results', ' String expected = new String("Prime factorization of 100 is: 2 x 2 x 5 x 5");', ' printInfo("Factorizing 100 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 101', ' public void test100MaxFactorize101() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (101);', '', ' // Print Results', ' String expected = new String("101 is too large to factorize");', ' printInfo("Factorizing 101 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 0', ' public void test100MaxFactorize0() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (0);', '', ' // Print Results', ' String expected = new String("Can\'t factorize a number less than 1");', ' printInfo("Factorizing 0 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' // Test the factorization of 97', ' public void test100MaxFactorize97() {', ' // Factorize the number'] | [' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (97);', '', ' // Print Results', ' String expected = new String("Prime factorization of 97 is: 97");', ' printInfo("Factorizing 97 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }'] | ['', ' // Test the factorization of 34534', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize34534() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (34534);', '', ' // Print Results', ' String expected = new String("Prime factorization of 34534 is: 2 x 31 x 557");', ' printInfo("Factorizing 34534 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 4339', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize4339() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (4339);', '', ' // Print Results', ' String expected = new String("Prime factorization of 4339 is: 4339");', ' printInfo("Factorizing 4339 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 65536', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize65536() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (65536);', '', ' // Print Results', ' String expected = new String("Prime factorization of 65536 is: 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2");', ' printInfo("Factorizing 65536 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 99797', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize99797() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (99797);', '', ' // Print Results', ' String expected = new String("Prime factorization of 99797 is: 23 x 4339");', ' printInfo("Factorizing 99797 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 307', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize307() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (307);', '', ' // Print Results', ' String expected = new String("Prime factorization of 307 is: 307");', ' printInfo("Factorizing 307 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 38845248344', ' // factorize numbers up to 100000000000', ' public void test100000000000MaxFactorize38845248344() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000000 = new PrimeFactorizer(100000000000L, outputStream);', ' myFactorizerMax100000000000.printPrimeFactorization (38845248344L);', '', ' // Print Results', ' String expected = new String("Prime factorization of 38845248344 is: 2 x 2 x 2 x 7 x 693665149");', ' printInfo("Factorizing 38845248344 using max 100000000000", expected, result.toString());', ' ', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' ', ' result.reset ();', ' myFactorizerMax100000000000.printPrimeFactorization (24210833220L);', ' expected = new String("Prime factorization of 24210833220 is: 2 x 2 x 3 x 3 x 5 x 7 x 17 x 19 x 19 x 31 x 101");', ' printInfo("Factorizing 24210833220 using max 100000000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' public void test100000000000MaxFactorize5387457483444() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000000 = new PrimeFactorizer(100000000000L, outputStream);', ' myFactorizerMax100000000000.printPrimeFactorization (5387457483444L);', '', ' // Print Results', ' String expected = new String("5387457483444 is too large to factorize");', ' printInfo("Factorizing 5387457483444 using max 100000000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' public void testSpeed() {', ' ', ' // here we factorize 10,000 large numbers; make sure that the constructor correctly sets', " // up the array of primes just once... if it does not, it'll take too long to run", ' PrimeFactorizer myFactorizerMax100000000000 = new PrimeFactorizer(100000000000L, outputStream);', ' for (long i = 38845248344L; i < 38845248344L + 50000; i++) {', ' myFactorizerMax100000000000.printPrimeFactorization (i);', ' if (i == 38845248344L) {', ' // Compare the Prime factorization of 38845248344 to the expected result', ' String expected = new String("Prime factorization of 38845248344 is: 2 x 2 x 2 x 7 x 693665149"); ', ' assertEquals (expected, result.toString());', ' }', ' }', ' ', ' // if we make it here, we pass the test', ' assertTrue (true);', ' }', ' ', '}'] | [] | Class 'PrimeFactorizer' used at line 321 is defined at line 12 and has a Long-Range dependency.
Global_Variable 'outputStream' used at line 321 is defined at line 170 and has a Long-Range dependency.
Function 'PrimeFactorizer.printPrimeFactorization' used at line 322 is defined at line 34 and has a Long-Range dependency.
Function 'printInfo' used at line 326 is defined at line 183 and has a Long-Range dependency.
Variable 'expected' used at line 326 is defined at line 325 and has a Short-Range dependency.
Global_Variable 'result' used at line 326 is defined at line 165 and has a Long-Range dependency.
Variable 'expected' used at line 329 is defined at line 325 and has a Short-Range dependency.
Global_Variable 'result' used at line 329 is defined at line 165 and has a Long-Range dependency. | {} | {'Class Long-Range': 1, 'Global_Variable Long-Range': 3, 'Function Long-Range': 2, 'Variable Short-Range': 2} |
infilling_java | FactorizationTester | 336 | 345 | ['import junit.framework.TestCase;', 'import java.io.ByteArrayOutputStream;', 'import java.io.PrintStream;', 'import java.lang.Math;', '', '/**', ' * This class implements a relatively simple algorithm for computing', ' * (and printing) the prime factors of a number. At initialization,', ' * a list of primes is computed. Given a number, this list is then', ' * used to efficiently print the prime factors of the number.', ' */', 'class PrimeFactorizer {', '', ' // this class will store all primes between 2 and upperBound', ' private int upperBound;', ' ', ' // this class will be able to factorize all primes between 1 and maxNumberToFactorize', ' private long maxNumberToFactorize;', ' ', ' // this is a list of all of the prime numbers between 2 and upperBound', ' private int [] allPrimes;', ' ', ' // this is the number of primes found between 2 and upperBound', ' private int numPrimes;', ' ', ' // this is the output stream that the factorization will be printed to', ' private PrintStream resultStream;', ' ', ' /**', ' * This prints the prime factorization of a number in a "pretty" fashion.', ' * If the number passed in exceeds "upperBound", then a nice error message', ' * is printed. ', ' */', ' public void printPrimeFactorization (long numToFactorize) {', ' ', " // If we are given a number that's too small/big to factor, tell the user", ' if (numToFactorize < 1) {', ' resultStream.format ("Can\'t factorize a number less than 1");', ' return;', ' }', ' if (numToFactorize > maxNumberToFactorize) {', ' resultStream.format ("%d is too large to factorize", numToFactorize);', ' return;', ' }', ' ', ' // Now get ready to print the factorization', ' resultStream.format ("Prime factorization of %d is: ", numToFactorize);', ' ', ' // our basic tactice will be to find all of the primes that divide evenly into', ' // our target. When we find one, print it out and reduce the target accrordingly.', ' // When the target gets down to one, we are done.', ' ', ' // this is the index of the next prime we need to try', ' int curPosInAllPrimes = 0;', ' ', ' // tells us we are still waiting to print the first prime... important so we', ' // don\'t print the "x" symbol before the first one', ' boolean firstOne = true;', ' ', ' while (numToFactorize > 1 && curPosInAllPrimes < numPrimes) {', ' ', " // if the current prime divides evenly into the target, we've got a prime factor", ' if (numToFactorize % allPrimes[curPosInAllPrimes] == 0) {', ' ', ' // if it\'s the first one, we don\'t need to print a "x"', ' // print the factor & reset the firstOne flag', ' if (firstOne) {', ' resultStream.format ("%d", allPrimes[curPosInAllPrimes]);', ' firstOne = false;', ' ', ' // otherwise, print the factor pre-pended with an "x"', ' } else {', ' resultStream.format (" x %d", allPrimes[curPosInAllPrimes]);', ' }', ' ', ' // remove that prime factor from the target', ' numToFactorize /= allPrimes[curPosInAllPrimes];', ' ', ' // if the current prime does not divde evenly, try the next one', ' } else {', ' curPosInAllPrimes++;', ' }', ' }', ' ', ' // if we never printed any factors, then display the number itself', ' if (firstOne) {', ' resultStream.format ("%d", numToFactorize);', " // Otherwsie print the factors connected by 'x'", ' } else if (numToFactorize > 1) {', ' resultStream.format (" x %d", numToFactorize);', ' }', ' }', ' ', ' ', ' /**', ' * This is the constructor. What it does is to fill the array allPrimes with all', ' * of the prime numbers from 2 through sqrt(maxNumberToFactorize). This array of primes', ' * can then subsequently be used by the printPrimeFactorization method to actually', ' * compute the prime factorization of a number. The method also sets upperBound', ' * (the largest number we checked for primality) and numPrimes (the number of primes', ' * in allPimes). The algorithm used to compute the primes is the classic "sieve of ', ' * Eratosthenes" algorithm.', ' */', ' public PrimeFactorizer (long maxNumberToFactorizeIn, PrintStream outputStream) {', ' ', ' resultStream = outputStream;', ' maxNumberToFactorize = maxNumberToFactorizeIn;', ' ', " // initialize the two class variables- 'upperBound' and 'allPrimes' note that the prime candidates are", ' // from 2 to upperBound, so there are upperBound prime candidates intially', ' upperBound = (int) Math.ceil (Math.sqrt (maxNumberToFactorize));', ' allPrimes = new int[upperBound - 1];', ' ', ' // numIntsInList is the number of ints currently in the list.', ' int numIntsInList = upperBound - 1;', ' ', ' // the number of primes so far is zero', ' numPrimes = 0;', ' ', ' // write all of the candidate numbers to the list... this is all of the numbers', ' // from two to upperBound', ' for (int i = 0; i < upperBound - 1; i++) {', ' allPrimes[i] = i + 2;', ' }', ' ', ' // now we keep removing numbers from the list until we have only primes', ' while (numIntsInList > numPrimes) {', ' ', ' // curPos tells us the last slot that has a "good" (still possibly prime) value.', ' int curPos = numPrimes + 1;', ' ', ' // the front of the list is a prime... kill everyone who is a multiple of it', ' for (int i = numPrimes + 1; i < numIntsInList; i++) {', ' ', ' // if the dude at position i is not a multiple of the current prime, then', " // we keep him; otherwise, he'll be lost", ' if (allPrimes[i] % allPrimes[numPrimes] != 0) {', ' allPrimes[curPos] = allPrimes[i];', ' curPos++;', ' }', ' }', ' ', ' // the number of ints in the list is now equal to the last slot we wrote a value to', ' numIntsInList = curPos;', ' ', ' // and the guy at the front of the list is now considered a prime', ' numPrimes++;', ' ', ' }', ' }', ' ', '', '}', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', ' ', 'public class FactorizationTester extends TestCase {', ' /**', ' * Stream to hold the result of each test.', ' */', ' private ByteArrayOutputStream result;', '', ' /**', ' * Wrapper to provide printing functionality.', ' */', ' private PrintStream outputStream;', '', ' /**', ' * Setup the output streams before each test.', ' */ ', ' protected void setUp () {', ' result = new ByteArrayOutputStream();', ' outputStream = new PrintStream(result);', ' } ', ' ', ' /**', ' * Print a nice message about each test.', ' */', ' private void printInfo(String description, String expected, String actual) {', ' System.out.format ("\\n%s\\n", description);', ' System.out.format ("output:\\t%s\\n", actual);', ' System.out.format ("correct:\\t%s\\n", expected);', ' }', '', ' /**', ' * These are the various test methods. The first 10 test factorizations', ' * using the object constructed to factorize numbers up to 100; the latter', ' * 7 use the object to factorize numbers up to 100000.', ' */', ' public void test100MaxFactorize1() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (1);', '', ' // Print Results', ' String expected = new String("Prime factorization of 1 is: 1");', ' printInfo("Factorizing 1 using max 100", expected, result.toString());', '', ' // Check if test passed by comparing the expected and actual results', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 7 ', ' public void test100MaxFactorize7() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (7);', '', ' // Print Results', ' String expected = new String("Prime factorization of 7 is: 7");', ' printInfo("Factorizing 7 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 5', ' public void test100MaxFactorize5() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (5);', '', ' // Print Results', ' String expected = new String("Prime factorization of 5 is: 5");', ' printInfo("Factorizing 5 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 30', ' public void test100MaxFactorize30() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (30);', '', ' // Print Results', ' String expected = new String("Prime factorization of 30 is: 2 x 3 x 5");', ' printInfo("Factorizing 30 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 81', ' public void test100MaxFactorize81() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (81);', '', ' // Print Results', ' String expected = new String("Prime factorization of 81 is: 3 x 3 x 3 x 3");', ' printInfo("Factorizing 81 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 71', ' public void test100MaxFactorize71() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (71);', '', ' // Print Results', ' String expected = new String("Prime factorization of 71 is: 71");', ' printInfo("Factorizing 71 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 100', ' public void test100MaxFactorize100() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (100);', '', ' // Print Results', ' String expected = new String("Prime factorization of 100 is: 2 x 2 x 5 x 5");', ' printInfo("Factorizing 100 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 101', ' public void test100MaxFactorize101() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (101);', '', ' // Print Results', ' String expected = new String("101 is too large to factorize");', ' printInfo("Factorizing 101 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 0', ' public void test100MaxFactorize0() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (0);', '', ' // Print Results', ' String expected = new String("Can\'t factorize a number less than 1");', ' printInfo("Factorizing 0 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' // Test the factorization of 97', ' public void test100MaxFactorize97() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (97);', '', ' // Print Results', ' String expected = new String("Prime factorization of 97 is: 97");', ' printInfo("Factorizing 97 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 34534', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize34534() {', ' // Factorize the number'] | [' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (34534);', '', ' // Print Results', ' String expected = new String("Prime factorization of 34534 is: 2 x 31 x 557");', ' printInfo("Factorizing 34534 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }'] | ['', ' // Test the factorization of 4339', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize4339() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (4339);', '', ' // Print Results', ' String expected = new String("Prime factorization of 4339 is: 4339");', ' printInfo("Factorizing 4339 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 65536', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize65536() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (65536);', '', ' // Print Results', ' String expected = new String("Prime factorization of 65536 is: 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2");', ' printInfo("Factorizing 65536 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 99797', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize99797() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (99797);', '', ' // Print Results', ' String expected = new String("Prime factorization of 99797 is: 23 x 4339");', ' printInfo("Factorizing 99797 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 307', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize307() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (307);', '', ' // Print Results', ' String expected = new String("Prime factorization of 307 is: 307");', ' printInfo("Factorizing 307 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 38845248344', ' // factorize numbers up to 100000000000', ' public void test100000000000MaxFactorize38845248344() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000000 = new PrimeFactorizer(100000000000L, outputStream);', ' myFactorizerMax100000000000.printPrimeFactorization (38845248344L);', '', ' // Print Results', ' String expected = new String("Prime factorization of 38845248344 is: 2 x 2 x 2 x 7 x 693665149");', ' printInfo("Factorizing 38845248344 using max 100000000000", expected, result.toString());', ' ', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' ', ' result.reset ();', ' myFactorizerMax100000000000.printPrimeFactorization (24210833220L);', ' expected = new String("Prime factorization of 24210833220 is: 2 x 2 x 3 x 3 x 5 x 7 x 17 x 19 x 19 x 31 x 101");', ' printInfo("Factorizing 24210833220 using max 100000000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' public void test100000000000MaxFactorize5387457483444() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000000 = new PrimeFactorizer(100000000000L, outputStream);', ' myFactorizerMax100000000000.printPrimeFactorization (5387457483444L);', '', ' // Print Results', ' String expected = new String("5387457483444 is too large to factorize");', ' printInfo("Factorizing 5387457483444 using max 100000000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' public void testSpeed() {', ' ', ' // here we factorize 10,000 large numbers; make sure that the constructor correctly sets', " // up the array of primes just once... if it does not, it'll take too long to run", ' PrimeFactorizer myFactorizerMax100000000000 = new PrimeFactorizer(100000000000L, outputStream);', ' for (long i = 38845248344L; i < 38845248344L + 50000; i++) {', ' myFactorizerMax100000000000.printPrimeFactorization (i);', ' if (i == 38845248344L) {', ' // Compare the Prime factorization of 38845248344 to the expected result', ' String expected = new String("Prime factorization of 38845248344 is: 2 x 2 x 2 x 7 x 693665149"); ', ' assertEquals (expected, result.toString());', ' }', ' }', ' ', ' // if we make it here, we pass the test', ' assertTrue (true);', ' }', ' ', '}'] | [] | Class 'PrimeFactorizer' used at line 336 is defined at line 12 and has a Long-Range dependency.
Global_Variable 'outputStream' used at line 336 is defined at line 170 and has a Long-Range dependency.
Function 'PrimeFactorizer.printPrimeFactorization' used at line 337 is defined at line 34 and has a Long-Range dependency.
Function 'printInfo' used at line 341 is defined at line 183 and has a Long-Range dependency.
Variable 'expected' used at line 341 is defined at line 340 and has a Short-Range dependency.
Global_Variable 'result' used at line 341 is defined at line 165 and has a Long-Range dependency.
Variable 'expected' used at line 344 is defined at line 340 and has a Short-Range dependency.
Global_Variable 'result' used at line 344 is defined at line 165 and has a Long-Range dependency. | {} | {'Class Long-Range': 1, 'Global_Variable Long-Range': 3, 'Function Long-Range': 2, 'Variable Short-Range': 2} |
infilling_java | FactorizationTester | 449 | 455 | ['import junit.framework.TestCase;', 'import java.io.ByteArrayOutputStream;', 'import java.io.PrintStream;', 'import java.lang.Math;', '', '/**', ' * This class implements a relatively simple algorithm for computing', ' * (and printing) the prime factors of a number. At initialization,', ' * a list of primes is computed. Given a number, this list is then', ' * used to efficiently print the prime factors of the number.', ' */', 'class PrimeFactorizer {', '', ' // this class will store all primes between 2 and upperBound', ' private int upperBound;', ' ', ' // this class will be able to factorize all primes between 1 and maxNumberToFactorize', ' private long maxNumberToFactorize;', ' ', ' // this is a list of all of the prime numbers between 2 and upperBound', ' private int [] allPrimes;', ' ', ' // this is the number of primes found between 2 and upperBound', ' private int numPrimes;', ' ', ' // this is the output stream that the factorization will be printed to', ' private PrintStream resultStream;', ' ', ' /**', ' * This prints the prime factorization of a number in a "pretty" fashion.', ' * If the number passed in exceeds "upperBound", then a nice error message', ' * is printed. ', ' */', ' public void printPrimeFactorization (long numToFactorize) {', ' ', " // If we are given a number that's too small/big to factor, tell the user", ' if (numToFactorize < 1) {', ' resultStream.format ("Can\'t factorize a number less than 1");', ' return;', ' }', ' if (numToFactorize > maxNumberToFactorize) {', ' resultStream.format ("%d is too large to factorize", numToFactorize);', ' return;', ' }', ' ', ' // Now get ready to print the factorization', ' resultStream.format ("Prime factorization of %d is: ", numToFactorize);', ' ', ' // our basic tactice will be to find all of the primes that divide evenly into', ' // our target. When we find one, print it out and reduce the target accrordingly.', ' // When the target gets down to one, we are done.', ' ', ' // this is the index of the next prime we need to try', ' int curPosInAllPrimes = 0;', ' ', ' // tells us we are still waiting to print the first prime... important so we', ' // don\'t print the "x" symbol before the first one', ' boolean firstOne = true;', ' ', ' while (numToFactorize > 1 && curPosInAllPrimes < numPrimes) {', ' ', " // if the current prime divides evenly into the target, we've got a prime factor", ' if (numToFactorize % allPrimes[curPosInAllPrimes] == 0) {', ' ', ' // if it\'s the first one, we don\'t need to print a "x"', ' // print the factor & reset the firstOne flag', ' if (firstOne) {', ' resultStream.format ("%d", allPrimes[curPosInAllPrimes]);', ' firstOne = false;', ' ', ' // otherwise, print the factor pre-pended with an "x"', ' } else {', ' resultStream.format (" x %d", allPrimes[curPosInAllPrimes]);', ' }', ' ', ' // remove that prime factor from the target', ' numToFactorize /= allPrimes[curPosInAllPrimes];', ' ', ' // if the current prime does not divde evenly, try the next one', ' } else {', ' curPosInAllPrimes++;', ' }', ' }', ' ', ' // if we never printed any factors, then display the number itself', ' if (firstOne) {', ' resultStream.format ("%d", numToFactorize);', " // Otherwsie print the factors connected by 'x'", ' } else if (numToFactorize > 1) {', ' resultStream.format (" x %d", numToFactorize);', ' }', ' }', ' ', ' ', ' /**', ' * This is the constructor. What it does is to fill the array allPrimes with all', ' * of the prime numbers from 2 through sqrt(maxNumberToFactorize). This array of primes', ' * can then subsequently be used by the printPrimeFactorization method to actually', ' * compute the prime factorization of a number. The method also sets upperBound', ' * (the largest number we checked for primality) and numPrimes (the number of primes', ' * in allPimes). The algorithm used to compute the primes is the classic "sieve of ', ' * Eratosthenes" algorithm.', ' */', ' public PrimeFactorizer (long maxNumberToFactorizeIn, PrintStream outputStream) {', ' ', ' resultStream = outputStream;', ' maxNumberToFactorize = maxNumberToFactorizeIn;', ' ', " // initialize the two class variables- 'upperBound' and 'allPrimes' note that the prime candidates are", ' // from 2 to upperBound, so there are upperBound prime candidates intially', ' upperBound = (int) Math.ceil (Math.sqrt (maxNumberToFactorize));', ' allPrimes = new int[upperBound - 1];', ' ', ' // numIntsInList is the number of ints currently in the list.', ' int numIntsInList = upperBound - 1;', ' ', ' // the number of primes so far is zero', ' numPrimes = 0;', ' ', ' // write all of the candidate numbers to the list... this is all of the numbers', ' // from two to upperBound', ' for (int i = 0; i < upperBound - 1; i++) {', ' allPrimes[i] = i + 2;', ' }', ' ', ' // now we keep removing numbers from the list until we have only primes', ' while (numIntsInList > numPrimes) {', ' ', ' // curPos tells us the last slot that has a "good" (still possibly prime) value.', ' int curPos = numPrimes + 1;', ' ', ' // the front of the list is a prime... kill everyone who is a multiple of it', ' for (int i = numPrimes + 1; i < numIntsInList; i++) {', ' ', ' // if the dude at position i is not a multiple of the current prime, then', " // we keep him; otherwise, he'll be lost", ' if (allPrimes[i] % allPrimes[numPrimes] != 0) {', ' allPrimes[curPos] = allPrimes[i];', ' curPos++;', ' }', ' }', ' ', ' // the number of ints in the list is now equal to the last slot we wrote a value to', ' numIntsInList = curPos;', ' ', ' // and the guy at the front of the list is now considered a prime', ' numPrimes++;', ' ', ' }', ' }', ' ', '', '}', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', ' ', 'public class FactorizationTester extends TestCase {', ' /**', ' * Stream to hold the result of each test.', ' */', ' private ByteArrayOutputStream result;', '', ' /**', ' * Wrapper to provide printing functionality.', ' */', ' private PrintStream outputStream;', '', ' /**', ' * Setup the output streams before each test.', ' */ ', ' protected void setUp () {', ' result = new ByteArrayOutputStream();', ' outputStream = new PrintStream(result);', ' } ', ' ', ' /**', ' * Print a nice message about each test.', ' */', ' private void printInfo(String description, String expected, String actual) {', ' System.out.format ("\\n%s\\n", description);', ' System.out.format ("output:\\t%s\\n", actual);', ' System.out.format ("correct:\\t%s\\n", expected);', ' }', '', ' /**', ' * These are the various test methods. The first 10 test factorizations', ' * using the object constructed to factorize numbers up to 100; the latter', ' * 7 use the object to factorize numbers up to 100000.', ' */', ' public void test100MaxFactorize1() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (1);', '', ' // Print Results', ' String expected = new String("Prime factorization of 1 is: 1");', ' printInfo("Factorizing 1 using max 100", expected, result.toString());', '', ' // Check if test passed by comparing the expected and actual results', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 7 ', ' public void test100MaxFactorize7() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (7);', '', ' // Print Results', ' String expected = new String("Prime factorization of 7 is: 7");', ' printInfo("Factorizing 7 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 5', ' public void test100MaxFactorize5() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (5);', '', ' // Print Results', ' String expected = new String("Prime factorization of 5 is: 5");', ' printInfo("Factorizing 5 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 30', ' public void test100MaxFactorize30() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (30);', '', ' // Print Results', ' String expected = new String("Prime factorization of 30 is: 2 x 3 x 5");', ' printInfo("Factorizing 30 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 81', ' public void test100MaxFactorize81() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (81);', '', ' // Print Results', ' String expected = new String("Prime factorization of 81 is: 3 x 3 x 3 x 3");', ' printInfo("Factorizing 81 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 71', ' public void test100MaxFactorize71() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (71);', '', ' // Print Results', ' String expected = new String("Prime factorization of 71 is: 71");', ' printInfo("Factorizing 71 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 100', ' public void test100MaxFactorize100() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (100);', '', ' // Print Results', ' String expected = new String("Prime factorization of 100 is: 2 x 2 x 5 x 5");', ' printInfo("Factorizing 100 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 101', ' public void test100MaxFactorize101() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (101);', '', ' // Print Results', ' String expected = new String("101 is too large to factorize");', ' printInfo("Factorizing 101 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 0', ' public void test100MaxFactorize0() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (0);', '', ' // Print Results', ' String expected = new String("Can\'t factorize a number less than 1");', ' printInfo("Factorizing 0 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' // Test the factorization of 97', ' public void test100MaxFactorize97() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100 = new PrimeFactorizer(100, outputStream);', ' myFactorizerMax100.printPrimeFactorization (97);', '', ' // Print Results', ' String expected = new String("Prime factorization of 97 is: 97");', ' printInfo("Factorizing 97 using max 100", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 34534', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize34534() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (34534);', '', ' // Print Results', ' String expected = new String("Prime factorization of 34534 is: 2 x 31 x 557");', ' printInfo("Factorizing 34534 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 4339', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize4339() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (4339);', '', ' // Print Results', ' String expected = new String("Prime factorization of 4339 is: 4339");', ' printInfo("Factorizing 4339 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 65536', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize65536() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (65536);', '', ' // Print Results', ' String expected = new String("Prime factorization of 65536 is: 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2");', ' printInfo("Factorizing 65536 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 99797', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize99797() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (99797);', '', ' // Print Results', ' String expected = new String("Prime factorization of 99797 is: 23 x 4339");', ' printInfo("Factorizing 99797 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' // Test the factorization of 307', ' // factorize numbers up to 100000000', ' public void test100000000MaxFactorize307() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000 = new PrimeFactorizer(100000000, outputStream);', ' myFactorizerMax100000000.printPrimeFactorization (307);', '', ' // Print Results', ' String expected = new String("Prime factorization of 307 is: 307");', ' printInfo("Factorizing 307 using max 100000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', '', ' // Test the factorization of 38845248344', ' // factorize numbers up to 100000000000', ' public void test100000000000MaxFactorize38845248344() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000000 = new PrimeFactorizer(100000000000L, outputStream);', ' myFactorizerMax100000000000.printPrimeFactorization (38845248344L);', '', ' // Print Results', ' String expected = new String("Prime factorization of 38845248344 is: 2 x 2 x 2 x 7 x 693665149");', ' printInfo("Factorizing 38845248344 using max 100000000000", expected, result.toString());', ' ', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' ', ' result.reset ();', ' myFactorizerMax100000000000.printPrimeFactorization (24210833220L);', ' expected = new String("Prime factorization of 24210833220 is: 2 x 2 x 3 x 3 x 5 x 7 x 17 x 19 x 19 x 31 x 101");', ' printInfo("Factorizing 24210833220 using max 100000000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' public void test100000000000MaxFactorize5387457483444() {', ' // Factorize the number', ' PrimeFactorizer myFactorizerMax100000000000 = new PrimeFactorizer(100000000000L, outputStream);', ' myFactorizerMax100000000000.printPrimeFactorization (5387457483444L);', '', ' // Print Results', ' String expected = new String("5387457483444 is too large to factorize");', ' printInfo("Factorizing 5387457483444 using max 100000000000", expected, result.toString());', '', ' // Check if test passed', ' assertEquals (expected, result.toString());', ' }', ' ', ' public void testSpeed() {', ' ', ' // here we factorize 10,000 large numbers; make sure that the constructor correctly sets', " // up the array of primes just once... if it does not, it'll take too long to run", ' PrimeFactorizer myFactorizerMax100000000000 = new PrimeFactorizer(100000000000L, outputStream);', ' for (long i = 38845248344L; i < 38845248344L + 50000; i++) {'] | [' myFactorizerMax100000000000.printPrimeFactorization (i);', ' if (i == 38845248344L) {', ' // Compare the Prime factorization of 38845248344 to the expected result', ' String expected = new String("Prime factorization of 38845248344 is: 2 x 2 x 2 x 7 x 693665149"); ', ' assertEquals (expected, result.toString());', ' }', ' }'] | [' ', ' // if we make it here, we pass the test', ' assertTrue (true);', ' }', ' ', '}'] | [{'reason_category': 'Loop Body', 'usage_line': 449}, {'reason_category': 'Loop Body', 'usage_line': 450}, {'reason_category': 'If Condition', 'usage_line': 450}, {'reason_category': 'If Body', 'usage_line': 451}, {'reason_category': 'Loop Body', 'usage_line': 451}, {'reason_category': 'Loop Body', 'usage_line': 452}, {'reason_category': 'If Body', 'usage_line': 452}, {'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}] | Function 'PrimeFactorizer.printPrimeFactorization' used at line 449 is defined at line 34 and has a Long-Range dependency.
Variable 'i' used at line 449 is defined at line 448 and has a Short-Range dependency.
Variable 'i' used at line 450 is defined at line 448 and has a Short-Range dependency.
Variable 'expected' used at line 453 is defined at line 452 and has a Short-Range dependency.
Global_Variable 'result' used at line 453 is defined at line 165 and has a Long-Range dependency. | {'Loop Body': 7, 'If Condition': 1, 'If Body': 4} | {'Function Long-Range': 1, 'Variable Short-Range': 3, 'Global_Variable Long-Range': 1} |
infilling_java | RNGTester | 146 | 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} |
infilling_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} |
infilling_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} |