id
int32
0
165k
repo
stringlengths
7
58
path
stringlengths
12
218
func_name
stringlengths
3
140
original_string
stringlengths
73
34.1k
language
stringclasses
1 value
code
stringlengths
73
34.1k
code_tokens
list
docstring
stringlengths
3
16k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
105
339
28,800
Waikato/moa
moa/src/main/java/moa/core/Utils.java
Utils.splitOptions
public static String[] splitOptions(String quotedOptionString) throws Exception{ Vector<String> optionsVec = new Vector<String>(); String str = new String(quotedOptionString); int i; while (true){ //trimLeft i = 0; while ((i < str.length()) && (Character.isWhitespace(str.charAt(i)))) i++; str = str.substring(i); //stop when str is empty if (str.length() == 0) break; //if str start with a double quote if (str.charAt(0) == '"'){ //find the first not anti-slached double quote i = 1; while(i < str.length()){ if (str.charAt(i) == str.charAt(0)) break; if (str.charAt(i) == '\\'){ i += 1; if (i >= str.length()) throw new Exception("String should not finish with \\"); } i += 1; } if (i >= str.length()) throw new Exception("Quote parse error."); //add the founded string to the option vector (without quotes) String optStr = str.substring(1,i); optStr = unbackQuoteChars(optStr); optionsVec.addElement(optStr); str = str.substring(i+1); } else { //find first whiteSpace i=0; while((i < str.length()) && (!Character.isWhitespace(str.charAt(i)))) i++; //add the founded string to the option vector String optStr = str.substring(0,i); optionsVec.addElement(optStr); str = str.substring(i); } } //convert optionsVec to an array of String String[] options = new String[optionsVec.size()]; for (i = 0; i < optionsVec.size(); i++) { options[i] = (String)optionsVec.elementAt(i); } return options; }
java
public static String[] splitOptions(String quotedOptionString) throws Exception{ Vector<String> optionsVec = new Vector<String>(); String str = new String(quotedOptionString); int i; while (true){ //trimLeft i = 0; while ((i < str.length()) && (Character.isWhitespace(str.charAt(i)))) i++; str = str.substring(i); //stop when str is empty if (str.length() == 0) break; //if str start with a double quote if (str.charAt(0) == '"'){ //find the first not anti-slached double quote i = 1; while(i < str.length()){ if (str.charAt(i) == str.charAt(0)) break; if (str.charAt(i) == '\\'){ i += 1; if (i >= str.length()) throw new Exception("String should not finish with \\"); } i += 1; } if (i >= str.length()) throw new Exception("Quote parse error."); //add the founded string to the option vector (without quotes) String optStr = str.substring(1,i); optStr = unbackQuoteChars(optStr); optionsVec.addElement(optStr); str = str.substring(i+1); } else { //find first whiteSpace i=0; while((i < str.length()) && (!Character.isWhitespace(str.charAt(i)))) i++; //add the founded string to the option vector String optStr = str.substring(0,i); optionsVec.addElement(optStr); str = str.substring(i); } } //convert optionsVec to an array of String String[] options = new String[optionsVec.size()]; for (i = 0; i < optionsVec.size(); i++) { options[i] = (String)optionsVec.elementAt(i); } return options; }
[ "public", "static", "String", "[", "]", "splitOptions", "(", "String", "quotedOptionString", ")", "throws", "Exception", "{", "Vector", "<", "String", ">", "optionsVec", "=", "new", "Vector", "<", "String", ">", "(", ")", ";", "String", "str", "=", "new", "String", "(", "quotedOptionString", ")", ";", "int", "i", ";", "while", "(", "true", ")", "{", "//trimLeft ", "i", "=", "0", ";", "while", "(", "(", "i", "<", "str", ".", "length", "(", ")", ")", "&&", "(", "Character", ".", "isWhitespace", "(", "str", ".", "charAt", "(", "i", ")", ")", ")", ")", "i", "++", ";", "str", "=", "str", ".", "substring", "(", "i", ")", ";", "//stop when str is empty", "if", "(", "str", ".", "length", "(", ")", "==", "0", ")", "break", ";", "//if str start with a double quote", "if", "(", "str", ".", "charAt", "(", "0", ")", "==", "'", "'", ")", "{", "//find the first not anti-slached double quote", "i", "=", "1", ";", "while", "(", "i", "<", "str", ".", "length", "(", ")", ")", "{", "if", "(", "str", ".", "charAt", "(", "i", ")", "==", "str", ".", "charAt", "(", "0", ")", ")", "break", ";", "if", "(", "str", ".", "charAt", "(", "i", ")", "==", "'", "'", ")", "{", "i", "+=", "1", ";", "if", "(", "i", ">=", "str", ".", "length", "(", ")", ")", "throw", "new", "Exception", "(", "\"String should not finish with \\\\\"", ")", ";", "}", "i", "+=", "1", ";", "}", "if", "(", "i", ">=", "str", ".", "length", "(", ")", ")", "throw", "new", "Exception", "(", "\"Quote parse error.\"", ")", ";", "//add the founded string to the option vector (without quotes)", "String", "optStr", "=", "str", ".", "substring", "(", "1", ",", "i", ")", ";", "optStr", "=", "unbackQuoteChars", "(", "optStr", ")", ";", "optionsVec", ".", "addElement", "(", "optStr", ")", ";", "str", "=", "str", ".", "substring", "(", "i", "+", "1", ")", ";", "}", "else", "{", "//find first whiteSpace", "i", "=", "0", ";", "while", "(", "(", "i", "<", "str", ".", "length", "(", ")", ")", "&&", "(", "!", "Character", ".", "isWhitespace", "(", "str", ".", "charAt", "(", "i", ")", ")", ")", ")", "i", "++", ";", "//add the founded string to the option vector", "String", "optStr", "=", "str", ".", "substring", "(", "0", ",", "i", ")", ";", "optionsVec", ".", "addElement", "(", "optStr", ")", ";", "str", "=", "str", ".", "substring", "(", "i", ")", ";", "}", "}", "//convert optionsVec to an array of String", "String", "[", "]", "options", "=", "new", "String", "[", "optionsVec", ".", "size", "(", ")", "]", ";", "for", "(", "i", "=", "0", ";", "i", "<", "optionsVec", ".", "size", "(", ")", ";", "i", "++", ")", "{", "options", "[", "i", "]", "=", "(", "String", ")", "optionsVec", ".", "elementAt", "(", "i", ")", ";", "}", "return", "options", ";", "}" ]
Split up a string containing options into an array of strings, one for each option. @param quotedOptionString the string containing the options @return the array of options @throws Exception in case of an unterminated string, unknown character or a parse error
[ "Split", "up", "a", "string", "containing", "options", "into", "an", "array", "of", "strings", "one", "for", "each", "option", "." ]
395982e5100bfe75a3a4d26115462ce2cc74cbb0
https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/moa/core/Utils.java#L869-L924
28,801
Waikato/moa
moa/src/main/java/moa/core/Utils.java
Utils.joinOptions
public static String joinOptions(String[] optionArray) { String optionString = ""; for (int i = 0; i < optionArray.length; i++) { if (optionArray[i].equals("")) { continue; } boolean escape = false; for (int n = 0; n < optionArray[i].length(); n++) { if (Character.isWhitespace(optionArray[i].charAt(n))) { escape = true; break; } } if (escape) { optionString += '"' + backQuoteChars(optionArray[i]) + '"'; } else { optionString += optionArray[i]; } optionString += " "; } return optionString.trim(); }
java
public static String joinOptions(String[] optionArray) { String optionString = ""; for (int i = 0; i < optionArray.length; i++) { if (optionArray[i].equals("")) { continue; } boolean escape = false; for (int n = 0; n < optionArray[i].length(); n++) { if (Character.isWhitespace(optionArray[i].charAt(n))) { escape = true; break; } } if (escape) { optionString += '"' + backQuoteChars(optionArray[i]) + '"'; } else { optionString += optionArray[i]; } optionString += " "; } return optionString.trim(); }
[ "public", "static", "String", "joinOptions", "(", "String", "[", "]", "optionArray", ")", "{", "String", "optionString", "=", "\"\"", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "optionArray", ".", "length", ";", "i", "++", ")", "{", "if", "(", "optionArray", "[", "i", "]", ".", "equals", "(", "\"\"", ")", ")", "{", "continue", ";", "}", "boolean", "escape", "=", "false", ";", "for", "(", "int", "n", "=", "0", ";", "n", "<", "optionArray", "[", "i", "]", ".", "length", "(", ")", ";", "n", "++", ")", "{", "if", "(", "Character", ".", "isWhitespace", "(", "optionArray", "[", "i", "]", ".", "charAt", "(", "n", ")", ")", ")", "{", "escape", "=", "true", ";", "break", ";", "}", "}", "if", "(", "escape", ")", "{", "optionString", "+=", "'", "'", "+", "backQuoteChars", "(", "optionArray", "[", "i", "]", ")", "+", "'", "'", ";", "}", "else", "{", "optionString", "+=", "optionArray", "[", "i", "]", ";", "}", "optionString", "+=", "\" \"", ";", "}", "return", "optionString", ".", "trim", "(", ")", ";", "}" ]
Joins all the options in an option array into a single string, as might be used on the command line. @param optionArray the array of options @return the string containing all options.
[ "Joins", "all", "the", "options", "in", "an", "option", "array", "into", "a", "single", "string", "as", "might", "be", "used", "on", "the", "command", "line", "." ]
395982e5100bfe75a3a4d26115462ce2cc74cbb0
https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/moa/core/Utils.java#L933-L955
28,802
Waikato/moa
moa/src/main/java/moa/core/Utils.java
Utils.info
public static /*@pure@*/ double info(int counts[]) { int total = 0; double x = 0; for (int j = 0; j < counts.length; j++) { x -= xlogx(counts[j]); total += counts[j]; } return x + xlogx(total); }
java
public static /*@pure@*/ double info(int counts[]) { int total = 0; double x = 0; for (int j = 0; j < counts.length; j++) { x -= xlogx(counts[j]); total += counts[j]; } return x + xlogx(total); }
[ "public", "static", "/*@pure@*/", "double", "info", "(", "int", "counts", "[", "]", ")", "{", "int", "total", "=", "0", ";", "double", "x", "=", "0", ";", "for", "(", "int", "j", "=", "0", ";", "j", "<", "counts", ".", "length", ";", "j", "++", ")", "{", "x", "-=", "xlogx", "(", "counts", "[", "j", "]", ")", ";", "total", "+=", "counts", "[", "j", "]", ";", "}", "return", "x", "+", "xlogx", "(", "total", ")", ";", "}" ]
Computes entropy for an array of integers. @param counts array of counts @return - a log2 a - b log2 b - c log2 c + (a+b+c) log2 (a+b+c) when given array [a b c]
[ "Computes", "entropy", "for", "an", "array", "of", "integers", "." ]
395982e5100bfe75a3a4d26115462ce2cc74cbb0
https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/moa/core/Utils.java#L965-L974
28,803
Waikato/moa
moa/src/main/java/moa/core/Utils.java
Utils.kthSmallestValue
public static double kthSmallestValue(int[] array, int k) { int[] index = new int[array.length]; for (int i = 0; i < index.length; i++) { index[i] = i; } return array[index[select(array, index, 0, array.length - 1, k)]]; }
java
public static double kthSmallestValue(int[] array, int k) { int[] index = new int[array.length]; for (int i = 0; i < index.length; i++) { index[i] = i; } return array[index[select(array, index, 0, array.length - 1, k)]]; }
[ "public", "static", "double", "kthSmallestValue", "(", "int", "[", "]", "array", ",", "int", "k", ")", "{", "int", "[", "]", "index", "=", "new", "int", "[", "array", ".", "length", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "index", ".", "length", ";", "i", "++", ")", "{", "index", "[", "i", "]", "=", "i", ";", "}", "return", "array", "[", "index", "[", "select", "(", "array", ",", "index", ",", "0", ",", "array", ".", "length", "-", "1", ",", "k", ")", "]", "]", ";", "}" ]
Returns the kth-smallest value in the array. @param array the array of integers @param k the value of k @return the kth-smallest value
[ "Returns", "the", "kth", "-", "smallest", "value", "in", "the", "array", "." ]
395982e5100bfe75a3a4d26115462ce2cc74cbb0
https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/moa/core/Utils.java#L1027-L1036
28,804
Waikato/moa
moa/src/main/java/moa/core/Utils.java
Utils.maxIndex
public static /*@pure@*/ int maxIndex(int[] ints) { int maximum = 0; int maxIndex = 0; for (int i = 0; i < ints.length; i++) { if ((i == 0) || (ints[i] > maximum)) { maxIndex = i; maximum = ints[i]; } } return maxIndex; }
java
public static /*@pure@*/ int maxIndex(int[] ints) { int maximum = 0; int maxIndex = 0; for (int i = 0; i < ints.length; i++) { if ((i == 0) || (ints[i] > maximum)) { maxIndex = i; maximum = ints[i]; } } return maxIndex; }
[ "public", "static", "/*@pure@*/", "int", "maxIndex", "(", "int", "[", "]", "ints", ")", "{", "int", "maximum", "=", "0", ";", "int", "maxIndex", "=", "0", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "ints", ".", "length", ";", "i", "++", ")", "{", "if", "(", "(", "i", "==", "0", ")", "||", "(", "ints", "[", "i", "]", ">", "maximum", ")", ")", "{", "maxIndex", "=", "i", ";", "maximum", "=", "ints", "[", "i", "]", ";", "}", "}", "return", "maxIndex", ";", "}" ]
Returns index of maximum element in a given array of integers. First maximum is returned. @param ints the array of integers @return the index of the maximum element
[ "Returns", "index", "of", "maximum", "element", "in", "a", "given", "array", "of", "integers", ".", "First", "maximum", "is", "returned", "." ]
395982e5100bfe75a3a4d26115462ce2cc74cbb0
https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/moa/core/Utils.java#L1096-L1109
28,805
Waikato/moa
moa/src/main/java/moa/core/Utils.java
Utils.mean
public static /*@pure@*/ double mean(double[] vector) { double sum = 0; if (vector.length == 0) { return 0; } for (int i = 0; i < vector.length; i++) { sum += vector[i]; } return sum / (double) vector.length; }
java
public static /*@pure@*/ double mean(double[] vector) { double sum = 0; if (vector.length == 0) { return 0; } for (int i = 0; i < vector.length; i++) { sum += vector[i]; } return sum / (double) vector.length; }
[ "public", "static", "/*@pure@*/", "double", "mean", "(", "double", "[", "]", "vector", ")", "{", "double", "sum", "=", "0", ";", "if", "(", "vector", ".", "length", "==", "0", ")", "{", "return", "0", ";", "}", "for", "(", "int", "i", "=", "0", ";", "i", "<", "vector", ".", "length", ";", "i", "++", ")", "{", "sum", "+=", "vector", "[", "i", "]", ";", "}", "return", "sum", "/", "(", "double", ")", "vector", ".", "length", ";", "}" ]
Computes the mean for an array of doubles. @param vector the array @return the mean
[ "Computes", "the", "mean", "for", "an", "array", "of", "doubles", "." ]
395982e5100bfe75a3a4d26115462ce2cc74cbb0
https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/moa/core/Utils.java#L1117-L1128
28,806
Waikato/moa
moa/src/main/java/moa/core/Utils.java
Utils.minIndex
public static /*@pure@*/ int minIndex(int[] ints) { int minimum = 0; int minIndex = 0; for (int i = 0; i < ints.length; i++) { if ((i == 0) || (ints[i] < minimum)) { minIndex = i; minimum = ints[i]; } } return minIndex; }
java
public static /*@pure@*/ int minIndex(int[] ints) { int minimum = 0; int minIndex = 0; for (int i = 0; i < ints.length; i++) { if ((i == 0) || (ints[i] < minimum)) { minIndex = i; minimum = ints[i]; } } return minIndex; }
[ "public", "static", "/*@pure@*/", "int", "minIndex", "(", "int", "[", "]", "ints", ")", "{", "int", "minimum", "=", "0", ";", "int", "minIndex", "=", "0", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "ints", ".", "length", ";", "i", "++", ")", "{", "if", "(", "(", "i", "==", "0", ")", "||", "(", "ints", "[", "i", "]", "<", "minimum", ")", ")", "{", "minIndex", "=", "i", ";", "minimum", "=", "ints", "[", "i", "]", ";", "}", "}", "return", "minIndex", ";", "}" ]
Returns index of minimum element in a given array of integers. First minimum is returned. @param ints the array of integers @return the index of the minimum element
[ "Returns", "index", "of", "minimum", "element", "in", "a", "given", "array", "of", "integers", ".", "First", "minimum", "is", "returned", "." ]
395982e5100bfe75a3a4d26115462ce2cc74cbb0
https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/moa/core/Utils.java#L1137-L1150
28,807
Waikato/moa
moa/src/main/java/moa/core/Utils.java
Utils.minIndex
public static /*@pure@*/ int minIndex(double[] doubles) { double minimum = 0; int minIndex = 0; for (int i = 0; i < doubles.length; i++) { if ((i == 0) || (doubles[i] < minimum)) { minIndex = i; minimum = doubles[i]; } } return minIndex; }
java
public static /*@pure@*/ int minIndex(double[] doubles) { double minimum = 0; int minIndex = 0; for (int i = 0; i < doubles.length; i++) { if ((i == 0) || (doubles[i] < minimum)) { minIndex = i; minimum = doubles[i]; } } return minIndex; }
[ "public", "static", "/*@pure@*/", "int", "minIndex", "(", "double", "[", "]", "doubles", ")", "{", "double", "minimum", "=", "0", ";", "int", "minIndex", "=", "0", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "doubles", ".", "length", ";", "i", "++", ")", "{", "if", "(", "(", "i", "==", "0", ")", "||", "(", "doubles", "[", "i", "]", "<", "minimum", ")", ")", "{", "minIndex", "=", "i", ";", "minimum", "=", "doubles", "[", "i", "]", ";", "}", "}", "return", "minIndex", ";", "}" ]
Returns index of minimum element in a given array of doubles. First minimum is returned. @param doubles the array of doubles @return the index of the minimum element
[ "Returns", "index", "of", "minimum", "element", "in", "a", "given", "array", "of", "doubles", ".", "First", "minimum", "is", "returned", "." ]
395982e5100bfe75a3a4d26115462ce2cc74cbb0
https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/moa/core/Utils.java#L1159-L1172
28,808
Waikato/moa
moa/src/main/java/moa/core/Utils.java
Utils.normalize
public static void normalize(double[] doubles) { double sum = 0; for (int i = 0; i < doubles.length; i++) { sum += doubles[i]; } normalize(doubles, sum); }
java
public static void normalize(double[] doubles) { double sum = 0; for (int i = 0; i < doubles.length; i++) { sum += doubles[i]; } normalize(doubles, sum); }
[ "public", "static", "void", "normalize", "(", "double", "[", "]", "doubles", ")", "{", "double", "sum", "=", "0", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "doubles", ".", "length", ";", "i", "++", ")", "{", "sum", "+=", "doubles", "[", "i", "]", ";", "}", "normalize", "(", "doubles", ",", "sum", ")", ";", "}" ]
Normalizes the doubles in the array by their sum. @param doubles the array of double @exception IllegalArgumentException if sum is Zero or NaN
[ "Normalizes", "the", "doubles", "in", "the", "array", "by", "their", "sum", "." ]
395982e5100bfe75a3a4d26115462ce2cc74cbb0
https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/moa/core/Utils.java#L1180-L1187
28,809
Waikato/moa
moa/src/main/java/moa/core/Utils.java
Utils.normalize
public static void normalize(double[] doubles, double sum) { if (Double.isNaN(sum)) { throw new IllegalArgumentException("Can't normalize array. Sum is NaN."); } if (sum == 0) { // Maybe this should just be a return. throw new IllegalArgumentException("Can't normalize array. Sum is zero."); } for (int i = 0; i < doubles.length; i++) { doubles[i] /= sum; } }
java
public static void normalize(double[] doubles, double sum) { if (Double.isNaN(sum)) { throw new IllegalArgumentException("Can't normalize array. Sum is NaN."); } if (sum == 0) { // Maybe this should just be a return. throw new IllegalArgumentException("Can't normalize array. Sum is zero."); } for (int i = 0; i < doubles.length; i++) { doubles[i] /= sum; } }
[ "public", "static", "void", "normalize", "(", "double", "[", "]", "doubles", ",", "double", "sum", ")", "{", "if", "(", "Double", ".", "isNaN", "(", "sum", ")", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Can't normalize array. Sum is NaN.\"", ")", ";", "}", "if", "(", "sum", "==", "0", ")", "{", "// Maybe this should just be a return.", "throw", "new", "IllegalArgumentException", "(", "\"Can't normalize array. Sum is zero.\"", ")", ";", "}", "for", "(", "int", "i", "=", "0", ";", "i", "<", "doubles", ".", "length", ";", "i", "++", ")", "{", "doubles", "[", "i", "]", "/=", "sum", ";", "}", "}" ]
Normalizes the doubles in the array using the given value. @param doubles the array of double @param sum the value by which the doubles are to be normalized @exception IllegalArgumentException if sum is zero or NaN
[ "Normalizes", "the", "doubles", "in", "the", "array", "using", "the", "given", "value", "." ]
395982e5100bfe75a3a4d26115462ce2cc74cbb0
https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/moa/core/Utils.java#L1196-L1208
28,810
Waikato/moa
moa/src/main/java/moa/core/Utils.java
Utils.logs2probs
public static double[] logs2probs(double[] a) { double max = a[maxIndex(a)]; double sum = 0.0; double[] result = new double[a.length]; for(int i = 0; i < a.length; i++) { result[i] = Math.exp(a[i] - max); sum += result[i]; } normalize(result, sum); return result; }
java
public static double[] logs2probs(double[] a) { double max = a[maxIndex(a)]; double sum = 0.0; double[] result = new double[a.length]; for(int i = 0; i < a.length; i++) { result[i] = Math.exp(a[i] - max); sum += result[i]; } normalize(result, sum); return result; }
[ "public", "static", "double", "[", "]", "logs2probs", "(", "double", "[", "]", "a", ")", "{", "double", "max", "=", "a", "[", "maxIndex", "(", "a", ")", "]", ";", "double", "sum", "=", "0.0", ";", "double", "[", "]", "result", "=", "new", "double", "[", "a", ".", "length", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "a", ".", "length", ";", "i", "++", ")", "{", "result", "[", "i", "]", "=", "Math", ".", "exp", "(", "a", "[", "i", "]", "-", "max", ")", ";", "sum", "+=", "result", "[", "i", "]", ";", "}", "normalize", "(", "result", ",", "sum", ")", ";", "return", "result", ";", "}" ]
Converts an array containing the natural logarithms of probabilities stored in a vector back into probabilities. The probabilities are assumed to sum to one. @param a an array holding the natural logarithms of the probabilities @return the converted array
[ "Converts", "an", "array", "containing", "the", "natural", "logarithms", "of", "probabilities", "stored", "in", "a", "vector", "back", "into", "probabilities", ".", "The", "probabilities", "are", "assumed", "to", "sum", "to", "one", "." ]
395982e5100bfe75a3a4d26115462ce2cc74cbb0
https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/moa/core/Utils.java#L1218-L1232
28,811
Waikato/moa
moa/src/main/java/moa/core/Utils.java
Utils.probToLogOdds
public static /*@pure@*/ double probToLogOdds(double prob) { if (gr(prob, 1) || (sm(prob, 0))) { throw new IllegalArgumentException("probToLogOdds: probability must " + "be in [0,1] "+prob); } double p = SMALL + (1.0 - 2 * SMALL) * prob; return Math.log(p / (1 - p)); }
java
public static /*@pure@*/ double probToLogOdds(double prob) { if (gr(prob, 1) || (sm(prob, 0))) { throw new IllegalArgumentException("probToLogOdds: probability must " + "be in [0,1] "+prob); } double p = SMALL + (1.0 - 2 * SMALL) * prob; return Math.log(p / (1 - p)); }
[ "public", "static", "/*@pure@*/", "double", "probToLogOdds", "(", "double", "prob", ")", "{", "if", "(", "gr", "(", "prob", ",", "1", ")", "||", "(", "sm", "(", "prob", ",", "0", ")", ")", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"probToLogOdds: probability must \"", "+", "\"be in [0,1] \"", "+", "prob", ")", ";", "}", "double", "p", "=", "SMALL", "+", "(", "1.0", "-", "2", "*", "SMALL", ")", "*", "prob", ";", "return", "Math", ".", "log", "(", "p", "/", "(", "1", "-", "p", ")", ")", ";", "}" ]
Returns the log-odds for a given probabilitiy. @param prob the probabilitiy @return the log-odds after the probability has been mapped to [Utils.SMALL, 1-Utils.SMALL]
[ "Returns", "the", "log", "-", "odds", "for", "a", "given", "probabilitiy", "." ]
395982e5100bfe75a3a4d26115462ce2cc74cbb0
https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/moa/core/Utils.java#L1242-L1250
28,812
Waikato/moa
moa/src/main/java/moa/core/Utils.java
Utils.roundDouble
public static /*@pure@*/ double roundDouble(double value,int afterDecimalPoint) { double mask = Math.pow(10.0, (double)afterDecimalPoint); return (double)(Math.round(value * mask)) / mask; }
java
public static /*@pure@*/ double roundDouble(double value,int afterDecimalPoint) { double mask = Math.pow(10.0, (double)afterDecimalPoint); return (double)(Math.round(value * mask)) / mask; }
[ "public", "static", "/*@pure@*/", "double", "roundDouble", "(", "double", "value", ",", "int", "afterDecimalPoint", ")", "{", "double", "mask", "=", "Math", ".", "pow", "(", "10.0", ",", "(", "double", ")", "afterDecimalPoint", ")", ";", "return", "(", "double", ")", "(", "Math", ".", "round", "(", "value", "*", "mask", ")", ")", "/", "mask", ";", "}" ]
Rounds a double to the given number of decimal places. @param value the double value @param afterDecimalPoint the number of digits after the decimal point @return the double rounded to the given precision
[ "Rounds", "a", "double", "to", "the", "given", "number", "of", "decimal", "places", "." ]
395982e5100bfe75a3a4d26115462ce2cc74cbb0
https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/moa/core/Utils.java#L1307-L1312
28,813
Waikato/moa
moa/src/main/java/moa/core/Utils.java
Utils.variance
public static /*@pure@*/ double variance(double[] vector) { double sum = 0, sumSquared = 0; if (vector.length <= 1) { return 0; } for (int i = 0; i < vector.length; i++) { sum += vector[i]; sumSquared += (vector[i] * vector[i]); } double result = (sumSquared - (sum * sum / (double) vector.length)) / (double) (vector.length - 1); // We don't like negative variance if (result < 0) { return 0; } else { return result; } }
java
public static /*@pure@*/ double variance(double[] vector) { double sum = 0, sumSquared = 0; if (vector.length <= 1) { return 0; } for (int i = 0; i < vector.length; i++) { sum += vector[i]; sumSquared += (vector[i] * vector[i]); } double result = (sumSquared - (sum * sum / (double) vector.length)) / (double) (vector.length - 1); // We don't like negative variance if (result < 0) { return 0; } else { return result; } }
[ "public", "static", "/*@pure@*/", "double", "variance", "(", "double", "[", "]", "vector", ")", "{", "double", "sum", "=", "0", ",", "sumSquared", "=", "0", ";", "if", "(", "vector", ".", "length", "<=", "1", ")", "{", "return", "0", ";", "}", "for", "(", "int", "i", "=", "0", ";", "i", "<", "vector", ".", "length", ";", "i", "++", ")", "{", "sum", "+=", "vector", "[", "i", "]", ";", "sumSquared", "+=", "(", "vector", "[", "i", "]", "*", "vector", "[", "i", "]", ")", ";", "}", "double", "result", "=", "(", "sumSquared", "-", "(", "sum", "*", "sum", "/", "(", "double", ")", "vector", ".", "length", ")", ")", "/", "(", "double", ")", "(", "vector", ".", "length", "-", "1", ")", ";", "// We don't like negative variance", "if", "(", "result", "<", "0", ")", "{", "return", "0", ";", "}", "else", "{", "return", "result", ";", "}", "}" ]
Computes the variance for an array of doubles. @param vector the array @return the variance
[ "Computes", "the", "variance", "for", "an", "array", "of", "doubles", "." ]
395982e5100bfe75a3a4d26115462ce2cc74cbb0
https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/moa/core/Utils.java#L1447-L1467
28,814
Waikato/moa
moa/src/main/java/moa/core/Utils.java
Utils.sum
public static /*@pure@*/ int sum(int[] ints) { int sum = 0; for (int i = 0; i < ints.length; i++) { sum += ints[i]; } return sum; }
java
public static /*@pure@*/ int sum(int[] ints) { int sum = 0; for (int i = 0; i < ints.length; i++) { sum += ints[i]; } return sum; }
[ "public", "static", "/*@pure@*/", "int", "sum", "(", "int", "[", "]", "ints", ")", "{", "int", "sum", "=", "0", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "ints", ".", "length", ";", "i", "++", ")", "{", "sum", "+=", "ints", "[", "i", "]", ";", "}", "return", "sum", ";", "}" ]
Computes the sum of the elements of an array of integers. @param ints the array of integers @return the sum of the elements
[ "Computes", "the", "sum", "of", "the", "elements", "of", "an", "array", "of", "integers", "." ]
395982e5100bfe75a3a4d26115462ce2cc74cbb0
https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/moa/core/Utils.java#L1491-L1499
28,815
Waikato/moa
moa/src/main/java/moa/core/Utils.java
Utils.quickSort
private static void quickSort(/*@non_null@*/ double[] array, /*@non_null@*/ int[] index, int left, int right) { if (left < right) { int middle = partition(array, index, left, right); quickSort(array, index, left, middle); quickSort(array, index, middle + 1, right); } }
java
private static void quickSort(/*@non_null@*/ double[] array, /*@non_null@*/ int[] index, int left, int right) { if (left < right) { int middle = partition(array, index, left, right); quickSort(array, index, left, middle); quickSort(array, index, middle + 1, right); } }
[ "private", "static", "void", "quickSort", "(", "/*@non_null@*/", "double", "[", "]", "array", ",", "/*@non_null@*/", "int", "[", "]", "index", ",", "int", "left", ",", "int", "right", ")", "{", "if", "(", "left", "<", "right", ")", "{", "int", "middle", "=", "partition", "(", "array", ",", "index", ",", "left", ",", "right", ")", ";", "quickSort", "(", "array", ",", "index", ",", "left", ",", "middle", ")", ";", "quickSort", "(", "array", ",", "index", ",", "middle", "+", "1", ",", "right", ")", ";", "}", "}" ]
assignable index;
[ "assignable", "index", ";" ]
395982e5100bfe75a3a4d26115462ce2cc74cbb0
https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/moa/core/Utils.java#L1604-L1612
28,816
Waikato/moa
moa/src/main/java/moa/core/Utils.java
Utils.breakUp
public static String[] breakUp(String s, int columns) { Vector<String> result; String line; BreakIterator boundary; int boundaryStart; int boundaryEnd; String word; String punctuation; int i; String[] lines; result = new Vector<String>(); punctuation = " .,;:!?'\""; lines = s.split("\n"); for (i = 0; i < lines.length; i++) { boundary = BreakIterator.getWordInstance(); boundary.setText(lines[i]); boundaryStart = boundary.first(); boundaryEnd = boundary.next(); line = ""; while (boundaryEnd != BreakIterator.DONE) { word = lines[i].substring(boundaryStart, boundaryEnd); if (line.length() >= columns) { if (word.length() == 1) { if (punctuation.indexOf(word.charAt(0)) > -1) { line += word; word = ""; } } result.add(line); line = ""; } line += word; boundaryStart = boundaryEnd; boundaryEnd = boundary.next(); } if (line.length() > 0) result.add(line); } return result.toArray(new String[result.size()]); }
java
public static String[] breakUp(String s, int columns) { Vector<String> result; String line; BreakIterator boundary; int boundaryStart; int boundaryEnd; String word; String punctuation; int i; String[] lines; result = new Vector<String>(); punctuation = " .,;:!?'\""; lines = s.split("\n"); for (i = 0; i < lines.length; i++) { boundary = BreakIterator.getWordInstance(); boundary.setText(lines[i]); boundaryStart = boundary.first(); boundaryEnd = boundary.next(); line = ""; while (boundaryEnd != BreakIterator.DONE) { word = lines[i].substring(boundaryStart, boundaryEnd); if (line.length() >= columns) { if (word.length() == 1) { if (punctuation.indexOf(word.charAt(0)) > -1) { line += word; word = ""; } } result.add(line); line = ""; } line += word; boundaryStart = boundaryEnd; boundaryEnd = boundary.next(); } if (line.length() > 0) result.add(line); } return result.toArray(new String[result.size()]); }
[ "public", "static", "String", "[", "]", "breakUp", "(", "String", "s", ",", "int", "columns", ")", "{", "Vector", "<", "String", ">", "result", ";", "String", "line", ";", "BreakIterator", "boundary", ";", "int", "boundaryStart", ";", "int", "boundaryEnd", ";", "String", "word", ";", "String", "punctuation", ";", "int", "i", ";", "String", "[", "]", "lines", ";", "result", "=", "new", "Vector", "<", "String", ">", "(", ")", ";", "punctuation", "=", "\" .,;:!?'\\\"\"", ";", "lines", "=", "s", ".", "split", "(", "\"\\n\"", ")", ";", "for", "(", "i", "=", "0", ";", "i", "<", "lines", ".", "length", ";", "i", "++", ")", "{", "boundary", "=", "BreakIterator", ".", "getWordInstance", "(", ")", ";", "boundary", ".", "setText", "(", "lines", "[", "i", "]", ")", ";", "boundaryStart", "=", "boundary", ".", "first", "(", ")", ";", "boundaryEnd", "=", "boundary", ".", "next", "(", ")", ";", "line", "=", "\"\"", ";", "while", "(", "boundaryEnd", "!=", "BreakIterator", ".", "DONE", ")", "{", "word", "=", "lines", "[", "i", "]", ".", "substring", "(", "boundaryStart", ",", "boundaryEnd", ")", ";", "if", "(", "line", ".", "length", "(", ")", ">=", "columns", ")", "{", "if", "(", "word", ".", "length", "(", ")", "==", "1", ")", "{", "if", "(", "punctuation", ".", "indexOf", "(", "word", ".", "charAt", "(", "0", ")", ")", ">", "-", "1", ")", "{", "line", "+=", "word", ";", "word", "=", "\"\"", ";", "}", "}", "result", ".", "add", "(", "line", ")", ";", "line", "=", "\"\"", ";", "}", "line", "+=", "word", ";", "boundaryStart", "=", "boundaryEnd", ";", "boundaryEnd", "=", "boundary", ".", "next", "(", ")", ";", "}", "if", "(", "line", ".", "length", "(", ")", ">", "0", ")", "result", ".", "add", "(", "line", ")", ";", "}", "return", "result", ".", "toArray", "(", "new", "String", "[", "result", ".", "size", "(", ")", "]", ")", ";", "}" ]
Breaks up the string, if wider than "columns" characters. @param s the string to process @param columns the width in columns @return the processed string
[ "Breaks", "up", "the", "string", "if", "wider", "than", "columns", "characters", "." ]
395982e5100bfe75a3a4d26115462ce2cc74cbb0
https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/moa/core/Utils.java#L1810-L1853
28,817
Waikato/moa
moa/src/main/java/moa/capabilities/CapabilityRequirement.java
CapabilityRequirement.isMetBy
public boolean isMetBy(Class<?> klass) { // Classes which aren't capabilities handlers have an assumed // set of capabilities if (!CapabilitiesHandler.class.isAssignableFrom(klass)) return isMetBy(NON_HANDLER_CAPABILITIES); // Attempt to instantiate an instance of the class CapabilitiesHandler instance; try { instance = (CapabilitiesHandler) klass.newInstance(); } catch (InstantiationException | IllegalAccessException e) { throw new RuntimeException("Couldn't instantiate CapabilitiesHandler " + klass.getSimpleName(), e); } // Test the instance return isMetBy(instance); }
java
public boolean isMetBy(Class<?> klass) { // Classes which aren't capabilities handlers have an assumed // set of capabilities if (!CapabilitiesHandler.class.isAssignableFrom(klass)) return isMetBy(NON_HANDLER_CAPABILITIES); // Attempt to instantiate an instance of the class CapabilitiesHandler instance; try { instance = (CapabilitiesHandler) klass.newInstance(); } catch (InstantiationException | IllegalAccessException e) { throw new RuntimeException("Couldn't instantiate CapabilitiesHandler " + klass.getSimpleName(), e); } // Test the instance return isMetBy(instance); }
[ "public", "boolean", "isMetBy", "(", "Class", "<", "?", ">", "klass", ")", "{", "// Classes which aren't capabilities handlers have an assumed", "// set of capabilities", "if", "(", "!", "CapabilitiesHandler", ".", "class", ".", "isAssignableFrom", "(", "klass", ")", ")", "return", "isMetBy", "(", "NON_HANDLER_CAPABILITIES", ")", ";", "// Attempt to instantiate an instance of the class", "CapabilitiesHandler", "instance", ";", "try", "{", "instance", "=", "(", "CapabilitiesHandler", ")", "klass", ".", "newInstance", "(", ")", ";", "}", "catch", "(", "InstantiationException", "|", "IllegalAccessException", "e", ")", "{", "throw", "new", "RuntimeException", "(", "\"Couldn't instantiate CapabilitiesHandler \"", "+", "klass", ".", "getSimpleName", "(", ")", ",", "e", ")", ";", "}", "// Test the instance", "return", "isMetBy", "(", "instance", ")", ";", "}" ]
Tests if the requirement is met by the given class. @param klass The class to test. @return True if the class meets the requirements, false if not.
[ "Tests", "if", "the", "requirement", "is", "met", "by", "the", "given", "class", "." ]
395982e5100bfe75a3a4d26115462ce2cc74cbb0
https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/moa/capabilities/CapabilityRequirement.java#L85-L104
28,818
Waikato/moa
moa/src/main/java/moa/capabilities/CapabilityRequirement.java
CapabilityRequirement.hasAll
public static CapabilityRequirement hasAll(Capability... capabilities) { return new CapabilityRequirement(c -> { for (Capability capability : capabilities) { if (!c.hasCapability(capability)) return false; } return true; }); }
java
public static CapabilityRequirement hasAll(Capability... capabilities) { return new CapabilityRequirement(c -> { for (Capability capability : capabilities) { if (!c.hasCapability(capability)) return false; } return true; }); }
[ "public", "static", "CapabilityRequirement", "hasAll", "(", "Capability", "...", "capabilities", ")", "{", "return", "new", "CapabilityRequirement", "(", "c", "->", "{", "for", "(", "Capability", "capability", ":", "capabilities", ")", "{", "if", "(", "!", "c", ".", "hasCapability", "(", "capability", ")", ")", "return", "false", ";", "}", "return", "true", ";", "}", ")", ";", "}" ]
Creates a requirement that a given set of capabilities have all of the specified capabilities. @param capabilities The capabilities that a tested set must have. @return The requirement.
[ "Creates", "a", "requirement", "that", "a", "given", "set", "of", "capabilities", "have", "all", "of", "the", "specified", "capabilities", "." ]
395982e5100bfe75a3a4d26115462ce2cc74cbb0
https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/moa/capabilities/CapabilityRequirement.java#L124-L132
28,819
Waikato/moa
moa/src/main/java/moa/gui/visualization/GraphMultiCurve.java
GraphMultiCurve.setGraph
protected void setGraph(MeasureCollection[] measures, MeasureCollection[] measureStds, int[] processFrequencies, Color[] colors){ // this.processFrequencies = processFrequencies; super.setGraph(measures, measureStds, colors); }
java
protected void setGraph(MeasureCollection[] measures, MeasureCollection[] measureStds, int[] processFrequencies, Color[] colors){ // this.processFrequencies = processFrequencies; super.setGraph(measures, measureStds, colors); }
[ "protected", "void", "setGraph", "(", "MeasureCollection", "[", "]", "measures", ",", "MeasureCollection", "[", "]", "measureStds", ",", "int", "[", "]", "processFrequencies", ",", "Color", "[", "]", "colors", ")", "{", "// \tthis.processFrequencies = processFrequencies; ", "super", ".", "setGraph", "(", "measures", ",", "measureStds", ",", "colors", ")", ";", "}" ]
Updates the measure collection information and repaints the curves. @param measures information about the curves @param measureStds standard deviation of the measures @param processFrequencies information about the process frequencies of the curves @param colors color encodings of the curves
[ "Updates", "the", "measure", "collection", "information", "and", "repaints", "the", "curves", "." ]
395982e5100bfe75a3a4d26115462ce2cc74cbb0
https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/moa/gui/visualization/GraphMultiCurve.java#L49-L52
28,820
Waikato/moa
moa/src/main/java/moa/gui/visualization/GraphMultiCurve.java
GraphMultiCurve.paintFullCurve
private void paintFullCurve(Graphics g, int i){ if (this.measures[i].getNumberOfValues(this.measureSelected) == 0) { // no values of this measure available return; } g.setColor(this.colors[i]); int height = getHeight(); // // compute the relation of minimum PF and current PF // double processFrequencyFactor = pf / this.min_processFrequency; int n = this.measures[i].getNumberOfValues(this.measureSelected); int[] x = new int[n]; int[] y = new int[n]; for (int j = 0; j < n; j++) { x[j] = (int) (j * x_resolution); y[j] = (int)(height-(this.measures[i].getValue(this.measureSelected, j)/this.upper_y_value)*height); if (this.isStandardDeviationPainted) { int len = (int) ((this.measureStds[i].getValue(this.measureSelected, j)/this.upper_y_value)*height); paintStandardDeviation(g, len, x[j], y[j]); } } g.drawPolyline(x, y, n); }
java
private void paintFullCurve(Graphics g, int i){ if (this.measures[i].getNumberOfValues(this.measureSelected) == 0) { // no values of this measure available return; } g.setColor(this.colors[i]); int height = getHeight(); // // compute the relation of minimum PF and current PF // double processFrequencyFactor = pf / this.min_processFrequency; int n = this.measures[i].getNumberOfValues(this.measureSelected); int[] x = new int[n]; int[] y = new int[n]; for (int j = 0; j < n; j++) { x[j] = (int) (j * x_resolution); y[j] = (int)(height-(this.measures[i].getValue(this.measureSelected, j)/this.upper_y_value)*height); if (this.isStandardDeviationPainted) { int len = (int) ((this.measureStds[i].getValue(this.measureSelected, j)/this.upper_y_value)*height); paintStandardDeviation(g, len, x[j], y[j]); } } g.drawPolyline(x, y, n); }
[ "private", "void", "paintFullCurve", "(", "Graphics", "g", ",", "int", "i", ")", "{", "if", "(", "this", ".", "measures", "[", "i", "]", ".", "getNumberOfValues", "(", "this", ".", "measureSelected", ")", "==", "0", ")", "{", "// no values of this measure available", "return", ";", "}", "g", ".", "setColor", "(", "this", ".", "colors", "[", "i", "]", ")", ";", "int", "height", "=", "getHeight", "(", ")", ";", "// // compute the relation of minimum PF and current PF", "// double processFrequencyFactor = pf / this.min_processFrequency;", "int", "n", "=", "this", ".", "measures", "[", "i", "]", ".", "getNumberOfValues", "(", "this", ".", "measureSelected", ")", ";", "int", "[", "]", "x", "=", "new", "int", "[", "n", "]", ";", "int", "[", "]", "y", "=", "new", "int", "[", "n", "]", ";", "for", "(", "int", "j", "=", "0", ";", "j", "<", "n", ";", "j", "++", ")", "{", "x", "[", "j", "]", "=", "(", "int", ")", "(", "j", "*", "x_resolution", ")", ";", "y", "[", "j", "]", "=", "(", "int", ")", "(", "height", "-", "(", "this", ".", "measures", "[", "i", "]", ".", "getValue", "(", "this", ".", "measureSelected", ",", "j", ")", "/", "this", ".", "upper_y_value", ")", "*", "height", ")", ";", "if", "(", "this", ".", "isStandardDeviationPainted", ")", "{", "int", "len", "=", "(", "int", ")", "(", "(", "this", ".", "measureStds", "[", "i", "]", ".", "getValue", "(", "this", ".", "measureSelected", ",", "j", ")", "/", "this", ".", "upper_y_value", ")", "*", "height", ")", ";", "paintStandardDeviation", "(", "g", ",", "len", ",", "x", "[", "j", "]", ",", "y", "[", "j", "]", ")", ";", "}", "}", "g", ".", "drawPolyline", "(", "x", ",", "y", ",", "n", ")", ";", "}" ]
Draws a single curve on the canvas. @param g the Graphics context in which to paint @param i index of the currently selected measure
[ "Draws", "a", "single", "curve", "on", "the", "canvas", "." ]
395982e5100bfe75a3a4d26115462ce2cc74cbb0
https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/moa/gui/visualization/GraphMultiCurve.java#L85-L114
28,821
Waikato/moa
moa/src/main/java/moa/gui/experimentertab/Measure.java
Measure.computeValue
public void computeValue(DoubleVector values) { if (this.isType()) { setValues(values); double sumDif = 0.0; this.value = this.values.sumOfValues() / (double) values.numValues(); for (int i = 0; i < this.values.numValues(); i++) { double dif = this.values.getValue(i) - this.value; sumDif += Math.pow(dif, 2); } sumDif = sumDif / this.values.numValues(); this.std = Math.sqrt(sumDif); } }
java
public void computeValue(DoubleVector values) { if (this.isType()) { setValues(values); double sumDif = 0.0; this.value = this.values.sumOfValues() / (double) values.numValues(); for (int i = 0; i < this.values.numValues(); i++) { double dif = this.values.getValue(i) - this.value; sumDif += Math.pow(dif, 2); } sumDif = sumDif / this.values.numValues(); this.std = Math.sqrt(sumDif); } }
[ "public", "void", "computeValue", "(", "DoubleVector", "values", ")", "{", "if", "(", "this", ".", "isType", "(", ")", ")", "{", "setValues", "(", "values", ")", ";", "double", "sumDif", "=", "0.0", ";", "this", ".", "value", "=", "this", ".", "values", ".", "sumOfValues", "(", ")", "/", "(", "double", ")", "values", ".", "numValues", "(", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "this", ".", "values", ".", "numValues", "(", ")", ";", "i", "++", ")", "{", "double", "dif", "=", "this", ".", "values", ".", "getValue", "(", "i", ")", "-", "this", ".", "value", ";", "sumDif", "+=", "Math", ".", "pow", "(", "dif", ",", "2", ")", ";", "}", "sumDif", "=", "sumDif", "/", "this", ".", "values", ".", "numValues", "(", ")", ";", "this", ".", "std", "=", "Math", ".", "sqrt", "(", "sumDif", ")", ";", "}", "}" ]
Calculates the value of measure @param values
[ "Calculates", "the", "value", "of", "measure" ]
395982e5100bfe75a3a4d26115462ce2cc74cbb0
https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/moa/gui/experimentertab/Measure.java#L168-L181
28,822
Waikato/moa
moa/src/main/java/moa/gui/visualization/AbstractGraphAxes.java
AbstractGraphAxes.xAxis
protected void xAxis(Graphics g) { g.setColor(Color.BLACK); // x-axis line g.drawLine(X_OFFSET_LEFT, calcY(0), width + X_OFFSET_LEFT, calcY(0)); drawXLabels(g); }
java
protected void xAxis(Graphics g) { g.setColor(Color.BLACK); // x-axis line g.drawLine(X_OFFSET_LEFT, calcY(0), width + X_OFFSET_LEFT, calcY(0)); drawXLabels(g); }
[ "protected", "void", "xAxis", "(", "Graphics", "g", ")", "{", "g", ".", "setColor", "(", "Color", ".", "BLACK", ")", ";", "// x-axis line", "g", ".", "drawLine", "(", "X_OFFSET_LEFT", ",", "calcY", "(", "0", ")", ",", "width", "+", "X_OFFSET_LEFT", ",", "calcY", "(", "0", ")", ")", ";", "drawXLabels", "(", "g", ")", ";", "}" ]
Draws the x axis, containing of the axis line and the labels. @param g the Graphics context in which to paint
[ "Draws", "the", "x", "axis", "containing", "of", "the", "axis", "line", "and", "the", "labels", "." ]
395982e5100bfe75a3a4d26115462ce2cc74cbb0
https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/moa/gui/visualization/AbstractGraphAxes.java#L129-L136
28,823
Waikato/moa
moa/src/main/java/moa/gui/visualization/AbstractGraphAxes.java
AbstractGraphAxes.yAxis
private void yAxis(Graphics g) { // y-axis g.setColor(Color.BLACK); g.drawLine(X_OFFSET_LEFT, calcY(0), X_OFFSET_LEFT, Y_OFFSET_TOP); // center horizontal line g.setColor(new Color(220, 220, 220)); g.drawLine(X_OFFSET_LEFT, height / 2 + Y_OFFSET_TOP, getWidth(), height / 2 + Y_OFFSET_TOP); g.setColor(Color.BLACK); // y-achsis markers + labels DecimalFormat d = new DecimalFormat("0.00"); double numLabels = Math.min(Math.pow(2, y_resolution), 32); /* * technically, this is numLabels-1, but as we're iterating 0 <= i <= * numLabels, we need the extra label. Also don't draw more than 32 * labels. */ for (int i = 0; i <= numLabels; i++) { double fraction = i / numLabels; double value = fraction * upper_y_value; g.drawString(d.format(value), 1, (int) ((1 - fraction) * height) + Y_OFFSET_TOP + 5); g.drawLine(X_OFFSET_LEFT - 5, (int) ((1 - fraction) * height) + Y_OFFSET_TOP, X_OFFSET_LEFT, (int) ((1 - fraction) * height) + Y_OFFSET_TOP); } }
java
private void yAxis(Graphics g) { // y-axis g.setColor(Color.BLACK); g.drawLine(X_OFFSET_LEFT, calcY(0), X_OFFSET_LEFT, Y_OFFSET_TOP); // center horizontal line g.setColor(new Color(220, 220, 220)); g.drawLine(X_OFFSET_LEFT, height / 2 + Y_OFFSET_TOP, getWidth(), height / 2 + Y_OFFSET_TOP); g.setColor(Color.BLACK); // y-achsis markers + labels DecimalFormat d = new DecimalFormat("0.00"); double numLabels = Math.min(Math.pow(2, y_resolution), 32); /* * technically, this is numLabels-1, but as we're iterating 0 <= i <= * numLabels, we need the extra label. Also don't draw more than 32 * labels. */ for (int i = 0; i <= numLabels; i++) { double fraction = i / numLabels; double value = fraction * upper_y_value; g.drawString(d.format(value), 1, (int) ((1 - fraction) * height) + Y_OFFSET_TOP + 5); g.drawLine(X_OFFSET_LEFT - 5, (int) ((1 - fraction) * height) + Y_OFFSET_TOP, X_OFFSET_LEFT, (int) ((1 - fraction) * height) + Y_OFFSET_TOP); } }
[ "private", "void", "yAxis", "(", "Graphics", "g", ")", "{", "// y-axis", "g", ".", "setColor", "(", "Color", ".", "BLACK", ")", ";", "g", ".", "drawLine", "(", "X_OFFSET_LEFT", ",", "calcY", "(", "0", ")", ",", "X_OFFSET_LEFT", ",", "Y_OFFSET_TOP", ")", ";", "// center horizontal line", "g", ".", "setColor", "(", "new", "Color", "(", "220", ",", "220", ",", "220", ")", ")", ";", "g", ".", "drawLine", "(", "X_OFFSET_LEFT", ",", "height", "/", "2", "+", "Y_OFFSET_TOP", ",", "getWidth", "(", ")", ",", "height", "/", "2", "+", "Y_OFFSET_TOP", ")", ";", "g", ".", "setColor", "(", "Color", ".", "BLACK", ")", ";", "// y-achsis markers + labels", "DecimalFormat", "d", "=", "new", "DecimalFormat", "(", "\"0.00\"", ")", ";", "double", "numLabels", "=", "Math", ".", "min", "(", "Math", ".", "pow", "(", "2", ",", "y_resolution", ")", ",", "32", ")", ";", "/*\n * technically, this is numLabels-1, but as we're iterating 0 <= i <=\n * numLabels, we need the extra label. Also don't draw more than 32\n * labels.\n */", "for", "(", "int", "i", "=", "0", ";", "i", "<=", "numLabels", ";", "i", "++", ")", "{", "double", "fraction", "=", "i", "/", "numLabels", ";", "double", "value", "=", "fraction", "*", "upper_y_value", ";", "g", ".", "drawString", "(", "d", ".", "format", "(", "value", ")", ",", "1", ",", "(", "int", ")", "(", "(", "1", "-", "fraction", ")", "*", "height", ")", "+", "Y_OFFSET_TOP", "+", "5", ")", ";", "g", ".", "drawLine", "(", "X_OFFSET_LEFT", "-", "5", ",", "(", "int", ")", "(", "(", "1", "-", "fraction", ")", "*", "height", ")", "+", "Y_OFFSET_TOP", ",", "X_OFFSET_LEFT", ",", "(", "int", ")", "(", "(", "1", "-", "fraction", ")", "*", "height", ")", "+", "Y_OFFSET_TOP", ")", ";", "}", "}" ]
Draws the y axis, containing og the axis line, the horizontal helping line and the labels. @param g the Graphics context in which to paint
[ "Draws", "the", "y", "axis", "containing", "og", "the", "axis", "line", "the", "horizontal", "helping", "line", "and", "the", "labels", "." ]
395982e5100bfe75a3a4d26115462ce2cc74cbb0
https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/moa/gui/visualization/AbstractGraphAxes.java#L153-L186
28,824
Waikato/moa
moa/src/main/java/moa/evaluation/preview/MeanPreviewCollection.java
MeanPreviewCollection.constructMeanStdPreviewsForParam
private void constructMeanStdPreviewsForParam( int numEntriesPerPreview, int numParamValues, int paramValue) { // calculate mean List<double[]> meanParamMeasurements = calculateMeanMeasurementsForParam( numEntriesPerPreview, numParamValues, paramValue); // calculate standard deviation List<double[]> stdParamMeasurements = calculateStdMeasurementsForParam( numEntriesPerPreview, numParamValues, paramValue, meanParamMeasurements); // get actual measurement names (first four are only additional IDs) String[] meanMeasurementNames = this.origMultiRunPreviews.getMeasurementNames(); meanMeasurementNames = Arrays.copyOfRange( meanMeasurementNames, 4, meanMeasurementNames.length); // Create names for standard deviations. // First name is used for indexing and remains unchanged. For the // remaining names, [std] is prepended to the original name. String[] stdMeasurementNames = new String[meanMeasurementNames.length]; stdMeasurementNames[0] = meanMeasurementNames[0]; for (int m = 1; m < meanMeasurementNames.length; m++) { stdMeasurementNames[m] = "[std] " + meanMeasurementNames[m]; } // wrap into LearningCurves LearningCurve meanLearningCurve = new LearningCurve(meanMeasurementNames[0]); meanLearningCurve.setData( Arrays.asList(meanMeasurementNames), meanParamMeasurements); LearningCurve stdLearningCurve = new LearningCurve(stdMeasurementNames[0]); stdLearningCurve.setData( Arrays.asList(stdMeasurementNames), stdParamMeasurements); // wrap into PreviewCollectionLearningCurveWrapper Preview meanParamValuePreview = new PreviewCollectionLearningCurveWrapper( meanLearningCurve, this.origMultiRunPreviews.taskClass); Preview stdParamValuePreview = new PreviewCollectionLearningCurveWrapper( stdLearningCurve, this.origMultiRunPreviews.taskClass); // store Previews in corresponding PreviewCollections this.meanPreviews.setPreview(paramValue, meanParamValuePreview); this.stdPreviews.setPreview(paramValue, stdParamValuePreview); }
java
private void constructMeanStdPreviewsForParam( int numEntriesPerPreview, int numParamValues, int paramValue) { // calculate mean List<double[]> meanParamMeasurements = calculateMeanMeasurementsForParam( numEntriesPerPreview, numParamValues, paramValue); // calculate standard deviation List<double[]> stdParamMeasurements = calculateStdMeasurementsForParam( numEntriesPerPreview, numParamValues, paramValue, meanParamMeasurements); // get actual measurement names (first four are only additional IDs) String[] meanMeasurementNames = this.origMultiRunPreviews.getMeasurementNames(); meanMeasurementNames = Arrays.copyOfRange( meanMeasurementNames, 4, meanMeasurementNames.length); // Create names for standard deviations. // First name is used for indexing and remains unchanged. For the // remaining names, [std] is prepended to the original name. String[] stdMeasurementNames = new String[meanMeasurementNames.length]; stdMeasurementNames[0] = meanMeasurementNames[0]; for (int m = 1; m < meanMeasurementNames.length; m++) { stdMeasurementNames[m] = "[std] " + meanMeasurementNames[m]; } // wrap into LearningCurves LearningCurve meanLearningCurve = new LearningCurve(meanMeasurementNames[0]); meanLearningCurve.setData( Arrays.asList(meanMeasurementNames), meanParamMeasurements); LearningCurve stdLearningCurve = new LearningCurve(stdMeasurementNames[0]); stdLearningCurve.setData( Arrays.asList(stdMeasurementNames), stdParamMeasurements); // wrap into PreviewCollectionLearningCurveWrapper Preview meanParamValuePreview = new PreviewCollectionLearningCurveWrapper( meanLearningCurve, this.origMultiRunPreviews.taskClass); Preview stdParamValuePreview = new PreviewCollectionLearningCurveWrapper( stdLearningCurve, this.origMultiRunPreviews.taskClass); // store Previews in corresponding PreviewCollections this.meanPreviews.setPreview(paramValue, meanParamValuePreview); this.stdPreviews.setPreview(paramValue, stdParamValuePreview); }
[ "private", "void", "constructMeanStdPreviewsForParam", "(", "int", "numEntriesPerPreview", ",", "int", "numParamValues", ",", "int", "paramValue", ")", "{", "// calculate mean", "List", "<", "double", "[", "]", ">", "meanParamMeasurements", "=", "calculateMeanMeasurementsForParam", "(", "numEntriesPerPreview", ",", "numParamValues", ",", "paramValue", ")", ";", "// calculate standard deviation", "List", "<", "double", "[", "]", ">", "stdParamMeasurements", "=", "calculateStdMeasurementsForParam", "(", "numEntriesPerPreview", ",", "numParamValues", ",", "paramValue", ",", "meanParamMeasurements", ")", ";", "// get actual measurement names (first four are only additional IDs)", "String", "[", "]", "meanMeasurementNames", "=", "this", ".", "origMultiRunPreviews", ".", "getMeasurementNames", "(", ")", ";", "meanMeasurementNames", "=", "Arrays", ".", "copyOfRange", "(", "meanMeasurementNames", ",", "4", ",", "meanMeasurementNames", ".", "length", ")", ";", "// Create names for standard deviations.", "// First name is used for indexing and remains unchanged. For the ", "// remaining names, [std] is prepended to the original name.", "String", "[", "]", "stdMeasurementNames", "=", "new", "String", "[", "meanMeasurementNames", ".", "length", "]", ";", "stdMeasurementNames", "[", "0", "]", "=", "meanMeasurementNames", "[", "0", "]", ";", "for", "(", "int", "m", "=", "1", ";", "m", "<", "meanMeasurementNames", ".", "length", ";", "m", "++", ")", "{", "stdMeasurementNames", "[", "m", "]", "=", "\"[std] \"", "+", "meanMeasurementNames", "[", "m", "]", ";", "}", "// wrap into LearningCurves", "LearningCurve", "meanLearningCurve", "=", "new", "LearningCurve", "(", "meanMeasurementNames", "[", "0", "]", ")", ";", "meanLearningCurve", ".", "setData", "(", "Arrays", ".", "asList", "(", "meanMeasurementNames", ")", ",", "meanParamMeasurements", ")", ";", "LearningCurve", "stdLearningCurve", "=", "new", "LearningCurve", "(", "stdMeasurementNames", "[", "0", "]", ")", ";", "stdLearningCurve", ".", "setData", "(", "Arrays", ".", "asList", "(", "stdMeasurementNames", ")", ",", "stdParamMeasurements", ")", ";", "// wrap into PreviewCollectionLearningCurveWrapper", "Preview", "meanParamValuePreview", "=", "new", "PreviewCollectionLearningCurveWrapper", "(", "meanLearningCurve", ",", "this", ".", "origMultiRunPreviews", ".", "taskClass", ")", ";", "Preview", "stdParamValuePreview", "=", "new", "PreviewCollectionLearningCurveWrapper", "(", "stdLearningCurve", ",", "this", ".", "origMultiRunPreviews", ".", "taskClass", ")", ";", "// store Previews in corresponding PreviewCollections", "this", ".", "meanPreviews", ".", "setPreview", "(", "paramValue", ",", "meanParamValuePreview", ")", ";", "this", ".", "stdPreviews", ".", "setPreview", "(", "paramValue", ",", "stdParamValuePreview", ")", ";", "}" ]
Construct the mean and standard deviation Previews for one specific parameter value. @param numEntriesPerPreview @param numParamValues @param paramValue
[ "Construct", "the", "mean", "and", "standard", "deviation", "Previews", "for", "one", "specific", "parameter", "value", "." ]
395982e5100bfe75a3a4d26115462ce2cc74cbb0
https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/moa/evaluation/preview/MeanPreviewCollection.java#L105-L159
28,825
Waikato/moa
moa/src/main/java/moa/evaluation/preview/MeanPreviewCollection.java
MeanPreviewCollection.calculateMeanMeasurementsForParam
private List<double[]> calculateMeanMeasurementsForParam( int numEntriesPerPreview, int numParamValues, int paramValue) { List<double[]> paramMeasurementsSum = new ArrayList<double[]>(numEntriesPerPreview); List<double[]> meanParamMeasurements = new ArrayList<double[]>(numEntriesPerPreview); int numCompleteFolds = 0; // sum up measurement values for (PreviewCollection<Preview> foldPreview : this.origMultiRunPreviews.subPreviews) { // check if there is a preview for each parameter value if (foldPreview.getPreviews().size() == numParamValues) { numCompleteFolds++; Preview foldParamPreview = foldPreview.getPreviews().get(paramValue); // add this Preview's measurements to the overall sum this.addPreviewMeasurementsToSum( paramMeasurementsSum, foldParamPreview, numEntriesPerPreview); } } // divide sum by number of folds for (int entryIdx = 0; entryIdx < numEntriesPerPreview; entryIdx++) { double[] sumEntry = paramMeasurementsSum.get(entryIdx); double[] meanEntry = new double[sumEntry.length]; // first measurement is used for indexing -> simply copy meanEntry[0] = sumEntry[0]; // calculate mean for remaining measurements for (int m = 1; m < sumEntry.length; m++) { meanEntry[m] = sumEntry[m] / numCompleteFolds; } meanParamMeasurements.add(meanEntry); } return meanParamMeasurements; }
java
private List<double[]> calculateMeanMeasurementsForParam( int numEntriesPerPreview, int numParamValues, int paramValue) { List<double[]> paramMeasurementsSum = new ArrayList<double[]>(numEntriesPerPreview); List<double[]> meanParamMeasurements = new ArrayList<double[]>(numEntriesPerPreview); int numCompleteFolds = 0; // sum up measurement values for (PreviewCollection<Preview> foldPreview : this.origMultiRunPreviews.subPreviews) { // check if there is a preview for each parameter value if (foldPreview.getPreviews().size() == numParamValues) { numCompleteFolds++; Preview foldParamPreview = foldPreview.getPreviews().get(paramValue); // add this Preview's measurements to the overall sum this.addPreviewMeasurementsToSum( paramMeasurementsSum, foldParamPreview, numEntriesPerPreview); } } // divide sum by number of folds for (int entryIdx = 0; entryIdx < numEntriesPerPreview; entryIdx++) { double[] sumEntry = paramMeasurementsSum.get(entryIdx); double[] meanEntry = new double[sumEntry.length]; // first measurement is used for indexing -> simply copy meanEntry[0] = sumEntry[0]; // calculate mean for remaining measurements for (int m = 1; m < sumEntry.length; m++) { meanEntry[m] = sumEntry[m] / numCompleteFolds; } meanParamMeasurements.add(meanEntry); } return meanParamMeasurements; }
[ "private", "List", "<", "double", "[", "]", ">", "calculateMeanMeasurementsForParam", "(", "int", "numEntriesPerPreview", ",", "int", "numParamValues", ",", "int", "paramValue", ")", "{", "List", "<", "double", "[", "]", ">", "paramMeasurementsSum", "=", "new", "ArrayList", "<", "double", "[", "]", ">", "(", "numEntriesPerPreview", ")", ";", "List", "<", "double", "[", "]", ">", "meanParamMeasurements", "=", "new", "ArrayList", "<", "double", "[", "]", ">", "(", "numEntriesPerPreview", ")", ";", "int", "numCompleteFolds", "=", "0", ";", "// sum up measurement values", "for", "(", "PreviewCollection", "<", "Preview", ">", "foldPreview", ":", "this", ".", "origMultiRunPreviews", ".", "subPreviews", ")", "{", "// check if there is a preview for each parameter value", "if", "(", "foldPreview", ".", "getPreviews", "(", ")", ".", "size", "(", ")", "==", "numParamValues", ")", "{", "numCompleteFolds", "++", ";", "Preview", "foldParamPreview", "=", "foldPreview", ".", "getPreviews", "(", ")", ".", "get", "(", "paramValue", ")", ";", "// add this Preview's measurements to the overall sum", "this", ".", "addPreviewMeasurementsToSum", "(", "paramMeasurementsSum", ",", "foldParamPreview", ",", "numEntriesPerPreview", ")", ";", "}", "}", "// divide sum by number of folds", "for", "(", "int", "entryIdx", "=", "0", ";", "entryIdx", "<", "numEntriesPerPreview", ";", "entryIdx", "++", ")", "{", "double", "[", "]", "sumEntry", "=", "paramMeasurementsSum", ".", "get", "(", "entryIdx", ")", ";", "double", "[", "]", "meanEntry", "=", "new", "double", "[", "sumEntry", ".", "length", "]", ";", "// first measurement is used for indexing -> simply copy", "meanEntry", "[", "0", "]", "=", "sumEntry", "[", "0", "]", ";", "// calculate mean for remaining measurements", "for", "(", "int", "m", "=", "1", ";", "m", "<", "sumEntry", ".", "length", ";", "m", "++", ")", "{", "meanEntry", "[", "m", "]", "=", "sumEntry", "[", "m", "]", "/", "numCompleteFolds", ";", "}", "meanParamMeasurements", ".", "add", "(", "meanEntry", ")", ";", "}", "return", "meanParamMeasurements", ";", "}" ]
Calculate the mean measurements for the given parameter value. @param numEntriesPerPreview @param numParamValues @param paramValue @return List of mean measurement arrays
[ "Calculate", "the", "mean", "measurements", "for", "the", "given", "parameter", "value", "." ]
395982e5100bfe75a3a4d26115462ce2cc74cbb0
https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/moa/evaluation/preview/MeanPreviewCollection.java#L169-L217
28,826
Waikato/moa
moa/src/main/java/moa/evaluation/preview/MeanPreviewCollection.java
MeanPreviewCollection.calculateStdMeasurementsForParam
private List<double[]> calculateStdMeasurementsForParam( int numEntriesPerPreview, int numParamValues, int paramValue, List<double[]> meanParamMeasurements) { List<double[]> paramMeasurementsSquaredDiffSum = new ArrayList<double[]>(numEntriesPerPreview); List<double[]> paramMeasurementsStd = new ArrayList<double[]>(numEntriesPerPreview); int numCompleteFolds = 0; // sum up squared differences between measurements and mean values for (PreviewCollection<Preview> foldPreview : this.origMultiRunPreviews.subPreviews) { // check if there is a preview for each parameter value if (foldPreview.getPreviews().size() == numParamValues) { numCompleteFolds++; Preview foldParamPreview = foldPreview.getPreviews().get(paramValue); // add this Preview's standardDeviations to the overall sum this.addPreviewMeasurementSquaredDiffsToSum( meanParamMeasurements, paramMeasurementsSquaredDiffSum, foldParamPreview, numEntriesPerPreview); } } // divide sum by number of folds and take square root for (int entryIdx = 0; entryIdx < numEntriesPerPreview; entryIdx++) { double[] sumEntry = paramMeasurementsSquaredDiffSum.get(entryIdx); double[] stdEntry = new double[sumEntry.length]; // first measurement is used for indexing -> simply copy stdEntry[0] = sumEntry[0]; // calculate standard deviation for remaining measurements for (int m = 1; m < sumEntry.length; m++) { if (numCompleteFolds > 1) { stdEntry[m] = Math.sqrt(sumEntry[m]/(numCompleteFolds-1)); } else { stdEntry[m] = Math.sqrt(sumEntry[m]); } } paramMeasurementsStd.add(stdEntry); } return paramMeasurementsStd; }
java
private List<double[]> calculateStdMeasurementsForParam( int numEntriesPerPreview, int numParamValues, int paramValue, List<double[]> meanParamMeasurements) { List<double[]> paramMeasurementsSquaredDiffSum = new ArrayList<double[]>(numEntriesPerPreview); List<double[]> paramMeasurementsStd = new ArrayList<double[]>(numEntriesPerPreview); int numCompleteFolds = 0; // sum up squared differences between measurements and mean values for (PreviewCollection<Preview> foldPreview : this.origMultiRunPreviews.subPreviews) { // check if there is a preview for each parameter value if (foldPreview.getPreviews().size() == numParamValues) { numCompleteFolds++; Preview foldParamPreview = foldPreview.getPreviews().get(paramValue); // add this Preview's standardDeviations to the overall sum this.addPreviewMeasurementSquaredDiffsToSum( meanParamMeasurements, paramMeasurementsSquaredDiffSum, foldParamPreview, numEntriesPerPreview); } } // divide sum by number of folds and take square root for (int entryIdx = 0; entryIdx < numEntriesPerPreview; entryIdx++) { double[] sumEntry = paramMeasurementsSquaredDiffSum.get(entryIdx); double[] stdEntry = new double[sumEntry.length]; // first measurement is used for indexing -> simply copy stdEntry[0] = sumEntry[0]; // calculate standard deviation for remaining measurements for (int m = 1; m < sumEntry.length; m++) { if (numCompleteFolds > 1) { stdEntry[m] = Math.sqrt(sumEntry[m]/(numCompleteFolds-1)); } else { stdEntry[m] = Math.sqrt(sumEntry[m]); } } paramMeasurementsStd.add(stdEntry); } return paramMeasurementsStd; }
[ "private", "List", "<", "double", "[", "]", ">", "calculateStdMeasurementsForParam", "(", "int", "numEntriesPerPreview", ",", "int", "numParamValues", ",", "int", "paramValue", ",", "List", "<", "double", "[", "]", ">", "meanParamMeasurements", ")", "{", "List", "<", "double", "[", "]", ">", "paramMeasurementsSquaredDiffSum", "=", "new", "ArrayList", "<", "double", "[", "]", ">", "(", "numEntriesPerPreview", ")", ";", "List", "<", "double", "[", "]", ">", "paramMeasurementsStd", "=", "new", "ArrayList", "<", "double", "[", "]", ">", "(", "numEntriesPerPreview", ")", ";", "int", "numCompleteFolds", "=", "0", ";", "// sum up squared differences between measurements and mean values", "for", "(", "PreviewCollection", "<", "Preview", ">", "foldPreview", ":", "this", ".", "origMultiRunPreviews", ".", "subPreviews", ")", "{", "// check if there is a preview for each parameter value", "if", "(", "foldPreview", ".", "getPreviews", "(", ")", ".", "size", "(", ")", "==", "numParamValues", ")", "{", "numCompleteFolds", "++", ";", "Preview", "foldParamPreview", "=", "foldPreview", ".", "getPreviews", "(", ")", ".", "get", "(", "paramValue", ")", ";", "// add this Preview's standardDeviations to the overall sum", "this", ".", "addPreviewMeasurementSquaredDiffsToSum", "(", "meanParamMeasurements", ",", "paramMeasurementsSquaredDiffSum", ",", "foldParamPreview", ",", "numEntriesPerPreview", ")", ";", "}", "}", "// divide sum by number of folds and take square root ", "for", "(", "int", "entryIdx", "=", "0", ";", "entryIdx", "<", "numEntriesPerPreview", ";", "entryIdx", "++", ")", "{", "double", "[", "]", "sumEntry", "=", "paramMeasurementsSquaredDiffSum", ".", "get", "(", "entryIdx", ")", ";", "double", "[", "]", "stdEntry", "=", "new", "double", "[", "sumEntry", ".", "length", "]", ";", "// first measurement is used for indexing -> simply copy", "stdEntry", "[", "0", "]", "=", "sumEntry", "[", "0", "]", ";", "// calculate standard deviation for remaining measurements", "for", "(", "int", "m", "=", "1", ";", "m", "<", "sumEntry", ".", "length", ";", "m", "++", ")", "{", "if", "(", "numCompleteFolds", ">", "1", ")", "{", "stdEntry", "[", "m", "]", "=", "Math", ".", "sqrt", "(", "sumEntry", "[", "m", "]", "/", "(", "numCompleteFolds", "-", "1", ")", ")", ";", "}", "else", "{", "stdEntry", "[", "m", "]", "=", "Math", ".", "sqrt", "(", "sumEntry", "[", "m", "]", ")", ";", "}", "}", "paramMeasurementsStd", ".", "add", "(", "stdEntry", ")", ";", "}", "return", "paramMeasurementsStd", ";", "}" ]
Calculate the standard deviation measurements for the given parameter value. @param numEntriesPerPreview @param numParamValues @param paramValue @return List of standard deviation measurement arrays
[ "Calculate", "the", "standard", "deviation", "measurements", "for", "the", "given", "parameter", "value", "." ]
395982e5100bfe75a3a4d26115462ce2cc74cbb0
https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/moa/evaluation/preview/MeanPreviewCollection.java#L228-L283
28,827
Waikato/moa
moa/src/main/java/moa/evaluation/preview/MeanPreviewCollection.java
MeanPreviewCollection.addPreviewMeasurementsToSum
private void addPreviewMeasurementsToSum( List<double[]> measurementsSum, Preview preview, int numEntriesPerPreview) { List<double[]> previewMeasurements = preview.getData(); // add values for each measurement in each entry for (int entryIdx = 0; entryIdx < numEntriesPerPreview; entryIdx++) { double[] previewEntry = previewMeasurements.get(entryIdx); double[] sumEntry; if (measurementsSum.size() > entryIdx) { sumEntry = measurementsSum.get(entryIdx); } else { // initialize sum entry sumEntry = new double[previewEntry.length]; measurementsSum.add(sumEntry); } // first measurement is used for indexing // -> simply copy from first preview if (sumEntry[0] == 0.0) { sumEntry[0] = previewEntry[0]; } // add measurements of current entry for (int measure = 1; measure < sumEntry.length; measure++) { sumEntry[measure] += previewEntry[measure]; } } }
java
private void addPreviewMeasurementsToSum( List<double[]> measurementsSum, Preview preview, int numEntriesPerPreview) { List<double[]> previewMeasurements = preview.getData(); // add values for each measurement in each entry for (int entryIdx = 0; entryIdx < numEntriesPerPreview; entryIdx++) { double[] previewEntry = previewMeasurements.get(entryIdx); double[] sumEntry; if (measurementsSum.size() > entryIdx) { sumEntry = measurementsSum.get(entryIdx); } else { // initialize sum entry sumEntry = new double[previewEntry.length]; measurementsSum.add(sumEntry); } // first measurement is used for indexing // -> simply copy from first preview if (sumEntry[0] == 0.0) { sumEntry[0] = previewEntry[0]; } // add measurements of current entry for (int measure = 1; measure < sumEntry.length; measure++) { sumEntry[measure] += previewEntry[measure]; } } }
[ "private", "void", "addPreviewMeasurementsToSum", "(", "List", "<", "double", "[", "]", ">", "measurementsSum", ",", "Preview", "preview", ",", "int", "numEntriesPerPreview", ")", "{", "List", "<", "double", "[", "]", ">", "previewMeasurements", "=", "preview", ".", "getData", "(", ")", ";", "// add values for each measurement in each entry", "for", "(", "int", "entryIdx", "=", "0", ";", "entryIdx", "<", "numEntriesPerPreview", ";", "entryIdx", "++", ")", "{", "double", "[", "]", "previewEntry", "=", "previewMeasurements", ".", "get", "(", "entryIdx", ")", ";", "double", "[", "]", "sumEntry", ";", "if", "(", "measurementsSum", ".", "size", "(", ")", ">", "entryIdx", ")", "{", "sumEntry", "=", "measurementsSum", ".", "get", "(", "entryIdx", ")", ";", "}", "else", "{", "// initialize sum entry", "sumEntry", "=", "new", "double", "[", "previewEntry", ".", "length", "]", ";", "measurementsSum", ".", "add", "(", "sumEntry", ")", ";", "}", "// first measurement is used for indexing", "// -> simply copy from first preview", "if", "(", "sumEntry", "[", "0", "]", "==", "0.0", ")", "{", "sumEntry", "[", "0", "]", "=", "previewEntry", "[", "0", "]", ";", "}", "// add measurements of current entry", "for", "(", "int", "measure", "=", "1", ";", "measure", "<", "sumEntry", ".", "length", ";", "measure", "++", ")", "{", "sumEntry", "[", "measure", "]", "+=", "previewEntry", "[", "measure", "]", ";", "}", "}", "}" ]
Add measurements from the given Preview to the overall sum. @param measurementsSum @param preview @param numEntriesPerPreview
[ "Add", "measurements", "from", "the", "given", "Preview", "to", "the", "overall", "sum", "." ]
395982e5100bfe75a3a4d26115462ce2cc74cbb0
https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/moa/evaluation/preview/MeanPreviewCollection.java#L292-L324
28,828
Waikato/moa
moa/src/main/java/moa/evaluation/preview/MeanPreviewCollection.java
MeanPreviewCollection.addPreviewMeasurementSquaredDiffsToSum
private void addPreviewMeasurementSquaredDiffsToSum( List<double[]> meanMeasurements, List<double[]> measurementsSquaredDiffSum, Preview preview, int numEntriesPerPreview) { List<double[]> previewMeasurements = preview.getData(); // add standard deviation for each measurement in each entry for (int entryIdx = 0; entryIdx < numEntriesPerPreview; entryIdx++) { double[] meanEntry = meanMeasurements.get(entryIdx); double[] previewEntry = previewMeasurements.get(entryIdx); double[] squaredDiffSumEntry; if (measurementsSquaredDiffSum.size() > entryIdx) { squaredDiffSumEntry = measurementsSquaredDiffSum.get(entryIdx); } else { // initialize sum entry squaredDiffSumEntry = new double[previewEntry.length]; measurementsSquaredDiffSum.add(squaredDiffSumEntry); } // first measurement is used for indexing // -> simply copy from first preview if (squaredDiffSumEntry[0] == 0.0) { squaredDiffSumEntry[0] = previewEntry[0]; } // add squared differences for current entry for (int m = 1; m < previewEntry.length; m++) { double diff = (meanEntry[m] - previewEntry[m]); double squaredDiff = diff * diff; squaredDiffSumEntry[m] += squaredDiff; } } }
java
private void addPreviewMeasurementSquaredDiffsToSum( List<double[]> meanMeasurements, List<double[]> measurementsSquaredDiffSum, Preview preview, int numEntriesPerPreview) { List<double[]> previewMeasurements = preview.getData(); // add standard deviation for each measurement in each entry for (int entryIdx = 0; entryIdx < numEntriesPerPreview; entryIdx++) { double[] meanEntry = meanMeasurements.get(entryIdx); double[] previewEntry = previewMeasurements.get(entryIdx); double[] squaredDiffSumEntry; if (measurementsSquaredDiffSum.size() > entryIdx) { squaredDiffSumEntry = measurementsSquaredDiffSum.get(entryIdx); } else { // initialize sum entry squaredDiffSumEntry = new double[previewEntry.length]; measurementsSquaredDiffSum.add(squaredDiffSumEntry); } // first measurement is used for indexing // -> simply copy from first preview if (squaredDiffSumEntry[0] == 0.0) { squaredDiffSumEntry[0] = previewEntry[0]; } // add squared differences for current entry for (int m = 1; m < previewEntry.length; m++) { double diff = (meanEntry[m] - previewEntry[m]); double squaredDiff = diff * diff; squaredDiffSumEntry[m] += squaredDiff; } } }
[ "private", "void", "addPreviewMeasurementSquaredDiffsToSum", "(", "List", "<", "double", "[", "]", ">", "meanMeasurements", ",", "List", "<", "double", "[", "]", ">", "measurementsSquaredDiffSum", ",", "Preview", "preview", ",", "int", "numEntriesPerPreview", ")", "{", "List", "<", "double", "[", "]", ">", "previewMeasurements", "=", "preview", ".", "getData", "(", ")", ";", "// add standard deviation for each measurement in each entry", "for", "(", "int", "entryIdx", "=", "0", ";", "entryIdx", "<", "numEntriesPerPreview", ";", "entryIdx", "++", ")", "{", "double", "[", "]", "meanEntry", "=", "meanMeasurements", ".", "get", "(", "entryIdx", ")", ";", "double", "[", "]", "previewEntry", "=", "previewMeasurements", ".", "get", "(", "entryIdx", ")", ";", "double", "[", "]", "squaredDiffSumEntry", ";", "if", "(", "measurementsSquaredDiffSum", ".", "size", "(", ")", ">", "entryIdx", ")", "{", "squaredDiffSumEntry", "=", "measurementsSquaredDiffSum", ".", "get", "(", "entryIdx", ")", ";", "}", "else", "{", "// initialize sum entry", "squaredDiffSumEntry", "=", "new", "double", "[", "previewEntry", ".", "length", "]", ";", "measurementsSquaredDiffSum", ".", "add", "(", "squaredDiffSumEntry", ")", ";", "}", "// first measurement is used for indexing", "// -> simply copy from first preview", "if", "(", "squaredDiffSumEntry", "[", "0", "]", "==", "0.0", ")", "{", "squaredDiffSumEntry", "[", "0", "]", "=", "previewEntry", "[", "0", "]", ";", "}", "// add squared differences for current entry", "for", "(", "int", "m", "=", "1", ";", "m", "<", "previewEntry", ".", "length", ";", "m", "++", ")", "{", "double", "diff", "=", "(", "meanEntry", "[", "m", "]", "-", "previewEntry", "[", "m", "]", ")", ";", "double", "squaredDiff", "=", "diff", "*", "diff", ";", "squaredDiffSumEntry", "[", "m", "]", "+=", "squaredDiff", ";", "}", "}", "}" ]
Add squared deviations from the mean value from the given Preview to the overall sum. @param meanMeasurements @param measurementsSquaredDiffSum @param preview @param numEntriesPerPreview
[ "Add", "squared", "deviations", "from", "the", "mean", "value", "from", "the", "given", "Preview", "to", "the", "overall", "sum", "." ]
395982e5100bfe75a3a4d26115462ce2cc74cbb0
https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/moa/evaluation/preview/MeanPreviewCollection.java#L335-L371
28,829
Waikato/moa
moa/src/main/java/moa/classifiers/bayes/NaiveBayes.java
NaiveBayes.doNaiveBayesPredictionLog
public static double[] doNaiveBayesPredictionLog(Instance inst, DoubleVector observedClassDistribution, AutoExpandVector<AttributeClassObserver> observers, AutoExpandVector<AttributeClassObserver> observers2) { AttributeClassObserver obs; double[] votes = new double[observedClassDistribution.numValues()]; double observedClassSum = observedClassDistribution.sumOfValues(); for (int classIndex = 0; classIndex < votes.length; classIndex++) { votes[classIndex] = Math.log10(observedClassDistribution.getValue(classIndex) / observedClassSum); for (int attIndex = 0; attIndex < inst.numAttributes() - 1; attIndex++) { int instAttIndex = modelAttIndexToInstanceAttIndex(attIndex, inst); if (inst.attribute(instAttIndex).isNominal()) { obs = observers.get(attIndex); } else { obs = observers2.get(attIndex); } if ((obs != null) && !inst.isMissing(instAttIndex)) { votes[classIndex] += Math.log10(obs.probabilityOfAttributeValueGivenClass(inst.value(instAttIndex), classIndex)); } } } return votes; }
java
public static double[] doNaiveBayesPredictionLog(Instance inst, DoubleVector observedClassDistribution, AutoExpandVector<AttributeClassObserver> observers, AutoExpandVector<AttributeClassObserver> observers2) { AttributeClassObserver obs; double[] votes = new double[observedClassDistribution.numValues()]; double observedClassSum = observedClassDistribution.sumOfValues(); for (int classIndex = 0; classIndex < votes.length; classIndex++) { votes[classIndex] = Math.log10(observedClassDistribution.getValue(classIndex) / observedClassSum); for (int attIndex = 0; attIndex < inst.numAttributes() - 1; attIndex++) { int instAttIndex = modelAttIndexToInstanceAttIndex(attIndex, inst); if (inst.attribute(instAttIndex).isNominal()) { obs = observers.get(attIndex); } else { obs = observers2.get(attIndex); } if ((obs != null) && !inst.isMissing(instAttIndex)) { votes[classIndex] += Math.log10(obs.probabilityOfAttributeValueGivenClass(inst.value(instAttIndex), classIndex)); } } } return votes; }
[ "public", "static", "double", "[", "]", "doNaiveBayesPredictionLog", "(", "Instance", "inst", ",", "DoubleVector", "observedClassDistribution", ",", "AutoExpandVector", "<", "AttributeClassObserver", ">", "observers", ",", "AutoExpandVector", "<", "AttributeClassObserver", ">", "observers2", ")", "{", "AttributeClassObserver", "obs", ";", "double", "[", "]", "votes", "=", "new", "double", "[", "observedClassDistribution", ".", "numValues", "(", ")", "]", ";", "double", "observedClassSum", "=", "observedClassDistribution", ".", "sumOfValues", "(", ")", ";", "for", "(", "int", "classIndex", "=", "0", ";", "classIndex", "<", "votes", ".", "length", ";", "classIndex", "++", ")", "{", "votes", "[", "classIndex", "]", "=", "Math", ".", "log10", "(", "observedClassDistribution", ".", "getValue", "(", "classIndex", ")", "/", "observedClassSum", ")", ";", "for", "(", "int", "attIndex", "=", "0", ";", "attIndex", "<", "inst", ".", "numAttributes", "(", ")", "-", "1", ";", "attIndex", "++", ")", "{", "int", "instAttIndex", "=", "modelAttIndexToInstanceAttIndex", "(", "attIndex", ",", "inst", ")", ";", "if", "(", "inst", ".", "attribute", "(", "instAttIndex", ")", ".", "isNominal", "(", ")", ")", "{", "obs", "=", "observers", ".", "get", "(", "attIndex", ")", ";", "}", "else", "{", "obs", "=", "observers2", ".", "get", "(", "attIndex", ")", ";", "}", "if", "(", "(", "obs", "!=", "null", ")", "&&", "!", "inst", ".", "isMissing", "(", "instAttIndex", ")", ")", "{", "votes", "[", "classIndex", "]", "+=", "Math", ".", "log10", "(", "obs", ".", "probabilityOfAttributeValueGivenClass", "(", "inst", ".", "value", "(", "instAttIndex", ")", ",", "classIndex", ")", ")", ";", "}", "}", "}", "return", "votes", ";", "}" ]
Naive Bayes Prediction using log10 for VFDR rules
[ "Naive", "Bayes", "Prediction", "using", "log10", "for", "VFDR", "rules" ]
395982e5100bfe75a3a4d26115462ce2cc74cbb0
https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/moa/classifiers/bayes/NaiveBayes.java#L157-L183
28,830
Waikato/moa
moa/src/main/java/moa/streams/generators/multilabel/MetaMultilabelGenerator.java
MetaMultilabelGenerator.generatePriors
private double[] generatePriors(Random r, int L, double z, boolean skew) { double P[] = new double[L]; for (int i = 0; i < L; i++) { P[i] = r.nextDouble(); //P[i] = 1.0; // @temp } // normalise to z do { double c = Utils.sum(P) / z; for (int i = 0; i < L; i++) { P[i] = Math.min(1.0, P[i] / c); // must be in [0,1] } } while (Utils.sum(P) < z); return P; }
java
private double[] generatePriors(Random r, int L, double z, boolean skew) { double P[] = new double[L]; for (int i = 0; i < L; i++) { P[i] = r.nextDouble(); //P[i] = 1.0; // @temp } // normalise to z do { double c = Utils.sum(P) / z; for (int i = 0; i < L; i++) { P[i] = Math.min(1.0, P[i] / c); // must be in [0,1] } } while (Utils.sum(P) < z); return P; }
[ "private", "double", "[", "]", "generatePriors", "(", "Random", "r", ",", "int", "L", ",", "double", "z", ",", "boolean", "skew", ")", "{", "double", "P", "[", "]", "=", "new", "double", "[", "L", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "L", ";", "i", "++", ")", "{", "P", "[", "i", "]", "=", "r", ".", "nextDouble", "(", ")", ";", "//P[i] = 1.0; // @temp", "}", "// normalise to z", "do", "{", "double", "c", "=", "Utils", ".", "sum", "(", "P", ")", "/", "z", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "L", ";", "i", "++", ")", "{", "P", "[", "i", "]", "=", "Math", ".", "min", "(", "1.0", ",", "P", "[", "i", "]", "/", "c", ")", ";", "// must be in [0,1]", "}", "}", "while", "(", "Utils", ".", "sum", "(", "P", ")", "<", "z", ")", ";", "return", "P", ";", "}" ]
Generate Priors. Generate the label priors. @param L number of labels @param z desired label cardinality @param r random number generator @param skew whether to be very skewed or not (@NOTE not currently used) @return P label prior distribution
[ "Generate", "Priors", ".", "Generate", "the", "label", "priors", "." ]
395982e5100bfe75a3a4d26115462ce2cc74cbb0
https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/moa/streams/generators/multilabel/MetaMultilabelGenerator.java#L180-L194
28,831
Waikato/moa
moa/src/main/java/moa/streams/generators/multilabel/MetaMultilabelGenerator.java
MetaMultilabelGenerator.generateSet
private HashSet generateSet() { int y[] = new int[m_L]; // [0,0,0] int k = samplePMF(priors_norm); // k = 1 // y[k] ~ p(k==1) y[k] = 1; // [0,1,0] ArrayList<Integer> indices = getShuffledListToLWithoutK(m_L, k); for (int j : indices) { //y[j] ~ p(j==1|y) y[j] = (joint(j, y) > m_MetaRandom.nextDouble()) ? 1 : 0; } return vector2set(y); }
java
private HashSet generateSet() { int y[] = new int[m_L]; // [0,0,0] int k = samplePMF(priors_norm); // k = 1 // y[k] ~ p(k==1) y[k] = 1; // [0,1,0] ArrayList<Integer> indices = getShuffledListToLWithoutK(m_L, k); for (int j : indices) { //y[j] ~ p(j==1|y) y[j] = (joint(j, y) > m_MetaRandom.nextDouble()) ? 1 : 0; } return vector2set(y); }
[ "private", "HashSet", "generateSet", "(", ")", "{", "int", "y", "[", "]", "=", "new", "int", "[", "m_L", "]", ";", "// [0,0,0]", "int", "k", "=", "samplePMF", "(", "priors_norm", ")", ";", "// k = 1 // y[k] ~ p(k==1)", "y", "[", "k", "]", "=", "1", ";", "// [0,1,0]", "ArrayList", "<", "Integer", ">", "indices", "=", "getShuffledListToLWithoutK", "(", "m_L", ",", "k", ")", ";", "for", "(", "int", "j", ":", "indices", ")", "{", "//y[j] ~ p(j==1|y)", "y", "[", "j", "]", "=", "(", "joint", "(", "j", ",", "y", ")", ">", "m_MetaRandom", ".", "nextDouble", "(", ")", ")", "?", "1", ":", "0", ";", "}", "return", "vector2set", "(", "y", ")", ";", "}" ]
Generate Set. @return a label set Y
[ "Generate", "Set", "." ]
395982e5100bfe75a3a4d26115462ce2cc74cbb0
https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/moa/streams/generators/multilabel/MetaMultilabelGenerator.java#L236-L247
28,832
Waikato/moa
moa/src/main/java/moa/streams/generators/multilabel/MetaMultilabelGenerator.java
MetaMultilabelGenerator.modifyPriorVector
protected double[] modifyPriorVector(double P[], double u, Random r, boolean skew) { for (int j = 0; j < P.length; j++) { if (r.nextDouble() < u) { P[j] = r.nextDouble(); } } return P; }
java
protected double[] modifyPriorVector(double P[], double u, Random r, boolean skew) { for (int j = 0; j < P.length; j++) { if (r.nextDouble() < u) { P[j] = r.nextDouble(); } } return P; }
[ "protected", "double", "[", "]", "modifyPriorVector", "(", "double", "P", "[", "]", ",", "double", "u", ",", "Random", "r", ",", "boolean", "skew", ")", "{", "for", "(", "int", "j", "=", "0", ";", "j", "<", "P", ".", "length", ";", "j", "++", ")", "{", "if", "(", "r", ".", "nextDouble", "(", ")", "<", "u", ")", "{", "P", "[", "j", "]", "=", "r", ".", "nextDouble", "(", ")", ";", "}", "}", "return", "P", ";", "}" ]
ModifyPriorVector. A certain number of values will be altered. @param P[] the prior distribution @param u the probability of changing P[j] @param r for random numbers @param skew NOTE not currently used @return the modified P
[ "ModifyPriorVector", ".", "A", "certain", "number", "of", "values", "will", "be", "altered", "." ]
395982e5100bfe75a3a4d26115462ce2cc74cbb0
https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/moa/streams/generators/multilabel/MetaMultilabelGenerator.java#L331-L338
28,833
Waikato/moa
moa/src/main/java/moa/streams/generators/multilabel/MetaMultilabelGenerator.java
MetaMultilabelGenerator.getTopCombinations
private HashSet[] getTopCombinations(int n) { final HashMap<HashSet, Integer> count = new HashMap<HashSet, Integer>(); HashMap<HashSet, Integer> isets = new HashMap<HashSet, Integer>(); int N = 100000; double lc = 0.0; for (int i = 0; i < N; i++) { HashSet Y = generateSet(); lc += Y.size(); count.put(Y, count.get(Y) != null ? count.get(Y) + 1 : 1); } lc = lc / N; // @TODO could generate closed frequent itemsets from 'count' List<HashSet> top_set = new ArrayList<HashSet>(count.keySet()); // Sort the sets by their count Collections.sort(top_set, new Comparator<HashSet>() { @Override public int compare(HashSet Y1, HashSet Y2) { return count.get(Y2).compareTo(count.get(Y1)); } }); System.err.println("The most common labelsets (from which we will build the map) will likely be: "); HashSet map_set[] = new HashSet[n]; double weights[] = new double[n]; int idx = 0; for (HashSet Y : top_set) { System.err.println(" " + Y + " : " + (count.get(Y) * 100.0 / N) + "%"); weights[idx++] = count.get(Y); if (idx == weights.length) { break; } } double sum = Utils.sum(weights); System.err.println("Estimated Label Cardinality: " + lc + "\n\n"); System.err.println("Estimated % Unique Labelsets: " + (count.size() * 100.0 / N) + "%\n\n"); // normalize weights[] Utils.normalize(weights); // add sets to the map set, according to their weights for (int i = 0, k = 0; i < top_set.size() && k < map_set.length; i++) { // i'th combination (pre) int num = (int) Math.round(Math.max(weights[i] * map_set.length, 1.0)); // i'th weight for (int j = 0; j < num && k < map_set.length; j++) { map_set[k++] = top_set.get(i); } } // shuffle Collections.shuffle(Arrays.asList(map_set)); // return return map_set; }
java
private HashSet[] getTopCombinations(int n) { final HashMap<HashSet, Integer> count = new HashMap<HashSet, Integer>(); HashMap<HashSet, Integer> isets = new HashMap<HashSet, Integer>(); int N = 100000; double lc = 0.0; for (int i = 0; i < N; i++) { HashSet Y = generateSet(); lc += Y.size(); count.put(Y, count.get(Y) != null ? count.get(Y) + 1 : 1); } lc = lc / N; // @TODO could generate closed frequent itemsets from 'count' List<HashSet> top_set = new ArrayList<HashSet>(count.keySet()); // Sort the sets by their count Collections.sort(top_set, new Comparator<HashSet>() { @Override public int compare(HashSet Y1, HashSet Y2) { return count.get(Y2).compareTo(count.get(Y1)); } }); System.err.println("The most common labelsets (from which we will build the map) will likely be: "); HashSet map_set[] = new HashSet[n]; double weights[] = new double[n]; int idx = 0; for (HashSet Y : top_set) { System.err.println(" " + Y + " : " + (count.get(Y) * 100.0 / N) + "%"); weights[idx++] = count.get(Y); if (idx == weights.length) { break; } } double sum = Utils.sum(weights); System.err.println("Estimated Label Cardinality: " + lc + "\n\n"); System.err.println("Estimated % Unique Labelsets: " + (count.size() * 100.0 / N) + "%\n\n"); // normalize weights[] Utils.normalize(weights); // add sets to the map set, according to their weights for (int i = 0, k = 0; i < top_set.size() && k < map_set.length; i++) { // i'th combination (pre) int num = (int) Math.round(Math.max(weights[i] * map_set.length, 1.0)); // i'th weight for (int j = 0; j < num && k < map_set.length; j++) { map_set[k++] = top_set.get(i); } } // shuffle Collections.shuffle(Arrays.asList(map_set)); // return return map_set; }
[ "private", "HashSet", "[", "]", "getTopCombinations", "(", "int", "n", ")", "{", "final", "HashMap", "<", "HashSet", ",", "Integer", ">", "count", "=", "new", "HashMap", "<", "HashSet", ",", "Integer", ">", "(", ")", ";", "HashMap", "<", "HashSet", ",", "Integer", ">", "isets", "=", "new", "HashMap", "<", "HashSet", ",", "Integer", ">", "(", ")", ";", "int", "N", "=", "100000", ";", "double", "lc", "=", "0.0", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "N", ";", "i", "++", ")", "{", "HashSet", "Y", "=", "generateSet", "(", ")", ";", "lc", "+=", "Y", ".", "size", "(", ")", ";", "count", ".", "put", "(", "Y", ",", "count", ".", "get", "(", "Y", ")", "!=", "null", "?", "count", ".", "get", "(", "Y", ")", "+", "1", ":", "1", ")", ";", "}", "lc", "=", "lc", "/", "N", ";", "// @TODO could generate closed frequent itemsets from 'count'", "List", "<", "HashSet", ">", "top_set", "=", "new", "ArrayList", "<", "HashSet", ">", "(", "count", ".", "keySet", "(", ")", ")", ";", "// Sort the sets by their count", "Collections", ".", "sort", "(", "top_set", ",", "new", "Comparator", "<", "HashSet", ">", "(", ")", "{", "@", "Override", "public", "int", "compare", "(", "HashSet", "Y1", ",", "HashSet", "Y2", ")", "{", "return", "count", ".", "get", "(", "Y2", ")", ".", "compareTo", "(", "count", ".", "get", "(", "Y1", ")", ")", ";", "}", "}", ")", ";", "System", ".", "err", ".", "println", "(", "\"The most common labelsets (from which we will build the map) will likely be: \"", ")", ";", "HashSet", "map_set", "[", "]", "=", "new", "HashSet", "[", "n", "]", ";", "double", "weights", "[", "]", "=", "new", "double", "[", "n", "]", ";", "int", "idx", "=", "0", ";", "for", "(", "HashSet", "Y", ":", "top_set", ")", "{", "System", ".", "err", ".", "println", "(", "\" \"", "+", "Y", "+", "\" : \"", "+", "(", "count", ".", "get", "(", "Y", ")", "*", "100.0", "/", "N", ")", "+", "\"%\"", ")", ";", "weights", "[", "idx", "++", "]", "=", "count", ".", "get", "(", "Y", ")", ";", "if", "(", "idx", "==", "weights", ".", "length", ")", "{", "break", ";", "}", "}", "double", "sum", "=", "Utils", ".", "sum", "(", "weights", ")", ";", "System", ".", "err", ".", "println", "(", "\"Estimated Label Cardinality: \"", "+", "lc", "+", "\"\\n\\n\"", ")", ";", "System", ".", "err", ".", "println", "(", "\"Estimated % Unique Labelsets: \"", "+", "(", "count", ".", "size", "(", ")", "*", "100.0", "/", "N", ")", "+", "\"%\\n\\n\"", ")", ";", "// normalize weights[]", "Utils", ".", "normalize", "(", "weights", ")", ";", "// add sets to the map set, according to their weights", "for", "(", "int", "i", "=", "0", ",", "k", "=", "0", ";", "i", "<", "top_set", ".", "size", "(", ")", "&&", "k", "<", "map_set", ".", "length", ";", "i", "++", ")", "{", "// i'th combination (pre)", "int", "num", "=", "(", "int", ")", "Math", ".", "round", "(", "Math", ".", "max", "(", "weights", "[", "i", "]", "*", "map_set", ".", "length", ",", "1.0", ")", ")", ";", "// i'th weight", "for", "(", "int", "j", "=", "0", ";", "j", "<", "num", "&&", "k", "<", "map_set", ".", "length", ";", "j", "++", ")", "{", "map_set", "[", "k", "++", "]", "=", "top_set", ".", "get", "(", "i", ")", ";", "}", "}", "// shuffle ", "Collections", ".", "shuffle", "(", "Arrays", ".", "asList", "(", "map_set", ")", ")", ";", "// return", "return", "map_set", ";", "}" ]
GetTopCombinations. Calculating the full joint probability distribution is too complex. - sample from the approximate joint many times - record the the n most commonly ocurring Y and their frequencies - create a map based on these frequencies @param n the number of labelsets @return n labelsts
[ "GetTopCombinations", ".", "Calculating", "the", "full", "joint", "probability", "distribution", "is", "too", "complex", ".", "-", "sample", "from", "the", "approximate", "joint", "many", "times", "-", "record", "the", "the", "n", "most", "commonly", "ocurring", "Y", "and", "their", "frequencies", "-", "create", "a", "map", "based", "on", "these", "frequencies" ]
395982e5100bfe75a3a4d26115462ce2cc74cbb0
https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/moa/streams/generators/multilabel/MetaMultilabelGenerator.java#L420-L478
28,834
Waikato/moa
moa/src/main/java/moa/streams/generators/multilabel/MetaMultilabelGenerator.java
MetaMultilabelGenerator.set2vector
private int[] set2vector(HashSet<Integer> Y, int L) { int y[] = new int[L]; for (int j : Y) { y[j] = 1; } return y; }
java
private int[] set2vector(HashSet<Integer> Y, int L) { int y[] = new int[L]; for (int j : Y) { y[j] = 1; } return y; }
[ "private", "int", "[", "]", "set2vector", "(", "HashSet", "<", "Integer", ">", "Y", ",", "int", "L", ")", "{", "int", "y", "[", "]", "=", "new", "int", "[", "L", "]", ";", "for", "(", "int", "j", ":", "Y", ")", "{", "y", "[", "j", "]", "=", "1", ";", "}", "return", "y", ";", "}" ]
convert set Y to an L-length vector y
[ "convert", "set", "Y", "to", "an", "L", "-", "length", "vector", "y" ]
395982e5100bfe75a3a4d26115462ce2cc74cbb0
https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/moa/streams/generators/multilabel/MetaMultilabelGenerator.java#L511-L517
28,835
Waikato/moa
moa/src/main/java/moa/streams/generators/multilabel/MetaMultilabelGenerator.java
MetaMultilabelGenerator.vector2set
private HashSet<Integer> vector2set(int y[]) { HashSet<Integer> Y = new HashSet<Integer>(); for (int j = 0; j < y.length; j++) { if (y[j] > 0) { Y.add(j); } } return Y; }
java
private HashSet<Integer> vector2set(int y[]) { HashSet<Integer> Y = new HashSet<Integer>(); for (int j = 0; j < y.length; j++) { if (y[j] > 0) { Y.add(j); } } return Y; }
[ "private", "HashSet", "<", "Integer", ">", "vector2set", "(", "int", "y", "[", "]", ")", "{", "HashSet", "<", "Integer", ">", "Y", "=", "new", "HashSet", "<", "Integer", ">", "(", ")", ";", "for", "(", "int", "j", "=", "0", ";", "j", "<", "y", ".", "length", ";", "j", "++", ")", "{", "if", "(", "y", "[", "j", "]", ">", "0", ")", "{", "Y", ".", "add", "(", "j", ")", ";", "}", "}", "return", "Y", ";", "}" ]
convert L-length vector y to set Y
[ "convert", "L", "-", "length", "vector", "y", "to", "set", "Y" ]
395982e5100bfe75a3a4d26115462ce2cc74cbb0
https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/moa/streams/generators/multilabel/MetaMultilabelGenerator.java#L520-L528
28,836
Waikato/moa
moa/src/main/java/com/github/javacliparser/JavaCLIParser.java
JavaCLIParser.discoverOptionsViaReflection
public Option[] discoverOptionsViaReflection() { //Class<? extends AbstractOptionHandler> c = this.getClass(); Class c = this.handler.getClass(); Field[] fields = c.getFields(); List<Option> optList = new LinkedList<Option>(); for (Field field : fields) { String fName = field.getName(); Class<?> fType = field.getType(); if (fType.getName().endsWith("Option")) { if (Option.class.isAssignableFrom(fType)) { Option oVal = null; try { field.setAccessible(true); oVal = (Option) field.get(this.handler); } catch (IllegalAccessException ignored) { // cannot access this field } if (oVal != null) { optList.add(oVal); } } } } return optList.toArray(new Option[optList.size()]); }
java
public Option[] discoverOptionsViaReflection() { //Class<? extends AbstractOptionHandler> c = this.getClass(); Class c = this.handler.getClass(); Field[] fields = c.getFields(); List<Option> optList = new LinkedList<Option>(); for (Field field : fields) { String fName = field.getName(); Class<?> fType = field.getType(); if (fType.getName().endsWith("Option")) { if (Option.class.isAssignableFrom(fType)) { Option oVal = null; try { field.setAccessible(true); oVal = (Option) field.get(this.handler); } catch (IllegalAccessException ignored) { // cannot access this field } if (oVal != null) { optList.add(oVal); } } } } return optList.toArray(new Option[optList.size()]); }
[ "public", "Option", "[", "]", "discoverOptionsViaReflection", "(", ")", "{", "//Class<? extends AbstractOptionHandler> c = this.getClass();", "Class", "c", "=", "this", ".", "handler", ".", "getClass", "(", ")", ";", "Field", "[", "]", "fields", "=", "c", ".", "getFields", "(", ")", ";", "List", "<", "Option", ">", "optList", "=", "new", "LinkedList", "<", "Option", ">", "(", ")", ";", "for", "(", "Field", "field", ":", "fields", ")", "{", "String", "fName", "=", "field", ".", "getName", "(", ")", ";", "Class", "<", "?", ">", "fType", "=", "field", ".", "getType", "(", ")", ";", "if", "(", "fType", ".", "getName", "(", ")", ".", "endsWith", "(", "\"Option\"", ")", ")", "{", "if", "(", "Option", ".", "class", ".", "isAssignableFrom", "(", "fType", ")", ")", "{", "Option", "oVal", "=", "null", ";", "try", "{", "field", ".", "setAccessible", "(", "true", ")", ";", "oVal", "=", "(", "Option", ")", "field", ".", "get", "(", "this", ".", "handler", ")", ";", "}", "catch", "(", "IllegalAccessException", "ignored", ")", "{", "// cannot access this field", "}", "if", "(", "oVal", "!=", "null", ")", "{", "optList", ".", "add", "(", "oVal", ")", ";", "}", "}", "}", "}", "return", "optList", ".", "toArray", "(", "new", "Option", "[", "optList", ".", "size", "(", ")", "]", ")", ";", "}" ]
Gets the options of this class via reflection. @return an array of options
[ "Gets", "the", "options", "of", "this", "class", "via", "reflection", "." ]
395982e5100bfe75a3a4d26115462ce2cc74cbb0
https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/com/github/javacliparser/JavaCLIParser.java#L70-L94
28,837
Waikato/moa
moa/src/main/java/moa/classifiers/lazy/neighboursearch/LinearNNSearch.java
LinearNNSearch.kNearestNeighbours
public Instances kNearestNeighbours(Instance target, int kNN) throws Exception { //debug boolean print=false; MyHeap heap = new MyHeap(kNN); double distance; int firstkNN=0; for(int i=0; i<m_Instances.numInstances(); i++) { if(target == m_Instances.instance(i)) //for hold-one-out cross-validation continue; if(firstkNN<kNN) { if(print) System.out.println("K(a): "+(heap.size()+heap.noOfKthNearest())); distance = m_DistanceFunction.distance(target, m_Instances.instance(i), Double.POSITIVE_INFINITY); if(distance == 0.0 && m_SkipIdentical) if(i<m_Instances.numInstances()-1) continue; else heap.put(i, distance); heap.put(i, distance); firstkNN++; } else { MyHeapElement temp = heap.peek(); if(print) System.out.println("K(b): "+(heap.size()+heap.noOfKthNearest())); distance = m_DistanceFunction.distance(target, m_Instances.instance(i), temp.distance); if(distance == 0.0 && m_SkipIdentical) continue; if(distance < temp.distance) { heap.putBySubstitute(i, distance); } else if(distance == temp.distance) { heap.putKthNearest(i, distance); } } } Instances neighbours = new Instances(m_Instances, (heap.size()+heap.noOfKthNearest())); m_Distances = new double[heap.size()+heap.noOfKthNearest()]; int [] indices = new int[heap.size()+heap.noOfKthNearest()]; int i=1; MyHeapElement h; while(heap.noOfKthNearest()>0) { h = heap.getKthNearest(); indices[indices.length-i] = h.index; m_Distances[indices.length-i] = h.distance; i++; } while(heap.size()>0) { h = heap.get(); indices[indices.length-i] = h.index; m_Distances[indices.length-i] = h.distance; i++; } m_DistanceFunction.postProcessDistances(m_Distances); for(int k=0; k<indices.length; k++) { neighbours.add(m_Instances.instance(indices[k])); } return neighbours; }
java
public Instances kNearestNeighbours(Instance target, int kNN) throws Exception { //debug boolean print=false; MyHeap heap = new MyHeap(kNN); double distance; int firstkNN=0; for(int i=0; i<m_Instances.numInstances(); i++) { if(target == m_Instances.instance(i)) //for hold-one-out cross-validation continue; if(firstkNN<kNN) { if(print) System.out.println("K(a): "+(heap.size()+heap.noOfKthNearest())); distance = m_DistanceFunction.distance(target, m_Instances.instance(i), Double.POSITIVE_INFINITY); if(distance == 0.0 && m_SkipIdentical) if(i<m_Instances.numInstances()-1) continue; else heap.put(i, distance); heap.put(i, distance); firstkNN++; } else { MyHeapElement temp = heap.peek(); if(print) System.out.println("K(b): "+(heap.size()+heap.noOfKthNearest())); distance = m_DistanceFunction.distance(target, m_Instances.instance(i), temp.distance); if(distance == 0.0 && m_SkipIdentical) continue; if(distance < temp.distance) { heap.putBySubstitute(i, distance); } else if(distance == temp.distance) { heap.putKthNearest(i, distance); } } } Instances neighbours = new Instances(m_Instances, (heap.size()+heap.noOfKthNearest())); m_Distances = new double[heap.size()+heap.noOfKthNearest()]; int [] indices = new int[heap.size()+heap.noOfKthNearest()]; int i=1; MyHeapElement h; while(heap.noOfKthNearest()>0) { h = heap.getKthNearest(); indices[indices.length-i] = h.index; m_Distances[indices.length-i] = h.distance; i++; } while(heap.size()>0) { h = heap.get(); indices[indices.length-i] = h.index; m_Distances[indices.length-i] = h.distance; i++; } m_DistanceFunction.postProcessDistances(m_Distances); for(int k=0; k<indices.length; k++) { neighbours.add(m_Instances.instance(indices[k])); } return neighbours; }
[ "public", "Instances", "kNearestNeighbours", "(", "Instance", "target", ",", "int", "kNN", ")", "throws", "Exception", "{", "//debug", "boolean", "print", "=", "false", ";", "MyHeap", "heap", "=", "new", "MyHeap", "(", "kNN", ")", ";", "double", "distance", ";", "int", "firstkNN", "=", "0", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "m_Instances", ".", "numInstances", "(", ")", ";", "i", "++", ")", "{", "if", "(", "target", "==", "m_Instances", ".", "instance", "(", "i", ")", ")", "//for hold-one-out cross-validation", "continue", ";", "if", "(", "firstkNN", "<", "kNN", ")", "{", "if", "(", "print", ")", "System", ".", "out", ".", "println", "(", "\"K(a): \"", "+", "(", "heap", ".", "size", "(", ")", "+", "heap", ".", "noOfKthNearest", "(", ")", ")", ")", ";", "distance", "=", "m_DistanceFunction", ".", "distance", "(", "target", ",", "m_Instances", ".", "instance", "(", "i", ")", ",", "Double", ".", "POSITIVE_INFINITY", ")", ";", "if", "(", "distance", "==", "0.0", "&&", "m_SkipIdentical", ")", "if", "(", "i", "<", "m_Instances", ".", "numInstances", "(", ")", "-", "1", ")", "continue", ";", "else", "heap", ".", "put", "(", "i", ",", "distance", ")", ";", "heap", ".", "put", "(", "i", ",", "distance", ")", ";", "firstkNN", "++", ";", "}", "else", "{", "MyHeapElement", "temp", "=", "heap", ".", "peek", "(", ")", ";", "if", "(", "print", ")", "System", ".", "out", ".", "println", "(", "\"K(b): \"", "+", "(", "heap", ".", "size", "(", ")", "+", "heap", ".", "noOfKthNearest", "(", ")", ")", ")", ";", "distance", "=", "m_DistanceFunction", ".", "distance", "(", "target", ",", "m_Instances", ".", "instance", "(", "i", ")", ",", "temp", ".", "distance", ")", ";", "if", "(", "distance", "==", "0.0", "&&", "m_SkipIdentical", ")", "continue", ";", "if", "(", "distance", "<", "temp", ".", "distance", ")", "{", "heap", ".", "putBySubstitute", "(", "i", ",", "distance", ")", ";", "}", "else", "if", "(", "distance", "==", "temp", ".", "distance", ")", "{", "heap", ".", "putKthNearest", "(", "i", ",", "distance", ")", ";", "}", "}", "}", "Instances", "neighbours", "=", "new", "Instances", "(", "m_Instances", ",", "(", "heap", ".", "size", "(", ")", "+", "heap", ".", "noOfKthNearest", "(", ")", ")", ")", ";", "m_Distances", "=", "new", "double", "[", "heap", ".", "size", "(", ")", "+", "heap", ".", "noOfKthNearest", "(", ")", "]", ";", "int", "[", "]", "indices", "=", "new", "int", "[", "heap", ".", "size", "(", ")", "+", "heap", ".", "noOfKthNearest", "(", ")", "]", ";", "int", "i", "=", "1", ";", "MyHeapElement", "h", ";", "while", "(", "heap", ".", "noOfKthNearest", "(", ")", ">", "0", ")", "{", "h", "=", "heap", ".", "getKthNearest", "(", ")", ";", "indices", "[", "indices", ".", "length", "-", "i", "]", "=", "h", ".", "index", ";", "m_Distances", "[", "indices", ".", "length", "-", "i", "]", "=", "h", ".", "distance", ";", "i", "++", ";", "}", "while", "(", "heap", ".", "size", "(", ")", ">", "0", ")", "{", "h", "=", "heap", ".", "get", "(", ")", ";", "indices", "[", "indices", ".", "length", "-", "i", "]", "=", "h", ".", "index", ";", "m_Distances", "[", "indices", ".", "length", "-", "i", "]", "=", "h", ".", "distance", ";", "i", "++", ";", "}", "m_DistanceFunction", ".", "postProcessDistances", "(", "m_Distances", ")", ";", "for", "(", "int", "k", "=", "0", ";", "k", "<", "indices", ".", "length", ";", "k", "++", ")", "{", "neighbours", ".", "add", "(", "m_Instances", ".", "instance", "(", "indices", "[", "k", "]", ")", ")", ";", "}", "return", "neighbours", ";", "}" ]
Returns k nearest instances in the current neighbourhood to the supplied instance. @param target The instance to find the k nearest neighbours for. @param kNN The number of nearest neighbours to find. @return the k nearest neighbors @throws Exception if the neighbours could not be found.
[ "Returns", "k", "nearest", "instances", "in", "the", "current", "neighbourhood", "to", "the", "supplied", "instance", "." ]
395982e5100bfe75a3a4d26115462ce2cc74cbb0
https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/moa/classifiers/lazy/neighboursearch/LinearNNSearch.java#L146-L209
28,838
Waikato/moa
moa/src/main/java/moa/classifiers/lazy/neighboursearch/LinearNNSearch.java
LinearNNSearch.update
public void update(Instance ins) throws Exception { if(m_Instances==null) throw new Exception("No instances supplied yet. Cannot update without"+ "supplying a set of instances first."); m_DistanceFunction.update(ins); }
java
public void update(Instance ins) throws Exception { if(m_Instances==null) throw new Exception("No instances supplied yet. Cannot update without"+ "supplying a set of instances first."); m_DistanceFunction.update(ins); }
[ "public", "void", "update", "(", "Instance", "ins", ")", "throws", "Exception", "{", "if", "(", "m_Instances", "==", "null", ")", "throw", "new", "Exception", "(", "\"No instances supplied yet. Cannot update without\"", "+", "\"supplying a set of instances first.\"", ")", ";", "m_DistanceFunction", ".", "update", "(", "ins", ")", ";", "}" ]
Updates the LinearNNSearch to cater for the new added instance. This implementation only updates the ranges of the DistanceFunction class, since our set of instances is passed by reference and should already have the newly added instance. @param ins The instance to add. Usually this is the instance that is added to our neighbourhood i.e. the training instances. @throws Exception if the given instances are null
[ "Updates", "the", "LinearNNSearch", "to", "cater", "for", "the", "new", "added", "instance", ".", "This", "implementation", "only", "updates", "the", "ranges", "of", "the", "DistanceFunction", "class", "since", "our", "set", "of", "instances", "is", "passed", "by", "reference", "and", "should", "already", "have", "the", "newly", "added", "instance", "." ]
395982e5100bfe75a3a4d26115462ce2cc74cbb0
https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/moa/classifiers/lazy/neighboursearch/LinearNNSearch.java#L259-L264
28,839
Waikato/moa
moa/src/main/java/moa/classifiers/lazy/neighboursearch/LinearNNSearch.java
LinearNNSearch.addInstanceInfo
public void addInstanceInfo(Instance ins) { if(m_Instances!=null) try{ update(ins); } catch(Exception ex) { ex.printStackTrace(); } }
java
public void addInstanceInfo(Instance ins) { if(m_Instances!=null) try{ update(ins); } catch(Exception ex) { ex.printStackTrace(); } }
[ "public", "void", "addInstanceInfo", "(", "Instance", "ins", ")", "{", "if", "(", "m_Instances", "!=", "null", ")", "try", "{", "update", "(", "ins", ")", ";", "}", "catch", "(", "Exception", "ex", ")", "{", "ex", ".", "printStackTrace", "(", ")", ";", "}", "}" ]
Adds the given instance info. This implementation updates the range datastructures of the DistanceFunction class. @param ins The instance to add the information of. Usually this is the test instance supplied to update the range of attributes in the distance function.
[ "Adds", "the", "given", "instance", "info", ".", "This", "implementation", "updates", "the", "range", "datastructures", "of", "the", "DistanceFunction", "class", "." ]
395982e5100bfe75a3a4d26115462ce2cc74cbb0
https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/moa/classifiers/lazy/neighboursearch/LinearNNSearch.java#L274-L278
28,840
Waikato/moa
moa/src/main/java/com/github/javacliparser/AbstractOption.java
AbstractOption.nameIsLegal
public static boolean nameIsLegal(String optionName) { for (char illegalChar : illegalNameCharacters) { if (optionName.indexOf(illegalChar) >= 0) { return false; } } return true; }
java
public static boolean nameIsLegal(String optionName) { for (char illegalChar : illegalNameCharacters) { if (optionName.indexOf(illegalChar) >= 0) { return false; } } return true; }
[ "public", "static", "boolean", "nameIsLegal", "(", "String", "optionName", ")", "{", "for", "(", "char", "illegalChar", ":", "illegalNameCharacters", ")", "{", "if", "(", "optionName", ".", "indexOf", "(", "illegalChar", ")", ">=", "0", ")", "{", "return", "false", ";", "}", "}", "return", "true", ";", "}" ]
Gets whether the name is valid or not. @param optionName the name of the option @return true if the name that not contain any illegal character
[ "Gets", "whether", "the", "name", "is", "valid", "or", "not", "." ]
395982e5100bfe75a3a4d26115462ce2cc74cbb0
https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/com/github/javacliparser/AbstractOption.java#L47-L54
28,841
Waikato/moa
moa/src/main/java/moa/gui/visualization/ProcessGraphCanvas.java
ProcessGraphCanvas.setGraph
public void setGraph(MeasureCollection[] measures, MeasureCollection[] measureStds, int[] processFrequencies, int min_processFrequency, Color[] colors) { this.measures = measures; this.processFrequencies = processFrequencies; this.min_processFrequency = min_processFrequency; ((ProcessGraphAxes) this.axesPanel).setProcessFrequency(min_processFrequency); ((GraphMultiCurve) this.plotPanel).setProcessFrequency(min_processFrequency); ((GraphMultiCurve) this.plotPanel).setGraph(measures, measureStds, processFrequencies, colors); updateCanvas(false); }
java
public void setGraph(MeasureCollection[] measures, MeasureCollection[] measureStds, int[] processFrequencies, int min_processFrequency, Color[] colors) { this.measures = measures; this.processFrequencies = processFrequencies; this.min_processFrequency = min_processFrequency; ((ProcessGraphAxes) this.axesPanel).setProcessFrequency(min_processFrequency); ((GraphMultiCurve) this.plotPanel).setProcessFrequency(min_processFrequency); ((GraphMultiCurve) this.plotPanel).setGraph(measures, measureStds, processFrequencies, colors); updateCanvas(false); }
[ "public", "void", "setGraph", "(", "MeasureCollection", "[", "]", "measures", ",", "MeasureCollection", "[", "]", "measureStds", ",", "int", "[", "]", "processFrequencies", ",", "int", "min_processFrequency", ",", "Color", "[", "]", "colors", ")", "{", "this", ".", "measures", "=", "measures", ";", "this", ".", "processFrequencies", "=", "processFrequencies", ";", "this", ".", "min_processFrequency", "=", "min_processFrequency", ";", "(", "(", "ProcessGraphAxes", ")", "this", ".", "axesPanel", ")", ".", "setProcessFrequency", "(", "min_processFrequency", ")", ";", "(", "(", "GraphMultiCurve", ")", "this", ".", "plotPanel", ")", ".", "setProcessFrequency", "(", "min_processFrequency", ")", ";", "(", "(", "GraphMultiCurve", ")", "this", ".", "plotPanel", ")", ".", "setGraph", "(", "measures", ",", "measureStds", ",", "processFrequencies", ",", "colors", ")", ";", "updateCanvas", "(", "false", ")", ";", "}" ]
Sets the graph containing multiple curves. @param measures information about the curves @param measureStds standard deviation values for the measures @param processFrequencies information about the process frequencies of the curves @param min_processFrequency minimum process frequency @param colors color encodings for the curves
[ "Sets", "the", "graph", "containing", "multiple", "curves", "." ]
395982e5100bfe75a3a4d26115462ce2cc74cbb0
https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/moa/gui/visualization/ProcessGraphCanvas.java#L87-L96
28,842
Waikato/moa
moa/src/main/java/moa/classifiers/lazy/neighboursearch/kdtrees/MidPointOfWidestDimension.java
MidPointOfWidestDimension.splitNode
public void splitNode(KDTreeNode node, int numNodesCreated, double[][] nodeRanges, double[][] universe) throws Exception { correctlyInitialized(); int splitDim = widestDim(nodeRanges, universe); double splitVal = m_EuclideanDistance.getMiddle(nodeRanges[splitDim]); int rightStart = rearrangePoints(m_InstList, node.m_Start, node.m_End, splitDim, splitVal); if (rightStart == node.m_Start || rightStart > node.m_End) { if (rightStart == node.m_Start) throw new Exception("Left child is empty in node " + node.m_NodeNumber + ". Not possible with " + "MidPointofWidestDim splitting method. Please " + "check code."); else throw new Exception("Right child is empty in node " + node.m_NodeNumber + ". Not possible with " + "MidPointofWidestDim splitting method. Please " + "check code."); } node.m_SplitDim = splitDim; node.m_SplitValue = splitVal; node.m_Left = new KDTreeNode(numNodesCreated + 1, node.m_Start, rightStart - 1, m_EuclideanDistance.initializeRanges(m_InstList, node.m_Start, rightStart - 1)); node.m_Right = new KDTreeNode(numNodesCreated + 2, rightStart, node.m_End, m_EuclideanDistance .initializeRanges(m_InstList, rightStart, node.m_End)); }
java
public void splitNode(KDTreeNode node, int numNodesCreated, double[][] nodeRanges, double[][] universe) throws Exception { correctlyInitialized(); int splitDim = widestDim(nodeRanges, universe); double splitVal = m_EuclideanDistance.getMiddle(nodeRanges[splitDim]); int rightStart = rearrangePoints(m_InstList, node.m_Start, node.m_End, splitDim, splitVal); if (rightStart == node.m_Start || rightStart > node.m_End) { if (rightStart == node.m_Start) throw new Exception("Left child is empty in node " + node.m_NodeNumber + ". Not possible with " + "MidPointofWidestDim splitting method. Please " + "check code."); else throw new Exception("Right child is empty in node " + node.m_NodeNumber + ". Not possible with " + "MidPointofWidestDim splitting method. Please " + "check code."); } node.m_SplitDim = splitDim; node.m_SplitValue = splitVal; node.m_Left = new KDTreeNode(numNodesCreated + 1, node.m_Start, rightStart - 1, m_EuclideanDistance.initializeRanges(m_InstList, node.m_Start, rightStart - 1)); node.m_Right = new KDTreeNode(numNodesCreated + 2, rightStart, node.m_End, m_EuclideanDistance .initializeRanges(m_InstList, rightStart, node.m_End)); }
[ "public", "void", "splitNode", "(", "KDTreeNode", "node", ",", "int", "numNodesCreated", ",", "double", "[", "]", "[", "]", "nodeRanges", ",", "double", "[", "]", "[", "]", "universe", ")", "throws", "Exception", "{", "correctlyInitialized", "(", ")", ";", "int", "splitDim", "=", "widestDim", "(", "nodeRanges", ",", "universe", ")", ";", "double", "splitVal", "=", "m_EuclideanDistance", ".", "getMiddle", "(", "nodeRanges", "[", "splitDim", "]", ")", ";", "int", "rightStart", "=", "rearrangePoints", "(", "m_InstList", ",", "node", ".", "m_Start", ",", "node", ".", "m_End", ",", "splitDim", ",", "splitVal", ")", ";", "if", "(", "rightStart", "==", "node", ".", "m_Start", "||", "rightStart", ">", "node", ".", "m_End", ")", "{", "if", "(", "rightStart", "==", "node", ".", "m_Start", ")", "throw", "new", "Exception", "(", "\"Left child is empty in node \"", "+", "node", ".", "m_NodeNumber", "+", "\". Not possible with \"", "+", "\"MidPointofWidestDim splitting method. Please \"", "+", "\"check code.\"", ")", ";", "else", "throw", "new", "Exception", "(", "\"Right child is empty in node \"", "+", "node", ".", "m_NodeNumber", "+", "\". Not possible with \"", "+", "\"MidPointofWidestDim splitting method. Please \"", "+", "\"check code.\"", ")", ";", "}", "node", ".", "m_SplitDim", "=", "splitDim", ";", "node", ".", "m_SplitValue", "=", "splitVal", ";", "node", ".", "m_Left", "=", "new", "KDTreeNode", "(", "numNodesCreated", "+", "1", ",", "node", ".", "m_Start", ",", "rightStart", "-", "1", ",", "m_EuclideanDistance", ".", "initializeRanges", "(", "m_InstList", ",", "node", ".", "m_Start", ",", "rightStart", "-", "1", ")", ")", ";", "node", ".", "m_Right", "=", "new", "KDTreeNode", "(", "numNodesCreated", "+", "2", ",", "rightStart", ",", "node", ".", "m_End", ",", "m_EuclideanDistance", ".", "initializeRanges", "(", "m_InstList", ",", "rightStart", ",", "node", ".", "m_End", ")", ")", ";", "}" ]
Splits a node into two based on the midpoint value of the dimension in which the points have the widest spread. After splitting two new nodes are created and correctly initialised. And, node.left and node.right are set appropriately. @param node The node to split. @param numNodesCreated The number of nodes that so far have been created for the tree, so that the newly created nodes are assigned correct/meaningful node numbers/ids. @param nodeRanges The attributes' range for the points inside the node that is to be split. @param universe The attributes' range for the whole point-space. @throws Exception If there is some problem in splitting the given node.
[ "Splits", "a", "node", "into", "two", "based", "on", "the", "midpoint", "value", "of", "the", "dimension", "in", "which", "the", "points", "have", "the", "widest", "spread", ".", "After", "splitting", "two", "new", "nodes", "are", "created", "and", "correctly", "initialised", ".", "And", "node", ".", "left", "and", "node", ".", "right", "are", "set", "appropriately", "." ]
395982e5100bfe75a3a4d26115462ce2cc74cbb0
https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/moa/classifiers/lazy/neighboursearch/kdtrees/MidPointOfWidestDimension.java#L90-L124
28,843
Waikato/moa
moa/src/main/java/moa/classifiers/meta/ADACC.java
ADACC.computeStabilityIndex
private double computeStabilityIndex(){ int m = (int)Math.floor((this.ensemble.length-MAXPERMANENT)/2); int[][] votes=new int[m][tau_size]; double errors=0; int count=0; Pair[] arr = getHalf(true); for (int i=0;i<m;i++){ for (int j=0;j<tau_size;j++){ votes[i][j]=Utils.maxIndex(this.ensemble[arr[i].index].getVotesForInstance(recentChunk.get(j))); errors+=(votes[i][j]==(int) this.recentChunk.get(j).classValue())?0:1; count++; } } errors = errors/count; double res=0; count=0; for (int i=0;i<m;i++) for (int j=i+1;j<m;j++) if (i!=j){ res+=computeKappa(votes[i],votes[j]); count++; } return res/count-errors; }
java
private double computeStabilityIndex(){ int m = (int)Math.floor((this.ensemble.length-MAXPERMANENT)/2); int[][] votes=new int[m][tau_size]; double errors=0; int count=0; Pair[] arr = getHalf(true); for (int i=0;i<m;i++){ for (int j=0;j<tau_size;j++){ votes[i][j]=Utils.maxIndex(this.ensemble[arr[i].index].getVotesForInstance(recentChunk.get(j))); errors+=(votes[i][j]==(int) this.recentChunk.get(j).classValue())?0:1; count++; } } errors = errors/count; double res=0; count=0; for (int i=0;i<m;i++) for (int j=i+1;j<m;j++) if (i!=j){ res+=computeKappa(votes[i],votes[j]); count++; } return res/count-errors; }
[ "private", "double", "computeStabilityIndex", "(", ")", "{", "int", "m", "=", "(", "int", ")", "Math", ".", "floor", "(", "(", "this", ".", "ensemble", ".", "length", "-", "MAXPERMANENT", ")", "/", "2", ")", ";", "int", "[", "]", "[", "]", "votes", "=", "new", "int", "[", "m", "]", "[", "tau_size", "]", ";", "double", "errors", "=", "0", ";", "int", "count", "=", "0", ";", "Pair", "[", "]", "arr", "=", "getHalf", "(", "true", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "m", ";", "i", "++", ")", "{", "for", "(", "int", "j", "=", "0", ";", "j", "<", "tau_size", ";", "j", "++", ")", "{", "votes", "[", "i", "]", "[", "j", "]", "=", "Utils", ".", "maxIndex", "(", "this", ".", "ensemble", "[", "arr", "[", "i", "]", ".", "index", "]", ".", "getVotesForInstance", "(", "recentChunk", ".", "get", "(", "j", ")", ")", ")", ";", "errors", "+=", "(", "votes", "[", "i", "]", "[", "j", "]", "==", "(", "int", ")", "this", ".", "recentChunk", ".", "get", "(", "j", ")", ".", "classValue", "(", ")", ")", "?", "0", ":", "1", ";", "count", "++", ";", "}", "}", "errors", "=", "errors", "/", "count", ";", "double", "res", "=", "0", ";", "count", "=", "0", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "m", ";", "i", "++", ")", "for", "(", "int", "j", "=", "i", "+", "1", ";", "j", "<", "m", ";", "j", "++", ")", "if", "(", "i", "!=", "j", ")", "{", "res", "+=", "computeKappa", "(", "votes", "[", "i", "]", ",", "votes", "[", "j", "]", ")", ";", "count", "++", ";", "}", "return", "res", "/", "count", "-", "errors", ";", "}" ]
Returns the stability index of the adaptive ensemble of classifiers. The ensemble is considered stable here if its diversity level and error rates are low. @return the stability measure value
[ "Returns", "the", "stability", "index", "of", "the", "adaptive", "ensemble", "of", "classifiers", ".", "The", "ensemble", "is", "considered", "stable", "here", "if", "its", "diversity", "level", "and", "error", "rates", "are", "low", "." ]
395982e5100bfe75a3a4d26115462ce2cc74cbb0
https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/moa/classifiers/meta/ADACC.java#L215-L243
28,844
Waikato/moa
moa/src/main/java/moa/classifiers/meta/ADACC.java
ADACC.getBestAdaptiveClassifier
private Classifier getBestAdaptiveClassifier(){ //take a copy of the ensemble weights (excluding snapshots) Pair[] newEnsembleWeights = new Pair[ensembleWeights.length-MAXPERMANENT]; for (int i = 0 ; i < newEnsembleWeights.length; i++) newEnsembleWeights[i]=ensembleWeights[i]; //sort the weight values Arrays.sort(newEnsembleWeights,Collections.reverseOrder()); return this.ensemble[newEnsembleWeights[0].index].copy(); }
java
private Classifier getBestAdaptiveClassifier(){ //take a copy of the ensemble weights (excluding snapshots) Pair[] newEnsembleWeights = new Pair[ensembleWeights.length-MAXPERMANENT]; for (int i = 0 ; i < newEnsembleWeights.length; i++) newEnsembleWeights[i]=ensembleWeights[i]; //sort the weight values Arrays.sort(newEnsembleWeights,Collections.reverseOrder()); return this.ensemble[newEnsembleWeights[0].index].copy(); }
[ "private", "Classifier", "getBestAdaptiveClassifier", "(", ")", "{", "//take a copy of the ensemble weights (excluding snapshots)", "Pair", "[", "]", "newEnsembleWeights", "=", "new", "Pair", "[", "ensembleWeights", ".", "length", "-", "MAXPERMANENT", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "newEnsembleWeights", ".", "length", ";", "i", "++", ")", "newEnsembleWeights", "[", "i", "]", "=", "ensembleWeights", "[", "i", "]", ";", "//sort the weight values\t", "Arrays", ".", "sort", "(", "newEnsembleWeights", ",", "Collections", ".", "reverseOrder", "(", ")", ")", ";", "return", "this", ".", "ensemble", "[", "newEnsembleWeights", "[", "0", "]", ".", "index", "]", ".", "copy", "(", ")", ";", "}" ]
Returns the adaptive classifier with the highest weight @return the best adaptive classifier
[ "Returns", "the", "adaptive", "classifier", "with", "the", "highest", "weight" ]
395982e5100bfe75a3a4d26115462ce2cc74cbb0
https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/moa/classifiers/meta/ADACC.java#L249-L260
28,845
Waikato/moa
moa/src/main/java/moa/gui/visualization/AbstractGraphCanvas.java
AbstractGraphCanvas.scaleYResolution
public void scaleYResolution(double factor) { this.y_resolution = Math.max(1.0, this.y_resolution * factor); updateYResolution(); updateUpperYValue(); updateCanvas(true); }
java
public void scaleYResolution(double factor) { this.y_resolution = Math.max(1.0, this.y_resolution * factor); updateYResolution(); updateUpperYValue(); updateCanvas(true); }
[ "public", "void", "scaleYResolution", "(", "double", "factor", ")", "{", "this", ".", "y_resolution", "=", "Math", ".", "max", "(", "1.0", ",", "this", ".", "y_resolution", "*", "factor", ")", ";", "updateYResolution", "(", ")", ";", "updateUpperYValue", "(", ")", ";", "updateCanvas", "(", "true", ")", ";", "}" ]
Scales the resolution on the y-axis by the given factor and updates the canvas. The y-resolution must not be lower than 1. @param factor factor the y_resolution will be scaled by
[ "Scales", "the", "resolution", "on", "the", "y", "-", "axis", "by", "the", "given", "factor", "and", "updates", "the", "canvas", ".", "The", "y", "-", "resolution", "must", "not", "be", "lower", "than", "1", "." ]
395982e5100bfe75a3a4d26115462ce2cc74cbb0
https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/moa/gui/visualization/AbstractGraphCanvas.java#L164-L169
28,846
Waikato/moa
moa/src/main/java/moa/gui/visualization/AbstractGraphCanvas.java
AbstractGraphCanvas.getMaxSelectedValue
private double getMaxSelectedValue() { double max = Double.MIN_VALUE; for (int i = 0; i < this.measures.length; i++) { if (this.measures[i].getMaxValue(this.measureSelected) > max) { max = this.measures[i].getMaxValue(this.measureSelected); } } return max; }
java
private double getMaxSelectedValue() { double max = Double.MIN_VALUE; for (int i = 0; i < this.measures.length; i++) { if (this.measures[i].getMaxValue(this.measureSelected) > max) { max = this.measures[i].getMaxValue(this.measureSelected); } } return max; }
[ "private", "double", "getMaxSelectedValue", "(", ")", "{", "double", "max", "=", "Double", ".", "MIN_VALUE", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "this", ".", "measures", ".", "length", ";", "i", "++", ")", "{", "if", "(", "this", ".", "measures", "[", "i", "]", ".", "getMaxValue", "(", "this", ".", "measureSelected", ")", ">", "max", ")", "{", "max", "=", "this", ".", "measures", "[", "i", "]", ".", "getMaxValue", "(", "this", ".", "measureSelected", ")", ";", "}", "}", "return", "max", ";", "}" ]
Computes the maximum value of the underlying measures at the currently selected measure. @return max value of measures at measureSelected
[ "Computes", "the", "maximum", "value", "of", "the", "underlying", "measures", "at", "the", "currently", "selected", "measure", "." ]
395982e5100bfe75a3a4d26115462ce2cc74cbb0
https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/moa/gui/visualization/AbstractGraphCanvas.java#L215-L224
28,847
Waikato/moa
moa/src/main/java/moa/gui/visualization/AbstractGraphCanvas.java
AbstractGraphCanvas.updateMinMaxValues
private boolean updateMinMaxValues() { double min_x_value_new; double max_x_value_new; double max_y_value_new; if (this.measures == null) { // no values received yet -> reset axes min_x_value_new = 0; max_x_value_new = 1; max_y_value_new = 1; } else { min_x_value_new = getMinXValue(); max_x_value_new = getMaxXValue(); max_y_value_new = getMaxSelectedValue(); } // resizing needed? if (min_x_value_new != this.min_x_value || max_x_value_new != this.max_x_value || max_y_value_new != this.max_y_value) { this.min_x_value = min_x_value_new; this.max_x_value = max_x_value_new; this.max_y_value = max_y_value_new; updateMinXValue(); updateMaxXValue(); updateMaxYValue(); updateLowerXValue(); updateUpperXValue(); updateUpperYValue(); return true; } return false; }
java
private boolean updateMinMaxValues() { double min_x_value_new; double max_x_value_new; double max_y_value_new; if (this.measures == null) { // no values received yet -> reset axes min_x_value_new = 0; max_x_value_new = 1; max_y_value_new = 1; } else { min_x_value_new = getMinXValue(); max_x_value_new = getMaxXValue(); max_y_value_new = getMaxSelectedValue(); } // resizing needed? if (min_x_value_new != this.min_x_value || max_x_value_new != this.max_x_value || max_y_value_new != this.max_y_value) { this.min_x_value = min_x_value_new; this.max_x_value = max_x_value_new; this.max_y_value = max_y_value_new; updateMinXValue(); updateMaxXValue(); updateMaxYValue(); updateLowerXValue(); updateUpperXValue(); updateUpperYValue(); return true; } return false; }
[ "private", "boolean", "updateMinMaxValues", "(", ")", "{", "double", "min_x_value_new", ";", "double", "max_x_value_new", ";", "double", "max_y_value_new", ";", "if", "(", "this", ".", "measures", "==", "null", ")", "{", "// no values received yet -> reset axes", "min_x_value_new", "=", "0", ";", "max_x_value_new", "=", "1", ";", "max_y_value_new", "=", "1", ";", "}", "else", "{", "min_x_value_new", "=", "getMinXValue", "(", ")", ";", "max_x_value_new", "=", "getMaxXValue", "(", ")", ";", "max_y_value_new", "=", "getMaxSelectedValue", "(", ")", ";", "}", "// resizing needed?", "if", "(", "min_x_value_new", "!=", "this", ".", "min_x_value", "||", "max_x_value_new", "!=", "this", ".", "max_x_value", "||", "max_y_value_new", "!=", "this", ".", "max_y_value", ")", "{", "this", ".", "min_x_value", "=", "min_x_value_new", ";", "this", ".", "max_x_value", "=", "max_x_value_new", ";", "this", ".", "max_y_value", "=", "max_y_value_new", ";", "updateMinXValue", "(", ")", ";", "updateMaxXValue", "(", ")", ";", "updateMaxYValue", "(", ")", ";", "updateLowerXValue", "(", ")", ";", "updateUpperXValue", "(", ")", ";", "updateUpperYValue", "(", ")", ";", "return", "true", ";", "}", "return", "false", ";", "}" ]
Computes the minimum and maximum values for the x and y-axis and updates the children, if necessary. @return true, if the values have changed
[ "Computes", "the", "minimum", "and", "maximum", "values", "for", "the", "x", "and", "y", "-", "axis", "and", "updates", "the", "children", "if", "necessary", "." ]
395982e5100bfe75a3a4d26115462ce2cc74cbb0
https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/moa/gui/visualization/AbstractGraphCanvas.java#L242-L275
28,848
Waikato/moa
moa/src/main/java/moa/gui/visualization/AbstractGraphCanvas.java
AbstractGraphCanvas.updateLowerXValue
private void updateLowerXValue() { double lower = 0.0; if (this.measures != null) { lower = this.min_x_value * (1 - (0.1 / x_resolution)); } this.axesPanel.setLowerXValue(lower); this.plotPanel.setLowerXValue(lower); }
java
private void updateLowerXValue() { double lower = 0.0; if (this.measures != null) { lower = this.min_x_value * (1 - (0.1 / x_resolution)); } this.axesPanel.setLowerXValue(lower); this.plotPanel.setLowerXValue(lower); }
[ "private", "void", "updateLowerXValue", "(", ")", "{", "double", "lower", "=", "0.0", ";", "if", "(", "this", ".", "measures", "!=", "null", ")", "{", "lower", "=", "this", ".", "min_x_value", "*", "(", "1", "-", "(", "0.1", "/", "x_resolution", ")", ")", ";", "}", "this", ".", "axesPanel", ".", "setLowerXValue", "(", "lower", ")", ";", "this", ".", "plotPanel", ".", "setLowerXValue", "(", "lower", ")", ";", "}" ]
Updates the lower value on the x-axis.
[ "Updates", "the", "lower", "value", "on", "the", "x", "-", "axis", "." ]
395982e5100bfe75a3a4d26115462ce2cc74cbb0
https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/moa/gui/visualization/AbstractGraphCanvas.java#L319-L327
28,849
Waikato/moa
moa/src/main/java/moa/gui/visualization/AbstractGraphCanvas.java
AbstractGraphCanvas.updateUpperXValue
private void updateUpperXValue() { double upper = 1.0; if (this.measures != null) { upper = max_x_value * (1 + (0.1 / x_resolution)); } this.axesPanel.setUpperXValue(upper); this.plotPanel.setUpperXValue(upper); }
java
private void updateUpperXValue() { double upper = 1.0; if (this.measures != null) { upper = max_x_value * (1 + (0.1 / x_resolution)); } this.axesPanel.setUpperXValue(upper); this.plotPanel.setUpperXValue(upper); }
[ "private", "void", "updateUpperXValue", "(", ")", "{", "double", "upper", "=", "1.0", ";", "if", "(", "this", ".", "measures", "!=", "null", ")", "{", "upper", "=", "max_x_value", "*", "(", "1", "+", "(", "0.1", "/", "x_resolution", ")", ")", ";", "}", "this", ".", "axesPanel", ".", "setUpperXValue", "(", "upper", ")", ";", "this", ".", "plotPanel", ".", "setUpperXValue", "(", "upper", ")", ";", "}" ]
Updates the upper value on the x-axis.
[ "Updates", "the", "upper", "value", "on", "the", "x", "-", "axis", "." ]
395982e5100bfe75a3a4d26115462ce2cc74cbb0
https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/moa/gui/visualization/AbstractGraphCanvas.java#L332-L340
28,850
Waikato/moa
moa/src/main/java/moa/gui/visualization/AbstractGraphCanvas.java
AbstractGraphCanvas.updateUpperYValue
private void updateUpperYValue() { double upper = 1.0; if (this.measures != null) { upper = max_y_value * (1 + (0.1 / y_resolution)); } this.axesPanel.setUpperYValue(upper); this.plotPanel.setUpperYValue(upper); }
java
private void updateUpperYValue() { double upper = 1.0; if (this.measures != null) { upper = max_y_value * (1 + (0.1 / y_resolution)); } this.axesPanel.setUpperYValue(upper); this.plotPanel.setUpperYValue(upper); }
[ "private", "void", "updateUpperYValue", "(", ")", "{", "double", "upper", "=", "1.0", ";", "if", "(", "this", ".", "measures", "!=", "null", ")", "{", "upper", "=", "max_y_value", "*", "(", "1", "+", "(", "0.1", "/", "y_resolution", ")", ")", ";", "}", "this", ".", "axesPanel", ".", "setUpperYValue", "(", "upper", ")", ";", "this", ".", "plotPanel", ".", "setUpperYValue", "(", "upper", ")", ";", "}" ]
Updates the upper value on the y-axis.
[ "Updates", "the", "upper", "value", "on", "the", "y", "-", "axis", "." ]
395982e5100bfe75a3a4d26115462ce2cc74cbb0
https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/moa/gui/visualization/AbstractGraphCanvas.java#L345-L353
28,851
Waikato/moa
moa/src/main/java/moa/gui/visualization/AbstractGraphCanvas.java
AbstractGraphCanvas.updateChildren
private void updateChildren() { axesPanel.setSize(getWidth(), getHeight()); plotPanel.setSize(getWidth() - X_OFFSET_LEFT - X_OFFSET_RIGHT, getHeight() - Y_OFFSET_BOTTOM - Y_OFFSET_TOP); }
java
private void updateChildren() { axesPanel.setSize(getWidth(), getHeight()); plotPanel.setSize(getWidth() - X_OFFSET_LEFT - X_OFFSET_RIGHT, getHeight() - Y_OFFSET_BOTTOM - Y_OFFSET_TOP); }
[ "private", "void", "updateChildren", "(", ")", "{", "axesPanel", ".", "setSize", "(", "getWidth", "(", ")", ",", "getHeight", "(", ")", ")", ";", "plotPanel", ".", "setSize", "(", "getWidth", "(", ")", "-", "X_OFFSET_LEFT", "-", "X_OFFSET_RIGHT", ",", "getHeight", "(", ")", "-", "Y_OFFSET_BOTTOM", "-", "Y_OFFSET_TOP", ")", ";", "}" ]
Updates the size of the axes, curve and event panel. Recomputes the event locations if necessary.
[ "Updates", "the", "size", "of", "the", "axes", "curve", "and", "event", "panel", ".", "Recomputes", "the", "event", "locations", "if", "necessary", "." ]
395982e5100bfe75a3a4d26115462ce2cc74cbb0
https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/moa/gui/visualization/AbstractGraphCanvas.java#L359-L363
28,852
Waikato/moa
moa/src/main/java/moa/options/EditableMultiChoiceOption.java
EditableMultiChoiceOption.setOptions
public void setOptions( String[] labels, String[] descriptions, int defaultIndex) { if (labels.length != descriptions.length) { throw new IllegalArgumentException("Labels/descriptions mismatch."); } if (labels.length > 0) { this.optionLabels = labels.clone(); this.optionDescriptions = descriptions.clone(); this.defaultOptionIndex = defaultIndex; } else { // use placeholders for empty list of choices this.optionLabels = new String[]{NO_CHOICES}; this.optionDescriptions = new String[]{NO_CHOICES_DESCRIPTION}; this.defaultOptionIndex = 0; } // reset to default value resetToDefault(); // refresh the edit component if (this.editComponent != null) { this.editComponent.refresh(); } }
java
public void setOptions( String[] labels, String[] descriptions, int defaultIndex) { if (labels.length != descriptions.length) { throw new IllegalArgumentException("Labels/descriptions mismatch."); } if (labels.length > 0) { this.optionLabels = labels.clone(); this.optionDescriptions = descriptions.clone(); this.defaultOptionIndex = defaultIndex; } else { // use placeholders for empty list of choices this.optionLabels = new String[]{NO_CHOICES}; this.optionDescriptions = new String[]{NO_CHOICES_DESCRIPTION}; this.defaultOptionIndex = 0; } // reset to default value resetToDefault(); // refresh the edit component if (this.editComponent != null) { this.editComponent.refresh(); } }
[ "public", "void", "setOptions", "(", "String", "[", "]", "labels", ",", "String", "[", "]", "descriptions", ",", "int", "defaultIndex", ")", "{", "if", "(", "labels", ".", "length", "!=", "descriptions", ".", "length", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Labels/descriptions mismatch.\"", ")", ";", "}", "if", "(", "labels", ".", "length", ">", "0", ")", "{", "this", ".", "optionLabels", "=", "labels", ".", "clone", "(", ")", ";", "this", ".", "optionDescriptions", "=", "descriptions", ".", "clone", "(", ")", ";", "this", ".", "defaultOptionIndex", "=", "defaultIndex", ";", "}", "else", "{", "// use placeholders for empty list of choices", "this", ".", "optionLabels", "=", "new", "String", "[", "]", "{", "NO_CHOICES", "}", ";", "this", ".", "optionDescriptions", "=", "new", "String", "[", "]", "{", "NO_CHOICES_DESCRIPTION", "}", ";", "this", ".", "defaultOptionIndex", "=", "0", ";", "}", "// reset to default value", "resetToDefault", "(", ")", ";", "// refresh the edit component", "if", "(", "this", ".", "editComponent", "!=", "null", ")", "{", "this", ".", "editComponent", ".", "refresh", "(", ")", ";", "}", "}" ]
Set new options for this MultiChoiceOption and refresh the edit component. @param labels @param descriptions @param defaultIndex
[ "Set", "new", "options", "for", "this", "MultiChoiceOption", "and", "refresh", "the", "edit", "component", "." ]
395982e5100bfe75a3a4d26115462ce2cc74cbb0
https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/moa/options/EditableMultiChoiceOption.java#L75-L101
28,853
Waikato/moa
moa/src/main/java/moa/clusterers/kmeanspm/CuckooHashing.java
CuckooHashing.put
public void put(long key, T element) { Entry<T> entry = new Entry<T>(key, element); elements.add(entry); this.numElements++; fileElement(entry, true); }
java
public void put(long key, T element) { Entry<T> entry = new Entry<T>(key, element); elements.add(entry); this.numElements++; fileElement(entry, true); }
[ "public", "void", "put", "(", "long", "key", ",", "T", "element", ")", "{", "Entry", "<", "T", ">", "entry", "=", "new", "Entry", "<", "T", ">", "(", "key", ",", "element", ")", ";", "elements", ".", "add", "(", "entry", ")", ";", "this", ".", "numElements", "++", ";", "fileElement", "(", "entry", ",", "true", ")", ";", "}" ]
Adds an element to the hash table. @param key key value of the element @param element value of the element
[ "Adds", "an", "element", "to", "the", "hash", "table", "." ]
395982e5100bfe75a3a4d26115462ce2cc74cbb0
https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/moa/clusterers/kmeanspm/CuckooHashing.java#L116-L121
28,854
Waikato/moa
moa/src/main/java/moa/clusterers/kmeanspm/CuckooHashing.java
CuckooHashing.fileElement
private void fileElement(Entry<T> currentElement, boolean rehash) { int maxFailures = Math.max((int) Math.log(this.numElements), this.numTables * 2); int currentTable = 0; for (int i = 0; i < maxFailures; i++) { int hash = this.hashfunctions.get(currentTable).hash( currentElement.getKey()); currentElement = this.tables.get(currentTable).set(hash, currentElement); if (currentElement == null) { break; } currentTable = (currentTable + 1) % this.numTables; } if (currentElement != null) { this.stash.add(currentElement); this.stashSize++; } while (rehash && this.stashSize > this.maxStashSize) { reset(); if (this.stashSize > this.maxStashSize) { increaseAndReset(); } } }
java
private void fileElement(Entry<T> currentElement, boolean rehash) { int maxFailures = Math.max((int) Math.log(this.numElements), this.numTables * 2); int currentTable = 0; for (int i = 0; i < maxFailures; i++) { int hash = this.hashfunctions.get(currentTable).hash( currentElement.getKey()); currentElement = this.tables.get(currentTable).set(hash, currentElement); if (currentElement == null) { break; } currentTable = (currentTable + 1) % this.numTables; } if (currentElement != null) { this.stash.add(currentElement); this.stashSize++; } while (rehash && this.stashSize > this.maxStashSize) { reset(); if (this.stashSize > this.maxStashSize) { increaseAndReset(); } } }
[ "private", "void", "fileElement", "(", "Entry", "<", "T", ">", "currentElement", ",", "boolean", "rehash", ")", "{", "int", "maxFailures", "=", "Math", ".", "max", "(", "(", "int", ")", "Math", ".", "log", "(", "this", ".", "numElements", ")", ",", "this", ".", "numTables", "*", "2", ")", ";", "int", "currentTable", "=", "0", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "maxFailures", ";", "i", "++", ")", "{", "int", "hash", "=", "this", ".", "hashfunctions", ".", "get", "(", "currentTable", ")", ".", "hash", "(", "currentElement", ".", "getKey", "(", ")", ")", ";", "currentElement", "=", "this", ".", "tables", ".", "get", "(", "currentTable", ")", ".", "set", "(", "hash", ",", "currentElement", ")", ";", "if", "(", "currentElement", "==", "null", ")", "{", "break", ";", "}", "currentTable", "=", "(", "currentTable", "+", "1", ")", "%", "this", ".", "numTables", ";", "}", "if", "(", "currentElement", "!=", "null", ")", "{", "this", ".", "stash", ".", "add", "(", "currentElement", ")", ";", "this", ".", "stashSize", "++", ";", "}", "while", "(", "rehash", "&&", "this", ".", "stashSize", ">", "this", ".", "maxStashSize", ")", "{", "reset", "(", ")", ";", "if", "(", "this", ".", "stashSize", ">", "this", ".", "maxStashSize", ")", "{", "increaseAndReset", "(", ")", ";", "}", "}", "}" ]
Adds an element to one of the tables for Cuckoo Hashing. @param currentElement entry to add in a table @param rehash if <code>true</code> the hash table will be rebuild when the stash became too big.
[ "Adds", "an", "element", "to", "one", "of", "the", "tables", "for", "Cuckoo", "Hashing", "." ]
395982e5100bfe75a3a4d26115462ce2cc74cbb0
https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/moa/clusterers/kmeanspm/CuckooHashing.java#L132-L156
28,855
Waikato/moa
moa/src/main/java/moa/clusterers/kmeanspm/CuckooHashing.java
CuckooHashing.increaseAndReset
private void increaseAndReset() { if (this.hashSize < 30) { this.hashSize += 1; this.hashfunctions.clear(); for (List<Entry<T>> table : this.tables) { this.hashfunctions.add(new DietzfelbingerHash(this.hashSize, this.random)); ((ArrayList<Entry<T>>) table) .ensureCapacity(1 << this.hashSize); } } else { this.hashfunctions.add(new DietzfelbingerHash(this.hashSize, this.random)); this.tables.add(new ArrayList<Entry<T>>(1 << this.hashSize)); this.numTables++; } reset(); }
java
private void increaseAndReset() { if (this.hashSize < 30) { this.hashSize += 1; this.hashfunctions.clear(); for (List<Entry<T>> table : this.tables) { this.hashfunctions.add(new DietzfelbingerHash(this.hashSize, this.random)); ((ArrayList<Entry<T>>) table) .ensureCapacity(1 << this.hashSize); } } else { this.hashfunctions.add(new DietzfelbingerHash(this.hashSize, this.random)); this.tables.add(new ArrayList<Entry<T>>(1 << this.hashSize)); this.numTables++; } reset(); }
[ "private", "void", "increaseAndReset", "(", ")", "{", "if", "(", "this", ".", "hashSize", "<", "30", ")", "{", "this", ".", "hashSize", "+=", "1", ";", "this", ".", "hashfunctions", ".", "clear", "(", ")", ";", "for", "(", "List", "<", "Entry", "<", "T", ">", ">", "table", ":", "this", ".", "tables", ")", "{", "this", ".", "hashfunctions", ".", "add", "(", "new", "DietzfelbingerHash", "(", "this", ".", "hashSize", ",", "this", ".", "random", ")", ")", ";", "(", "(", "ArrayList", "<", "Entry", "<", "T", ">", ">", ")", "table", ")", ".", "ensureCapacity", "(", "1", "<<", "this", ".", "hashSize", ")", ";", "}", "}", "else", "{", "this", ".", "hashfunctions", ".", "add", "(", "new", "DietzfelbingerHash", "(", "this", ".", "hashSize", ",", "this", ".", "random", ")", ")", ";", "this", ".", "tables", ".", "add", "(", "new", "ArrayList", "<", "Entry", "<", "T", ">", ">", "(", "1", "<<", "this", ".", "hashSize", ")", ")", ";", "this", ".", "numTables", "++", ";", "}", "reset", "(", ")", ";", "}" ]
Adds a new table and rebuild the hash table.
[ "Adds", "a", "new", "table", "and", "rebuild", "the", "hash", "table", "." ]
395982e5100bfe75a3a4d26115462ce2cc74cbb0
https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/moa/clusterers/kmeanspm/CuckooHashing.java#L162-L179
28,856
Waikato/moa
moa/src/main/java/moa/clusterers/kmeanspm/CuckooHashing.java
CuckooHashing.get
public T get(long key) { for (int i = 0; i < this.numTables; i++) { Entry<T> entry = this.tables.get(i).get( this.hashfunctions.get(i).hash(key)); if (entry != null && entry.getKey() == key) { return entry.getValue(); } } for (Entry<T> entry : this.stash) { if (entry.getKey() == key) { return entry.getValue(); } } return null; }
java
public T get(long key) { for (int i = 0; i < this.numTables; i++) { Entry<T> entry = this.tables.get(i).get( this.hashfunctions.get(i).hash(key)); if (entry != null && entry.getKey() == key) { return entry.getValue(); } } for (Entry<T> entry : this.stash) { if (entry.getKey() == key) { return entry.getValue(); } } return null; }
[ "public", "T", "get", "(", "long", "key", ")", "{", "for", "(", "int", "i", "=", "0", ";", "i", "<", "this", ".", "numTables", ";", "i", "++", ")", "{", "Entry", "<", "T", ">", "entry", "=", "this", ".", "tables", ".", "get", "(", "i", ")", ".", "get", "(", "this", ".", "hashfunctions", ".", "get", "(", "i", ")", ".", "hash", "(", "key", ")", ")", ";", "if", "(", "entry", "!=", "null", "&&", "entry", ".", "getKey", "(", ")", "==", "key", ")", "{", "return", "entry", ".", "getValue", "(", ")", ";", "}", "}", "for", "(", "Entry", "<", "T", ">", "entry", ":", "this", ".", "stash", ")", "{", "if", "(", "entry", ".", "getKey", "(", ")", "==", "key", ")", "{", "return", "entry", ".", "getValue", "(", ")", ";", "}", "}", "return", "null", ";", "}" ]
Gets an element of the hash table. @param key key value of the element
[ "Gets", "an", "element", "of", "the", "hash", "table", "." ]
395982e5100bfe75a3a4d26115462ce2cc74cbb0
https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/moa/clusterers/kmeanspm/CuckooHashing.java#L187-L201
28,857
Waikato/moa
moa/src/main/java/moa/clusterers/kmeanspm/CuckooHashing.java
CuckooHashing.reset
private void reset() { for (DietzfelbingerHash hashfunction : this.hashfunctions) { hashfunction.nextHashFunction(); } int sizeTables = 1 << this.hashSize; for (List<Entry<T>> table : this.tables) { table.clear(); for (int j = 0; j < sizeTables; j++) { table.add(null); } } this.stash.clear(); this.stashSize = 0; for (Entry<T> entry : this.elements) { fileElement(entry, false); } }
java
private void reset() { for (DietzfelbingerHash hashfunction : this.hashfunctions) { hashfunction.nextHashFunction(); } int sizeTables = 1 << this.hashSize; for (List<Entry<T>> table : this.tables) { table.clear(); for (int j = 0; j < sizeTables; j++) { table.add(null); } } this.stash.clear(); this.stashSize = 0; for (Entry<T> entry : this.elements) { fileElement(entry, false); } }
[ "private", "void", "reset", "(", ")", "{", "for", "(", "DietzfelbingerHash", "hashfunction", ":", "this", ".", "hashfunctions", ")", "{", "hashfunction", ".", "nextHashFunction", "(", ")", ";", "}", "int", "sizeTables", "=", "1", "<<", "this", ".", "hashSize", ";", "for", "(", "List", "<", "Entry", "<", "T", ">", ">", "table", ":", "this", ".", "tables", ")", "{", "table", ".", "clear", "(", ")", ";", "for", "(", "int", "j", "=", "0", ";", "j", "<", "sizeTables", ";", "j", "++", ")", "{", "table", ".", "add", "(", "null", ")", ";", "}", "}", "this", ".", "stash", ".", "clear", "(", ")", ";", "this", ".", "stashSize", "=", "0", ";", "for", "(", "Entry", "<", "T", ">", "entry", ":", "this", ".", "elements", ")", "{", "fileElement", "(", "entry", ",", "false", ")", ";", "}", "}" ]
Rebuilds the hash table.
[ "Rebuilds", "the", "hash", "table", "." ]
395982e5100bfe75a3a4d26115462ce2cc74cbb0
https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/moa/clusterers/kmeanspm/CuckooHashing.java#L207-L226
28,858
Waikato/moa
moa/src/main/java/moa/clusterers/kmeanspm/CuckooHashing.java
CuckooHashing.clear
public void clear() { this.hashSize = this.startHashSize; this.numTables = this.startNumTables; this.numElements = 0; this.hashfunctions.clear(); this.tables.clear(); int sizeTables = 1 << this.startHashSize; for (int i = 0; i < this.startNumTables; i++) { this.hashfunctions.add(new DietzfelbingerHash(this.startHashSize, this.random)); List<Entry<T>> table = new ArrayList<Entry<T>>(sizeTables); for (int j = 0; j < sizeTables; j++) { table.add(null); } this.tables.add(table); } this.stash.clear(); this.stashSize = 0; }
java
public void clear() { this.hashSize = this.startHashSize; this.numTables = this.startNumTables; this.numElements = 0; this.hashfunctions.clear(); this.tables.clear(); int sizeTables = 1 << this.startHashSize; for (int i = 0; i < this.startNumTables; i++) { this.hashfunctions.add(new DietzfelbingerHash(this.startHashSize, this.random)); List<Entry<T>> table = new ArrayList<Entry<T>>(sizeTables); for (int j = 0; j < sizeTables; j++) { table.add(null); } this.tables.add(table); } this.stash.clear(); this.stashSize = 0; }
[ "public", "void", "clear", "(", ")", "{", "this", ".", "hashSize", "=", "this", ".", "startHashSize", ";", "this", ".", "numTables", "=", "this", ".", "startNumTables", ";", "this", ".", "numElements", "=", "0", ";", "this", ".", "hashfunctions", ".", "clear", "(", ")", ";", "this", ".", "tables", ".", "clear", "(", ")", ";", "int", "sizeTables", "=", "1", "<<", "this", ".", "startHashSize", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "this", ".", "startNumTables", ";", "i", "++", ")", "{", "this", ".", "hashfunctions", ".", "add", "(", "new", "DietzfelbingerHash", "(", "this", ".", "startHashSize", ",", "this", ".", "random", ")", ")", ";", "List", "<", "Entry", "<", "T", ">", ">", "table", "=", "new", "ArrayList", "<", "Entry", "<", "T", ">", ">", "(", "sizeTables", ")", ";", "for", "(", "int", "j", "=", "0", ";", "j", "<", "sizeTables", ";", "j", "++", ")", "{", "table", ".", "add", "(", "null", ")", ";", "}", "this", ".", "tables", ".", "add", "(", "table", ")", ";", "}", "this", ".", "stash", ".", "clear", "(", ")", ";", "this", ".", "stashSize", "=", "0", ";", "}" ]
Removes all of the elements from this hash table. The hash table will be empty after this call returns.
[ "Removes", "all", "of", "the", "elements", "from", "this", "hash", "table", ".", "The", "hash", "table", "will", "be", "empty", "after", "this", "call", "returns", "." ]
395982e5100bfe75a3a4d26115462ce2cc74cbb0
https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/moa/clusterers/kmeanspm/CuckooHashing.java#L233-L253
28,859
Waikato/moa
moa/src/main/java/moa/classifiers/lazy/neighboursearch/kdtrees/MedianOfWidestDimension.java
MedianOfWidestDimension.splitNode
public void splitNode(KDTreeNode node, int numNodesCreated, double[][] nodeRanges, double[][] universe) throws Exception { correctlyInitialized(); int splitDim = widestDim(nodeRanges, universe); //In this case median is defined to be either the middle value (in case of //odd number of values) or the left of the two middle values (in case of //even number of values). int medianIdxIdx = node.m_Start + (node.m_End-node.m_Start)/2; //the following finds the median and also re-arranges the array so all //elements to the left are < median and those to the right are > median. int medianIdx = select(splitDim, m_InstList, node.m_Start, node.m_End, (node.m_End-node.m_Start)/2+1); node.m_SplitDim = splitDim; node.m_SplitValue = m_Instances.instance(m_InstList[medianIdx]).value(splitDim); node.m_Left = new KDTreeNode(numNodesCreated+1, node.m_Start, medianIdxIdx, m_EuclideanDistance.initializeRanges(m_InstList, node.m_Start, medianIdxIdx)); node.m_Right = new KDTreeNode(numNodesCreated+2, medianIdxIdx+1, node.m_End, m_EuclideanDistance.initializeRanges(m_InstList, medianIdxIdx+1, node.m_End)); }
java
public void splitNode(KDTreeNode node, int numNodesCreated, double[][] nodeRanges, double[][] universe) throws Exception { correctlyInitialized(); int splitDim = widestDim(nodeRanges, universe); //In this case median is defined to be either the middle value (in case of //odd number of values) or the left of the two middle values (in case of //even number of values). int medianIdxIdx = node.m_Start + (node.m_End-node.m_Start)/2; //the following finds the median and also re-arranges the array so all //elements to the left are < median and those to the right are > median. int medianIdx = select(splitDim, m_InstList, node.m_Start, node.m_End, (node.m_End-node.m_Start)/2+1); node.m_SplitDim = splitDim; node.m_SplitValue = m_Instances.instance(m_InstList[medianIdx]).value(splitDim); node.m_Left = new KDTreeNode(numNodesCreated+1, node.m_Start, medianIdxIdx, m_EuclideanDistance.initializeRanges(m_InstList, node.m_Start, medianIdxIdx)); node.m_Right = new KDTreeNode(numNodesCreated+2, medianIdxIdx+1, node.m_End, m_EuclideanDistance.initializeRanges(m_InstList, medianIdxIdx+1, node.m_End)); }
[ "public", "void", "splitNode", "(", "KDTreeNode", "node", ",", "int", "numNodesCreated", ",", "double", "[", "]", "[", "]", "nodeRanges", ",", "double", "[", "]", "[", "]", "universe", ")", "throws", "Exception", "{", "correctlyInitialized", "(", ")", ";", "int", "splitDim", "=", "widestDim", "(", "nodeRanges", ",", "universe", ")", ";", "//In this case median is defined to be either the middle value (in case of", "//odd number of values) or the left of the two middle values (in case of ", "//even number of values).", "int", "medianIdxIdx", "=", "node", ".", "m_Start", "+", "(", "node", ".", "m_End", "-", "node", ".", "m_Start", ")", "/", "2", ";", "//the following finds the median and also re-arranges the array so all ", "//elements to the left are < median and those to the right are > median.", "int", "medianIdx", "=", "select", "(", "splitDim", ",", "m_InstList", ",", "node", ".", "m_Start", ",", "node", ".", "m_End", ",", "(", "node", ".", "m_End", "-", "node", ".", "m_Start", ")", "/", "2", "+", "1", ")", ";", "node", ".", "m_SplitDim", "=", "splitDim", ";", "node", ".", "m_SplitValue", "=", "m_Instances", ".", "instance", "(", "m_InstList", "[", "medianIdx", "]", ")", ".", "value", "(", "splitDim", ")", ";", "node", ".", "m_Left", "=", "new", "KDTreeNode", "(", "numNodesCreated", "+", "1", ",", "node", ".", "m_Start", ",", "medianIdxIdx", ",", "m_EuclideanDistance", ".", "initializeRanges", "(", "m_InstList", ",", "node", ".", "m_Start", ",", "medianIdxIdx", ")", ")", ";", "node", ".", "m_Right", "=", "new", "KDTreeNode", "(", "numNodesCreated", "+", "2", ",", "medianIdxIdx", "+", "1", ",", "node", ".", "m_End", ",", "m_EuclideanDistance", ".", "initializeRanges", "(", "m_InstList", ",", "medianIdxIdx", "+", "1", ",", "node", ".", "m_End", ")", ")", ";", "}" ]
Splits a node into two based on the median value of the dimension in which the points have the widest spread. After splitting two new nodes are created and correctly initialised. And, node.left and node.right are set appropriately. @param node The node to split. @param numNodesCreated The number of nodes that so far have been created for the tree, so that the newly created nodes are assigned correct/meaningful node numbers/ids. @param nodeRanges The attributes' range for the points inside the node that is to be split. @param universe The attributes' range for the whole point-space. @throws Exception If there is some problem in splitting the given node.
[ "Splits", "a", "node", "into", "two", "based", "on", "the", "median", "value", "of", "the", "dimension", "in", "which", "the", "points", "have", "the", "widest", "spread", ".", "After", "splitting", "two", "new", "nodes", "are", "created", "and", "correctly", "initialised", ".", "And", "node", ".", "left", "and", "node", ".", "right", "are", "set", "appropriately", "." ]
395982e5100bfe75a3a4d26115462ce2cc74cbb0
https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/moa/classifiers/lazy/neighboursearch/kdtrees/MedianOfWidestDimension.java#L94-L117
28,860
Waikato/moa
moa/src/main/java/moa/classifiers/lazy/neighboursearch/kdtrees/MedianOfWidestDimension.java
MedianOfWidestDimension.select
public int select(int attIdx, int[] indices, int left, int right, int k) { if (left == right) { return left; } else { int middle = partition(attIdx, indices, left, right); if ((middle - left + 1) >= k) { return select(attIdx, indices, left, middle, k); } else { return select(attIdx, indices, middle + 1, right, k - (middle - left + 1)); } } }
java
public int select(int attIdx, int[] indices, int left, int right, int k) { if (left == right) { return left; } else { int middle = partition(attIdx, indices, left, right); if ((middle - left + 1) >= k) { return select(attIdx, indices, left, middle, k); } else { return select(attIdx, indices, middle + 1, right, k - (middle - left + 1)); } } }
[ "public", "int", "select", "(", "int", "attIdx", ",", "int", "[", "]", "indices", ",", "int", "left", ",", "int", "right", ",", "int", "k", ")", "{", "if", "(", "left", "==", "right", ")", "{", "return", "left", ";", "}", "else", "{", "int", "middle", "=", "partition", "(", "attIdx", ",", "indices", ",", "left", ",", "right", ")", ";", "if", "(", "(", "middle", "-", "left", "+", "1", ")", ">=", "k", ")", "{", "return", "select", "(", "attIdx", ",", "indices", ",", "left", ",", "middle", ",", "k", ")", ";", "}", "else", "{", "return", "select", "(", "attIdx", ",", "indices", ",", "middle", "+", "1", ",", "right", ",", "k", "-", "(", "middle", "-", "left", "+", "1", ")", ")", ";", "}", "}", "}" ]
Implements computation of the kth-smallest element according to Manber's "Introduction to Algorithms". @param attIdx The dimension/attribute of the instances in which to find the kth-smallest element. @param indices The master index array containing indices of the instances. @param left The begining index of the portion of the master index array in which to find the kth-smallest element. @param right The end index of the portion of the master index array in which to find the kth-smallest element. @param k The value of k @return The index of the kth-smallest element
[ "Implements", "computation", "of", "the", "kth", "-", "smallest", "element", "according", "to", "Manber", "s", "Introduction", "to", "Algorithms", "." ]
395982e5100bfe75a3a4d26115462ce2cc74cbb0
https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/moa/classifiers/lazy/neighboursearch/kdtrees/MedianOfWidestDimension.java#L175-L187
28,861
Waikato/moa
moa/src/main/java/com/yahoo/labs/samoa/instances/Instances.java
Instances.deleteAttributeAt
public void deleteAttributeAt(Integer integer) { this.instanceInformation.deleteAttributeAt(integer); for (int i = 0; i < numInstances(); i++) { instance(i).setDataset(null); instance(i).deleteAttributeAt(integer); instance(i).setDataset(this); } }
java
public void deleteAttributeAt(Integer integer) { this.instanceInformation.deleteAttributeAt(integer); for (int i = 0; i < numInstances(); i++) { instance(i).setDataset(null); instance(i).deleteAttributeAt(integer); instance(i).setDataset(this); } }
[ "public", "void", "deleteAttributeAt", "(", "Integer", "integer", ")", "{", "this", ".", "instanceInformation", ".", "deleteAttributeAt", "(", "integer", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "numInstances", "(", ")", ";", "i", "++", ")", "{", "instance", "(", "i", ")", ".", "setDataset", "(", "null", ")", ";", "instance", "(", "i", ")", ".", "deleteAttributeAt", "(", "integer", ")", ";", "instance", "(", "i", ")", ".", "setDataset", "(", "this", ")", ";", "}", "}" ]
Delete attribute at. @param integer the integer
[ "Delete", "attribute", "at", "." ]
395982e5100bfe75a3a4d26115462ce2cc74cbb0
https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/com/yahoo/labs/samoa/instances/Instances.java#L280-L287
28,862
Waikato/moa
moa/src/main/java/com/yahoo/labs/samoa/instances/Instances.java
Instances.insertAttributeAt
public void insertAttributeAt(Attribute attribute, int position) { if (this.instanceInformation == null) { this.instanceInformation = new InstanceInformation(); } this.instanceInformation.insertAttributeAt(attribute, position); for (int i = 0; i < numInstances(); i++) { instance(i).setDataset(null); instance(i).insertAttributeAt(i); instance(i).setDataset(this); } }
java
public void insertAttributeAt(Attribute attribute, int position) { if (this.instanceInformation == null) { this.instanceInformation = new InstanceInformation(); } this.instanceInformation.insertAttributeAt(attribute, position); for (int i = 0; i < numInstances(); i++) { instance(i).setDataset(null); instance(i).insertAttributeAt(i); instance(i).setDataset(this); } }
[ "public", "void", "insertAttributeAt", "(", "Attribute", "attribute", ",", "int", "position", ")", "{", "if", "(", "this", ".", "instanceInformation", "==", "null", ")", "{", "this", ".", "instanceInformation", "=", "new", "InstanceInformation", "(", ")", ";", "}", "this", ".", "instanceInformation", ".", "insertAttributeAt", "(", "attribute", ",", "position", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "numInstances", "(", ")", ";", "i", "++", ")", "{", "instance", "(", "i", ")", ".", "setDataset", "(", "null", ")", ";", "instance", "(", "i", ")", ".", "insertAttributeAt", "(", "i", ")", ";", "instance", "(", "i", ")", ".", "setDataset", "(", "this", ")", ";", "}", "}" ]
Insert attribute at. @param attribute the attribute @param position the position
[ "Insert", "attribute", "at", "." ]
395982e5100bfe75a3a4d26115462ce2cc74cbb0
https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/com/yahoo/labs/samoa/instances/Instances.java#L295-L305
28,863
Waikato/moa
moa/src/main/java/com/yahoo/labs/samoa/instances/Instances.java
Instances.trainCV
public Instances trainCV(int numFolds, int numFold, Random random) { Instances train = trainCV(numFolds, numFold); train.randomize(random); return train; }
java
public Instances trainCV(int numFolds, int numFold, Random random) { Instances train = trainCV(numFolds, numFold); train.randomize(random); return train; }
[ "public", "Instances", "trainCV", "(", "int", "numFolds", ",", "int", "numFold", ",", "Random", "random", ")", "{", "Instances", "train", "=", "trainCV", "(", "numFolds", ",", "numFold", ")", ";", "train", ".", "randomize", "(", "random", ")", ";", "return", "train", ";", "}" ]
Train cv. @param numFolds the num folds @param numFold @param random the random @return the instances
[ "Train", "cv", "." ]
395982e5100bfe75a3a4d26115462ce2cc74cbb0
https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/com/yahoo/labs/samoa/instances/Instances.java#L399-L403
28,864
Waikato/moa
moa/src/main/java/com/yahoo/labs/samoa/instances/Instances.java
Instances.readInstance
public boolean readInstance(Reader fileReader) { //ArffReader arff = new ArffReader(reader, this, m_Lines, 1); Instance inst = arff.readInstance(); if (inst != null) { inst.setDataset(this); add(inst); return true; } else { return false; } }
java
public boolean readInstance(Reader fileReader) { //ArffReader arff = new ArffReader(reader, this, m_Lines, 1); Instance inst = arff.readInstance(); if (inst != null) { inst.setDataset(this); add(inst); return true; } else { return false; } }
[ "public", "boolean", "readInstance", "(", "Reader", "fileReader", ")", "{", "//ArffReader arff = new ArffReader(reader, this, m_Lines, 1);", "Instance", "inst", "=", "arff", ".", "readInstance", "(", ")", ";", "if", "(", "inst", "!=", "null", ")", "{", "inst", ".", "setDataset", "(", "this", ")", ";", "add", "(", "inst", ")", ";", "return", "true", ";", "}", "else", "{", "return", "false", ";", "}", "}" ]
Read instance. @param fileReader the file reader @return true, if successful
[ "Read", "instance", "." ]
395982e5100bfe75a3a4d26115462ce2cc74cbb0
https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/com/yahoo/labs/samoa/instances/Instances.java#L474-L485
28,865
Waikato/moa
moa/src/main/java/com/yahoo/labs/samoa/instances/Instances.java
Instances.stringWithoutHeader
protected String stringWithoutHeader() { StringBuffer text = new StringBuffer(); for (int i = 0; i < numInstances(); i++) { text.append(instance(i)); if (i < numInstances() - 1) { text.append('\n'); } } return text.toString(); }
java
protected String stringWithoutHeader() { StringBuffer text = new StringBuffer(); for (int i = 0; i < numInstances(); i++) { text.append(instance(i)); if (i < numInstances() - 1) { text.append('\n'); } } return text.toString(); }
[ "protected", "String", "stringWithoutHeader", "(", ")", "{", "StringBuffer", "text", "=", "new", "StringBuffer", "(", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "numInstances", "(", ")", ";", "i", "++", ")", "{", "text", ".", "append", "(", "instance", "(", "i", ")", ")", ";", "if", "(", "i", "<", "numInstances", "(", ")", "-", "1", ")", "{", "text", ".", "append", "(", "'", "'", ")", ";", "}", "}", "return", "text", ".", "toString", "(", ")", ";", "}" ]
Returns the instances in the dataset as a string in ARFF format. Strings are quoted if they contain whitespace characters, or if they are a question mark. @return the dataset in ARFF format as a string
[ "Returns", "the", "instances", "in", "the", "dataset", "as", "a", "string", "in", "ARFF", "format", ".", "Strings", "are", "quoted", "if", "they", "contain", "whitespace", "characters", "or", "if", "they", "are", "a", "question", "mark", "." ]
395982e5100bfe75a3a4d26115462ce2cc74cbb0
https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/com/yahoo/labs/samoa/instances/Instances.java#L601-L613
28,866
Waikato/moa
moa/src/main/java/com/yahoo/labs/samoa/instances/Instances.java
Instances.computeAttributesIndices
private void computeAttributesIndices() { this.hsAttributesIndices = new HashMap<String, Integer>(); // iterates through all existing attributes // and sets an unique identifier for each one of them for (int i = 0; i < this.numAttributes(); i++) { hsAttributesIndices.put(this.attribute(i).name(), i); } }
java
private void computeAttributesIndices() { this.hsAttributesIndices = new HashMap<String, Integer>(); // iterates through all existing attributes // and sets an unique identifier for each one of them for (int i = 0; i < this.numAttributes(); i++) { hsAttributesIndices.put(this.attribute(i).name(), i); } }
[ "private", "void", "computeAttributesIndices", "(", ")", "{", "this", ".", "hsAttributesIndices", "=", "new", "HashMap", "<", "String", ",", "Integer", ">", "(", ")", ";", "// iterates through all existing attributes ", "// and sets an unique identifier for each one of them", "for", "(", "int", "i", "=", "0", ";", "i", "<", "this", ".", "numAttributes", "(", ")", ";", "i", "++", ")", "{", "hsAttributesIndices", ".", "put", "(", "this", ".", "attribute", "(", "i", ")", ".", "name", "(", ")", ",", "i", ")", ";", "}", "}" ]
Completes the hashset with attributes indices.
[ "Completes", "the", "hashset", "with", "attributes", "indices", "." ]
395982e5100bfe75a3a4d26115462ce2cc74cbb0
https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/com/yahoo/labs/samoa/instances/Instances.java#L627-L634
28,867
Waikato/moa
moa/src/main/java/com/yahoo/labs/samoa/instances/Instances.java
Instances.setIndicesRelevants
public void setIndicesRelevants(int[] indicesRelevants) { this.indicesRelevants = indicesRelevants; // -1 to skip the class attribute int numIrrelevantFeatures = this.numAttributes() - this.indicesRelevants.length - 1; this.indicesIrrelevants = new int[numIrrelevantFeatures]; // Infers and sets the set of irrelevant features int index = 0; int indexRel = 0; for(int i = 0; i < numAttributes(); i++){ if(i != classIndex()) { while (indexRel < indicesRelevants.length - 1 && i > indicesRelevants[indexRel]) indexRel++; if (indicesRelevants[indexRel] != i){ indicesIrrelevants[index] = i; index++; } } } }
java
public void setIndicesRelevants(int[] indicesRelevants) { this.indicesRelevants = indicesRelevants; // -1 to skip the class attribute int numIrrelevantFeatures = this.numAttributes() - this.indicesRelevants.length - 1; this.indicesIrrelevants = new int[numIrrelevantFeatures]; // Infers and sets the set of irrelevant features int index = 0; int indexRel = 0; for(int i = 0; i < numAttributes(); i++){ if(i != classIndex()) { while (indexRel < indicesRelevants.length - 1 && i > indicesRelevants[indexRel]) indexRel++; if (indicesRelevants[indexRel] != i){ indicesIrrelevants[index] = i; index++; } } } }
[ "public", "void", "setIndicesRelevants", "(", "int", "[", "]", "indicesRelevants", ")", "{", "this", ".", "indicesRelevants", "=", "indicesRelevants", ";", "// -1 to skip the class attribute", "int", "numIrrelevantFeatures", "=", "this", ".", "numAttributes", "(", ")", "-", "this", ".", "indicesRelevants", ".", "length", "-", "1", ";", "this", ".", "indicesIrrelevants", "=", "new", "int", "[", "numIrrelevantFeatures", "]", ";", "// Infers and sets the set of irrelevant features", "int", "index", "=", "0", ";", "int", "indexRel", "=", "0", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "numAttributes", "(", ")", ";", "i", "++", ")", "{", "if", "(", "i", "!=", "classIndex", "(", ")", ")", "{", "while", "(", "indexRel", "<", "indicesRelevants", ".", "length", "-", "1", "&&", "i", ">", "indicesRelevants", "[", "indexRel", "]", ")", "indexRel", "++", ";", "if", "(", "indicesRelevants", "[", "indexRel", "]", "!=", "i", ")", "{", "indicesIrrelevants", "[", "index", "]", "=", "i", ";", "index", "++", ";", "}", "}", "}", "}" ]
Sets the indices of relevant features. This method also sets the irrelevant ones since it is the set complement. @param indicesRelevants
[ "Sets", "the", "indices", "of", "relevant", "features", ".", "This", "method", "also", "sets", "the", "irrelevant", "ones", "since", "it", "is", "the", "set", "complement", "." ]
395982e5100bfe75a3a4d26115462ce2cc74cbb0
https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/com/yahoo/labs/samoa/instances/Instances.java#L659-L678
28,868
Waikato/moa
moa/src/main/java/moa/cluster/SphereCluster.java
SphereCluster.sample
public Instance sample(Random random) { // Create sample in hypersphere coordinates //get the center through getCenter so subclass have a chance double[] center = getCenter(); final int dimensions = center.length; final double sin[] = new double[dimensions - 1]; final double cos[] = new double[dimensions - 1]; final double length = random.nextDouble() * getRadius(); double lastValue = 1.0; for (int i = 0; i < dimensions-1; i++) { double angle = random.nextDouble() * 2 * Math.PI; sin[i] = lastValue * Math.sin( angle ); // Store cumulative values cos[i] = Math.cos( angle ); lastValue = sin[i]; } // Calculate cartesian coordinates double res[] = new double[dimensions]; // First value uses only cosines res[0] = center[0] + length*cos[0]; // Loop through 'middle' coordinates which use cosines and sines for (int i = 1; i < dimensions-1; i++) { res[i] = center[i] + length*sin[i-1]*cos[i]; } // Last value uses only sines res[dimensions-1] = center[dimensions-1] + length*sin[dimensions-2]; return new DenseInstance(1.0, res); }
java
public Instance sample(Random random) { // Create sample in hypersphere coordinates //get the center through getCenter so subclass have a chance double[] center = getCenter(); final int dimensions = center.length; final double sin[] = new double[dimensions - 1]; final double cos[] = new double[dimensions - 1]; final double length = random.nextDouble() * getRadius(); double lastValue = 1.0; for (int i = 0; i < dimensions-1; i++) { double angle = random.nextDouble() * 2 * Math.PI; sin[i] = lastValue * Math.sin( angle ); // Store cumulative values cos[i] = Math.cos( angle ); lastValue = sin[i]; } // Calculate cartesian coordinates double res[] = new double[dimensions]; // First value uses only cosines res[0] = center[0] + length*cos[0]; // Loop through 'middle' coordinates which use cosines and sines for (int i = 1; i < dimensions-1; i++) { res[i] = center[i] + length*sin[i-1]*cos[i]; } // Last value uses only sines res[dimensions-1] = center[dimensions-1] + length*sin[dimensions-2]; return new DenseInstance(1.0, res); }
[ "public", "Instance", "sample", "(", "Random", "random", ")", "{", "// Create sample in hypersphere coordinates", "//get the center through getCenter so subclass have a chance", "double", "[", "]", "center", "=", "getCenter", "(", ")", ";", "final", "int", "dimensions", "=", "center", ".", "length", ";", "final", "double", "sin", "[", "]", "=", "new", "double", "[", "dimensions", "-", "1", "]", ";", "final", "double", "cos", "[", "]", "=", "new", "double", "[", "dimensions", "-", "1", "]", ";", "final", "double", "length", "=", "random", ".", "nextDouble", "(", ")", "*", "getRadius", "(", ")", ";", "double", "lastValue", "=", "1.0", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "dimensions", "-", "1", ";", "i", "++", ")", "{", "double", "angle", "=", "random", ".", "nextDouble", "(", ")", "*", "2", "*", "Math", ".", "PI", ";", "sin", "[", "i", "]", "=", "lastValue", "*", "Math", ".", "sin", "(", "angle", ")", ";", "// Store cumulative values", "cos", "[", "i", "]", "=", "Math", ".", "cos", "(", "angle", ")", ";", "lastValue", "=", "sin", "[", "i", "]", ";", "}", "// Calculate cartesian coordinates", "double", "res", "[", "]", "=", "new", "double", "[", "dimensions", "]", ";", "// First value uses only cosines", "res", "[", "0", "]", "=", "center", "[", "0", "]", "+", "length", "*", "cos", "[", "0", "]", ";", "// Loop through 'middle' coordinates which use cosines and sines", "for", "(", "int", "i", "=", "1", ";", "i", "<", "dimensions", "-", "1", ";", "i", "++", ")", "{", "res", "[", "i", "]", "=", "center", "[", "i", "]", "+", "length", "*", "sin", "[", "i", "-", "1", "]", "*", "cos", "[", "i", "]", ";", "}", "// Last value uses only sines", "res", "[", "dimensions", "-", "1", "]", "=", "center", "[", "dimensions", "-", "1", "]", "+", "length", "*", "sin", "[", "dimensions", "-", "2", "]", ";", "return", "new", "DenseInstance", "(", "1.0", ",", "res", ")", ";", "}" ]
Samples this cluster by returning a point from inside it. @param random a random number source @return a point that lies inside this cluster
[ "Samples", "this", "cluster", "by", "returning", "a", "point", "from", "inside", "it", "." ]
395982e5100bfe75a3a4d26115462ce2cc74cbb0
https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/moa/cluster/SphereCluster.java#L332-L366
28,869
Waikato/moa
moa/src/main/java/moa/clusterers/kmeanspm/CoresetKMeans.java
CoresetKMeans.generatekMeansPlusPlusCentroids
public static List<double[]> generatekMeansPlusPlusCentroids(int k, List<double[]> input, Random random) { int n = input.size(); assert (n > 0); int d = input.get(0).length - 1; assert (k <= n); List<double[]> centerValue = new ArrayList<double[]>(k); // Selects and copies the first centroid double[] lastCenter = new double[d]; System.arraycopy(input.get(random.nextInt(n)), 1, lastCenter, 0, d); centerValue.add(lastCenter); double[] distance = new double[n]; for (int j = 0; j < n; j++) { distance[j] = Double.POSITIVE_INFINITY; } for (int i = 1; i < k; i++) { // Selects the next centroid double sum = 0.0; Iterator<double[]> jIter = input.iterator(); for (int j = 0; j < n; j++) { double[] point = jIter.next(); distance[j] = Math .min(distance[j], point[0] * Metric.distanceSquared(lastCenter, point, 1)); sum += distance[j]; } int candidate = 0; if (sum > 0) { double nextCenterValue = sum * random.nextDouble(); double currentValue = distance[0]; while (!(nextCenterValue < currentValue)) { currentValue += distance[++candidate]; } } // Copies the selected centroid lastCenter = new double[d]; System.arraycopy(input.get(candidate), 1, lastCenter, 0, d); centerValue.add(lastCenter); } return centerValue; }
java
public static List<double[]> generatekMeansPlusPlusCentroids(int k, List<double[]> input, Random random) { int n = input.size(); assert (n > 0); int d = input.get(0).length - 1; assert (k <= n); List<double[]> centerValue = new ArrayList<double[]>(k); // Selects and copies the first centroid double[] lastCenter = new double[d]; System.arraycopy(input.get(random.nextInt(n)), 1, lastCenter, 0, d); centerValue.add(lastCenter); double[] distance = new double[n]; for (int j = 0; j < n; j++) { distance[j] = Double.POSITIVE_INFINITY; } for (int i = 1; i < k; i++) { // Selects the next centroid double sum = 0.0; Iterator<double[]> jIter = input.iterator(); for (int j = 0; j < n; j++) { double[] point = jIter.next(); distance[j] = Math .min(distance[j], point[0] * Metric.distanceSquared(lastCenter, point, 1)); sum += distance[j]; } int candidate = 0; if (sum > 0) { double nextCenterValue = sum * random.nextDouble(); double currentValue = distance[0]; while (!(nextCenterValue < currentValue)) { currentValue += distance[++candidate]; } } // Copies the selected centroid lastCenter = new double[d]; System.arraycopy(input.get(candidate), 1, lastCenter, 0, d); centerValue.add(lastCenter); } return centerValue; }
[ "public", "static", "List", "<", "double", "[", "]", ">", "generatekMeansPlusPlusCentroids", "(", "int", "k", ",", "List", "<", "double", "[", "]", ">", "input", ",", "Random", "random", ")", "{", "int", "n", "=", "input", ".", "size", "(", ")", ";", "assert", "(", "n", ">", "0", ")", ";", "int", "d", "=", "input", ".", "get", "(", "0", ")", ".", "length", "-", "1", ";", "assert", "(", "k", "<=", "n", ")", ";", "List", "<", "double", "[", "]", ">", "centerValue", "=", "new", "ArrayList", "<", "double", "[", "]", ">", "(", "k", ")", ";", "// Selects and copies the first centroid", "double", "[", "]", "lastCenter", "=", "new", "double", "[", "d", "]", ";", "System", ".", "arraycopy", "(", "input", ".", "get", "(", "random", ".", "nextInt", "(", "n", ")", ")", ",", "1", ",", "lastCenter", ",", "0", ",", "d", ")", ";", "centerValue", ".", "add", "(", "lastCenter", ")", ";", "double", "[", "]", "distance", "=", "new", "double", "[", "n", "]", ";", "for", "(", "int", "j", "=", "0", ";", "j", "<", "n", ";", "j", "++", ")", "{", "distance", "[", "j", "]", "=", "Double", ".", "POSITIVE_INFINITY", ";", "}", "for", "(", "int", "i", "=", "1", ";", "i", "<", "k", ";", "i", "++", ")", "{", "// Selects the next centroid", "double", "sum", "=", "0.0", ";", "Iterator", "<", "double", "[", "]", ">", "jIter", "=", "input", ".", "iterator", "(", ")", ";", "for", "(", "int", "j", "=", "0", ";", "j", "<", "n", ";", "j", "++", ")", "{", "double", "[", "]", "point", "=", "jIter", ".", "next", "(", ")", ";", "distance", "[", "j", "]", "=", "Math", ".", "min", "(", "distance", "[", "j", "]", ",", "point", "[", "0", "]", "*", "Metric", ".", "distanceSquared", "(", "lastCenter", ",", "point", ",", "1", ")", ")", ";", "sum", "+=", "distance", "[", "j", "]", ";", "}", "int", "candidate", "=", "0", ";", "if", "(", "sum", ">", "0", ")", "{", "double", "nextCenterValue", "=", "sum", "*", "random", ".", "nextDouble", "(", ")", ";", "double", "currentValue", "=", "distance", "[", "0", "]", ";", "while", "(", "!", "(", "nextCenterValue", "<", "currentValue", ")", ")", "{", "currentValue", "+=", "distance", "[", "++", "candidate", "]", ";", "}", "}", "// Copies the selected centroid", "lastCenter", "=", "new", "double", "[", "d", "]", ";", "System", ".", "arraycopy", "(", "input", ".", "get", "(", "candidate", ")", ",", "1", ",", "lastCenter", ",", "0", ",", "d", ")", ";", "centerValue", ".", "add", "(", "lastCenter", ")", ";", "}", "return", "centerValue", ";", "}" ]
Generates the initial centroids like the k-means++ algorithm. @param k number of centroids @param input input clustering @param random instance to generate a stream of pseudorandom numbers @return the generated centroids
[ "Generates", "the", "initial", "centroids", "like", "the", "k", "-", "means", "++", "algorithm", "." ]
395982e5100bfe75a3a4d26115462ce2cc74cbb0
https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/moa/clusterers/kmeanspm/CoresetKMeans.java#L49-L95
28,870
Waikato/moa
moa/src/main/java/moa/clusterers/clustree/Node.java
Node.isLeaf
protected boolean isLeaf() { for (int i = 0; i < entries.length; i++) { Entry entry = entries[i]; if (entry.getChild() != null) { return false; } } return true; }
java
protected boolean isLeaf() { for (int i = 0; i < entries.length; i++) { Entry entry = entries[i]; if (entry.getChild() != null) { return false; } } return true; }
[ "protected", "boolean", "isLeaf", "(", ")", "{", "for", "(", "int", "i", "=", "0", ";", "i", "<", "entries", ".", "length", ";", "i", "++", ")", "{", "Entry", "entry", "=", "entries", "[", "i", "]", ";", "if", "(", "entry", ".", "getChild", "(", ")", "!=", "null", ")", "{", "return", "false", ";", "}", "}", "return", "true", ";", "}" ]
Checks if this node is a leaf. A node is a leaf when none of the entries in the node have children. @return <code>true</code> if the node is leaf, <code>false</code> otherwise.
[ "Checks", "if", "this", "node", "is", "a", "leaf", ".", "A", "node", "is", "a", "leaf", "when", "none", "of", "the", "entries", "in", "the", "node", "have", "children", "." ]
395982e5100bfe75a3a4d26115462ce2cc74cbb0
https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/moa/clusterers/clustree/Node.java#L103-L113
28,871
Waikato/moa
moa/src/main/java/moa/clusterers/clustree/Node.java
Node.getNextEmptyPosition
private int getNextEmptyPosition(){ int counter; for (counter = 0; counter < entries.length; counter++) { Entry e = entries[counter]; if (e.isEmpty()) { break; } } if (counter == entries.length) { throw new RuntimeException("Entry added to a node which is already full."); } return counter; }
java
private int getNextEmptyPosition(){ int counter; for (counter = 0; counter < entries.length; counter++) { Entry e = entries[counter]; if (e.isEmpty()) { break; } } if (counter == entries.length) { throw new RuntimeException("Entry added to a node which is already full."); } return counter; }
[ "private", "int", "getNextEmptyPosition", "(", ")", "{", "int", "counter", ";", "for", "(", "counter", "=", "0", ";", "counter", "<", "entries", ".", "length", ";", "counter", "++", ")", "{", "Entry", "e", "=", "entries", "[", "counter", "]", ";", "if", "(", "e", ".", "isEmpty", "(", ")", ")", "{", "break", ";", "}", "}", "if", "(", "counter", "==", "entries", ".", "length", ")", "{", "throw", "new", "RuntimeException", "(", "\"Entry added to a node which is already full.\"", ")", ";", "}", "return", "counter", ";", "}" ]
Returns the position of the next free Entry. @return The position of the next free Entry. @throws NoFreeEntryException Is thrown when there is no free entry left in the node.
[ "Returns", "the", "position", "of", "the", "next", "free", "Entry", "." ]
395982e5100bfe75a3a4d26115462ce2cc74cbb0
https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/moa/clusterers/clustree/Node.java#L216-L230
28,872
Waikato/moa
moa/src/main/java/moa/gui/active/ALTaskTextViewerPanel.java
ALTaskTextViewerPanel.setText
public void setText(Preview preview) { Point p = this.scrollPaneTable.getViewport().getViewPosition(); previewTableModel.setPreview(preview); SwingUtilities.invokeLater( new Runnable(){ boolean structureChanged = previewTableModel.structureChanged(); public void run(){ if(!scrollPaneTable.isVisible()) { topWrapper.remove(scrollPaneText); scrollPaneText.setVisible(false); topWrapper.add(scrollPaneTable, BorderLayout.CENTER); scrollPaneTable.setVisible(true); topWrapper.validate(); } if(structureChanged) { previewTableModel.fireTableStructureChanged(); rescaleTableColumns(); } else { previewTableModel.fireTableDataChanged(); } previewTable.repaint(); } } ); this.scrollPaneTable.getViewport().setViewPosition(p); this.exportButton.setEnabled(preview != null); }
java
public void setText(Preview preview) { Point p = this.scrollPaneTable.getViewport().getViewPosition(); previewTableModel.setPreview(preview); SwingUtilities.invokeLater( new Runnable(){ boolean structureChanged = previewTableModel.structureChanged(); public void run(){ if(!scrollPaneTable.isVisible()) { topWrapper.remove(scrollPaneText); scrollPaneText.setVisible(false); topWrapper.add(scrollPaneTable, BorderLayout.CENTER); scrollPaneTable.setVisible(true); topWrapper.validate(); } if(structureChanged) { previewTableModel.fireTableStructureChanged(); rescaleTableColumns(); } else { previewTableModel.fireTableDataChanged(); } previewTable.repaint(); } } ); this.scrollPaneTable.getViewport().setViewPosition(p); this.exportButton.setEnabled(preview != null); }
[ "public", "void", "setText", "(", "Preview", "preview", ")", "{", "Point", "p", "=", "this", ".", "scrollPaneTable", ".", "getViewport", "(", ")", ".", "getViewPosition", "(", ")", ";", "previewTableModel", ".", "setPreview", "(", "preview", ")", ";", "SwingUtilities", ".", "invokeLater", "(", "new", "Runnable", "(", ")", "{", "boolean", "structureChanged", "=", "previewTableModel", ".", "structureChanged", "(", ")", ";", "public", "void", "run", "(", ")", "{", "if", "(", "!", "scrollPaneTable", ".", "isVisible", "(", ")", ")", "{", "topWrapper", ".", "remove", "(", "scrollPaneText", ")", ";", "scrollPaneText", ".", "setVisible", "(", "false", ")", ";", "topWrapper", ".", "add", "(", "scrollPaneTable", ",", "BorderLayout", ".", "CENTER", ")", ";", "scrollPaneTable", ".", "setVisible", "(", "true", ")", ";", "topWrapper", ".", "validate", "(", ")", ";", "}", "if", "(", "structureChanged", ")", "{", "previewTableModel", ".", "fireTableStructureChanged", "(", ")", ";", "rescaleTableColumns", "(", ")", ";", "}", "else", "{", "previewTableModel", ".", "fireTableDataChanged", "(", ")", ";", "}", "previewTable", ".", "repaint", "(", ")", ";", "}", "}", ")", ";", "this", ".", "scrollPaneTable", ".", "getViewport", "(", ")", ".", "setViewPosition", "(", "p", ")", ";", "this", ".", "exportButton", ".", "setEnabled", "(", "preview", "!=", "null", ")", ";", "}" ]
Updates the preview table based on the information given by preview. @param preview the new information used to update the table
[ "Updates", "the", "preview", "table", "based", "on", "the", "information", "given", "by", "preview", "." ]
395982e5100bfe75a3a4d26115462ce2cc74cbb0
https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/moa/gui/active/ALTaskTextViewerPanel.java#L475-L508
28,873
Waikato/moa
moa/src/main/java/moa/gui/active/ALTaskTextViewerPanel.java
ALTaskTextViewerPanel.readCollection
public ParsedPreview readCollection(PreviewCollection<Preview> pc) { ParsedPreview pp = new ParsedPreview(); List<Preview> sps = pc.getPreviews(); if (sps.size() > 0 && sps.get(0) instanceof PreviewCollection) { // members are PreviewCollections again // NOTE: this assumes that all elements in sps are of the same type for (Preview sp: sps) { @SuppressWarnings("unchecked") ParsedPreview tmp = readCollection((PreviewCollection<Preview>) sp); pp.add(tmp); } } else { // members are simple previews for (Preview sp: sps) { ParsedPreview tmp = read(sp); pp.add(tmp); } } return pp; }
java
public ParsedPreview readCollection(PreviewCollection<Preview> pc) { ParsedPreview pp = new ParsedPreview(); List<Preview> sps = pc.getPreviews(); if (sps.size() > 0 && sps.get(0) instanceof PreviewCollection) { // members are PreviewCollections again // NOTE: this assumes that all elements in sps are of the same type for (Preview sp: sps) { @SuppressWarnings("unchecked") ParsedPreview tmp = readCollection((PreviewCollection<Preview>) sp); pp.add(tmp); } } else { // members are simple previews for (Preview sp: sps) { ParsedPreview tmp = read(sp); pp.add(tmp); } } return pp; }
[ "public", "ParsedPreview", "readCollection", "(", "PreviewCollection", "<", "Preview", ">", "pc", ")", "{", "ParsedPreview", "pp", "=", "new", "ParsedPreview", "(", ")", ";", "List", "<", "Preview", ">", "sps", "=", "pc", ".", "getPreviews", "(", ")", ";", "if", "(", "sps", ".", "size", "(", ")", ">", "0", "&&", "sps", ".", "get", "(", "0", ")", "instanceof", "PreviewCollection", ")", "{", "// members are PreviewCollections again", "// NOTE: this assumes that all elements in sps are of the same type", "for", "(", "Preview", "sp", ":", "sps", ")", "{", "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "ParsedPreview", "tmp", "=", "readCollection", "(", "(", "PreviewCollection", "<", "Preview", ">", ")", "sp", ")", ";", "pp", ".", "add", "(", "tmp", ")", ";", "}", "}", "else", "{", "// members are simple previews", "for", "(", "Preview", "sp", ":", "sps", ")", "{", "ParsedPreview", "tmp", "=", "read", "(", "sp", ")", ";", "pp", ".", "add", "(", "tmp", ")", ";", "}", "}", "return", "pp", ";", "}" ]
Parses a PreviewCollection and return the resulting ParsedPreview object. If the PreviewCollection contains PreviewCollections again, it recursively adds their results. If it contains simple Previews, it adds their properties to the result. @param pc PreviewCollection @return relevant information contained in the PreviewCollection
[ "Parses", "a", "PreviewCollection", "and", "return", "the", "resulting", "ParsedPreview", "object", ".", "If", "the", "PreviewCollection", "contains", "PreviewCollections", "again", "it", "recursively", "adds", "their", "results", ".", "If", "it", "contains", "simple", "Previews", "it", "adds", "their", "properties", "to", "the", "result", "." ]
395982e5100bfe75a3a4d26115462ce2cc74cbb0
https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/moa/gui/active/ALTaskTextViewerPanel.java#L687-L708
28,874
Waikato/moa
moa/src/main/java/moa/gui/active/ALTaskTextViewerPanel.java
ALTaskTextViewerPanel.read
private ParsedPreview read(Preview p) { // find measure columns String[] measureNames = p.getMeasurementNames(); int numMeasures = p.getMeasurementNameCount(); int processFrequencyColumn = -1; int accuracyColumn = -1; int kappaColumn = -1; int kappaTempColumn = -1; int ramColumn = -1; int timeColumn = -1; int memoryColumn = -1; int budgetColumn = -1; for (int i = 0; i < numMeasures; i++) { switch (measureNames[i]) { case "learning evaluation instances": processFrequencyColumn = i; break; case "classifications correct (percent)": case "[avg] classifications correct (percent)": case "[std] classifications correct (percent)": accuracyColumn = i; break; case "Kappa Statistic (percent)": case "[avg] Kappa Statistic (percent)": case "[std] Kappa Statistic (percent)": kappaColumn = i; break; case "Kappa Temporal Statistic (percent)": case "[avg] Kappa Temporal Statistic (percent)": case "[std] Kappa Temporal Statistic (percent)": kappaTempColumn = i; break; case "model cost (RAM-Hours)": case "[std] model cost (RAM-Hours)": ramColumn = i; break; case "evaluation time (cpu seconds)": case "total train time": case "[std] evaluation time (cpu seconds)": timeColumn = i; break; case "model serialized size (bytes)": case "[std] model serialized size (bytes)": memoryColumn = i; break; case "Rel Number of Label Acquisitions": case "[std] Rel Number of Label Acquisitions": budgetColumn = i; break; default: break; } } List<double[]> data = p.getData(); MeasureCollection m = new ALMeasureCollection(); // set entries // TODO: obviously this should be changed into a dict for (double[] entry: data) { m.addValue(0, entry[accuracyColumn]); m.addValue(1, entry[kappaColumn]); m.addValue(2, entry[kappaTempColumn]); m.addValue(3, Math.abs(entry[ramColumn])); m.addValue(4, entry[timeColumn]); m.addValue(5, entry[memoryColumn] / (1024 * 1024)); m.addValue(6, entry[budgetColumn]); } // determine process frequency int processFrequency = (int) data.get(0)[processFrequencyColumn]; ParsedPreview pp = new ParsedPreview(); pp.addMeasureCollection(m); pp.addProcessFrequency(processFrequency); return pp; }
java
private ParsedPreview read(Preview p) { // find measure columns String[] measureNames = p.getMeasurementNames(); int numMeasures = p.getMeasurementNameCount(); int processFrequencyColumn = -1; int accuracyColumn = -1; int kappaColumn = -1; int kappaTempColumn = -1; int ramColumn = -1; int timeColumn = -1; int memoryColumn = -1; int budgetColumn = -1; for (int i = 0; i < numMeasures; i++) { switch (measureNames[i]) { case "learning evaluation instances": processFrequencyColumn = i; break; case "classifications correct (percent)": case "[avg] classifications correct (percent)": case "[std] classifications correct (percent)": accuracyColumn = i; break; case "Kappa Statistic (percent)": case "[avg] Kappa Statistic (percent)": case "[std] Kappa Statistic (percent)": kappaColumn = i; break; case "Kappa Temporal Statistic (percent)": case "[avg] Kappa Temporal Statistic (percent)": case "[std] Kappa Temporal Statistic (percent)": kappaTempColumn = i; break; case "model cost (RAM-Hours)": case "[std] model cost (RAM-Hours)": ramColumn = i; break; case "evaluation time (cpu seconds)": case "total train time": case "[std] evaluation time (cpu seconds)": timeColumn = i; break; case "model serialized size (bytes)": case "[std] model serialized size (bytes)": memoryColumn = i; break; case "Rel Number of Label Acquisitions": case "[std] Rel Number of Label Acquisitions": budgetColumn = i; break; default: break; } } List<double[]> data = p.getData(); MeasureCollection m = new ALMeasureCollection(); // set entries // TODO: obviously this should be changed into a dict for (double[] entry: data) { m.addValue(0, entry[accuracyColumn]); m.addValue(1, entry[kappaColumn]); m.addValue(2, entry[kappaTempColumn]); m.addValue(3, Math.abs(entry[ramColumn])); m.addValue(4, entry[timeColumn]); m.addValue(5, entry[memoryColumn] / (1024 * 1024)); m.addValue(6, entry[budgetColumn]); } // determine process frequency int processFrequency = (int) data.get(0)[processFrequencyColumn]; ParsedPreview pp = new ParsedPreview(); pp.addMeasureCollection(m); pp.addProcessFrequency(processFrequency); return pp; }
[ "private", "ParsedPreview", "read", "(", "Preview", "p", ")", "{", "// find measure columns", "String", "[", "]", "measureNames", "=", "p", ".", "getMeasurementNames", "(", ")", ";", "int", "numMeasures", "=", "p", ".", "getMeasurementNameCount", "(", ")", ";", "int", "processFrequencyColumn", "=", "-", "1", ";", "int", "accuracyColumn", "=", "-", "1", ";", "int", "kappaColumn", "=", "-", "1", ";", "int", "kappaTempColumn", "=", "-", "1", ";", "int", "ramColumn", "=", "-", "1", ";", "int", "timeColumn", "=", "-", "1", ";", "int", "memoryColumn", "=", "-", "1", ";", "int", "budgetColumn", "=", "-", "1", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "numMeasures", ";", "i", "++", ")", "{", "switch", "(", "measureNames", "[", "i", "]", ")", "{", "case", "\"learning evaluation instances\"", ":", "processFrequencyColumn", "=", "i", ";", "break", ";", "case", "\"classifications correct (percent)\"", ":", "case", "\"[avg] classifications correct (percent)\"", ":", "case", "\"[std] classifications correct (percent)\"", ":", "accuracyColumn", "=", "i", ";", "break", ";", "case", "\"Kappa Statistic (percent)\"", ":", "case", "\"[avg] Kappa Statistic (percent)\"", ":", "case", "\"[std] Kappa Statistic (percent)\"", ":", "kappaColumn", "=", "i", ";", "break", ";", "case", "\"Kappa Temporal Statistic (percent)\"", ":", "case", "\"[avg] Kappa Temporal Statistic (percent)\"", ":", "case", "\"[std] Kappa Temporal Statistic (percent)\"", ":", "kappaTempColumn", "=", "i", ";", "break", ";", "case", "\"model cost (RAM-Hours)\"", ":", "case", "\"[std] model cost (RAM-Hours)\"", ":", "ramColumn", "=", "i", ";", "break", ";", "case", "\"evaluation time (cpu seconds)\"", ":", "case", "\"total train time\"", ":", "case", "\"[std] evaluation time (cpu seconds)\"", ":", "timeColumn", "=", "i", ";", "break", ";", "case", "\"model serialized size (bytes)\"", ":", "case", "\"[std] model serialized size (bytes)\"", ":", "memoryColumn", "=", "i", ";", "break", ";", "case", "\"Rel Number of Label Acquisitions\"", ":", "case", "\"[std] Rel Number of Label Acquisitions\"", ":", "budgetColumn", "=", "i", ";", "break", ";", "default", ":", "break", ";", "}", "}", "List", "<", "double", "[", "]", ">", "data", "=", "p", ".", "getData", "(", ")", ";", "MeasureCollection", "m", "=", "new", "ALMeasureCollection", "(", ")", ";", "// set entries", "// TODO: obviously this should be changed into a dict", "for", "(", "double", "[", "]", "entry", ":", "data", ")", "{", "m", ".", "addValue", "(", "0", ",", "entry", "[", "accuracyColumn", "]", ")", ";", "m", ".", "addValue", "(", "1", ",", "entry", "[", "kappaColumn", "]", ")", ";", "m", ".", "addValue", "(", "2", ",", "entry", "[", "kappaTempColumn", "]", ")", ";", "m", ".", "addValue", "(", "3", ",", "Math", ".", "abs", "(", "entry", "[", "ramColumn", "]", ")", ")", ";", "m", ".", "addValue", "(", "4", ",", "entry", "[", "timeColumn", "]", ")", ";", "m", ".", "addValue", "(", "5", ",", "entry", "[", "memoryColumn", "]", "/", "(", "1024", "*", "1024", ")", ")", ";", "m", ".", "addValue", "(", "6", ",", "entry", "[", "budgetColumn", "]", ")", ";", "}", "// determine process frequency", "int", "processFrequency", "=", "(", "int", ")", "data", ".", "get", "(", "0", ")", "[", "processFrequencyColumn", "]", ";", "ParsedPreview", "pp", "=", "new", "ParsedPreview", "(", ")", ";", "pp", ".", "addMeasureCollection", "(", "m", ")", ";", "pp", ".", "addProcessFrequency", "(", "processFrequency", ")", ";", "return", "pp", ";", "}" ]
Parses a preview with respect to the process frequency and several measurements. @param preview
[ "Parses", "a", "preview", "with", "respect", "to", "the", "process", "frequency", "and", "several", "measurements", "." ]
395982e5100bfe75a3a4d26115462ce2cc74cbb0
https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/moa/gui/active/ALTaskTextViewerPanel.java#L766-L846
28,875
Waikato/moa
moa/src/main/java/moa/DoTask.java
DoTask.isJavaVersionOK
public static boolean isJavaVersionOK() { boolean isJavaVersionOK = true; String versionStr = System.getProperty("java.version"); String[] parts; double version; if (versionStr.contains(".")) { parts = versionStr.split("\\."); } else { parts = new String[]{versionStr}; } if (parts.length == 1) { try { version = Double.parseDouble(parts[0]); } catch (Exception e) { System.err.println("Unparsable Java version: " + versionStr); return false; } } else { try { version = Double.parseDouble(parts[0]) + Double.parseDouble(parts[1]) / 10; } catch (Exception e) { System.err.println("Unparsable Java version: " + versionStr); return false; } } if (version < 1.8) { isJavaVersionOK = false; System.err.println(); System.err.println(Globals.getWorkbenchInfoString()); System.err.println(); System.err.print("Java 8 or higher is required to run MOA. "); System.err.println("Java version " + versionStr + " found"); } return isJavaVersionOK; }
java
public static boolean isJavaVersionOK() { boolean isJavaVersionOK = true; String versionStr = System.getProperty("java.version"); String[] parts; double version; if (versionStr.contains(".")) { parts = versionStr.split("\\."); } else { parts = new String[]{versionStr}; } if (parts.length == 1) { try { version = Double.parseDouble(parts[0]); } catch (Exception e) { System.err.println("Unparsable Java version: " + versionStr); return false; } } else { try { version = Double.parseDouble(parts[0]) + Double.parseDouble(parts[1]) / 10; } catch (Exception e) { System.err.println("Unparsable Java version: " + versionStr); return false; } } if (version < 1.8) { isJavaVersionOK = false; System.err.println(); System.err.println(Globals.getWorkbenchInfoString()); System.err.println(); System.err.print("Java 8 or higher is required to run MOA. "); System.err.println("Java version " + versionStr + " found"); } return isJavaVersionOK; }
[ "public", "static", "boolean", "isJavaVersionOK", "(", ")", "{", "boolean", "isJavaVersionOK", "=", "true", ";", "String", "versionStr", "=", "System", ".", "getProperty", "(", "\"java.version\"", ")", ";", "String", "[", "]", "parts", ";", "double", "version", ";", "if", "(", "versionStr", ".", "contains", "(", "\".\"", ")", ")", "{", "parts", "=", "versionStr", ".", "split", "(", "\"\\\\.\"", ")", ";", "}", "else", "{", "parts", "=", "new", "String", "[", "]", "{", "versionStr", "}", ";", "}", "if", "(", "parts", ".", "length", "==", "1", ")", "{", "try", "{", "version", "=", "Double", ".", "parseDouble", "(", "parts", "[", "0", "]", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "System", ".", "err", ".", "println", "(", "\"Unparsable Java version: \"", "+", "versionStr", ")", ";", "return", "false", ";", "}", "}", "else", "{", "try", "{", "version", "=", "Double", ".", "parseDouble", "(", "parts", "[", "0", "]", ")", "+", "Double", ".", "parseDouble", "(", "parts", "[", "1", "]", ")", "/", "10", ";", "}", "catch", "(", "Exception", "e", ")", "{", "System", ".", "err", ".", "println", "(", "\"Unparsable Java version: \"", "+", "versionStr", ")", ";", "return", "false", ";", "}", "}", "if", "(", "version", "<", "1.8", ")", "{", "isJavaVersionOK", "=", "false", ";", "System", ".", "err", ".", "println", "(", ")", ";", "System", ".", "err", ".", "println", "(", "Globals", ".", "getWorkbenchInfoString", "(", ")", ")", ";", "System", ".", "err", ".", "println", "(", ")", ";", "System", ".", "err", ".", "print", "(", "\"Java 8 or higher is required to run MOA. \"", ")", ";", "System", ".", "err", ".", "println", "(", "\"Java version \"", "+", "versionStr", "+", "\" found\"", ")", ";", "}", "return", "isJavaVersionOK", ";", "}" ]
Checks if the Java version is recent enough to run MOA. @return true if the Java version is recent.
[ "Checks", "if", "the", "Java", "version", "is", "recent", "enough", "to", "run", "MOA", "." ]
395982e5100bfe75a3a4d26115462ce2cc74cbb0
https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/moa/DoTask.java#L59-L97
28,876
Waikato/moa
moa/src/main/java/moa/classifiers/meta/AccuracyWeightedEnsemble.java
AccuracyWeightedEnsemble.computeCandidateWeight
protected double computeCandidateWeight(Classifier candidate, Instances chunk, int numFolds) { double candidateWeight = 0.0; Random random = new Random(1); Instances randData = new Instances(chunk); randData.randomize(random); if (randData.classAttribute().isNominal()) { randData.stratify(numFolds); } for (int n = 0; n < numFolds; n++) { Instances train = randData.trainCV(numFolds, n, random); Instances test = randData.testCV(numFolds, n); Classifier learner = candidate.copy(); for (int num = 0; num < train.numInstances(); num++) { learner.trainOnInstance(train.instance(num)); } candidateWeight += computeWeight(learner, test); } double resultWeight = candidateWeight / numFolds; if (Double.isInfinite(resultWeight)) { return Double.MAX_VALUE; } else { return resultWeight; } }
java
protected double computeCandidateWeight(Classifier candidate, Instances chunk, int numFolds) { double candidateWeight = 0.0; Random random = new Random(1); Instances randData = new Instances(chunk); randData.randomize(random); if (randData.classAttribute().isNominal()) { randData.stratify(numFolds); } for (int n = 0; n < numFolds; n++) { Instances train = randData.trainCV(numFolds, n, random); Instances test = randData.testCV(numFolds, n); Classifier learner = candidate.copy(); for (int num = 0; num < train.numInstances(); num++) { learner.trainOnInstance(train.instance(num)); } candidateWeight += computeWeight(learner, test); } double resultWeight = candidateWeight / numFolds; if (Double.isInfinite(resultWeight)) { return Double.MAX_VALUE; } else { return resultWeight; } }
[ "protected", "double", "computeCandidateWeight", "(", "Classifier", "candidate", ",", "Instances", "chunk", ",", "int", "numFolds", ")", "{", "double", "candidateWeight", "=", "0.0", ";", "Random", "random", "=", "new", "Random", "(", "1", ")", ";", "Instances", "randData", "=", "new", "Instances", "(", "chunk", ")", ";", "randData", ".", "randomize", "(", "random", ")", ";", "if", "(", "randData", ".", "classAttribute", "(", ")", ".", "isNominal", "(", ")", ")", "{", "randData", ".", "stratify", "(", "numFolds", ")", ";", "}", "for", "(", "int", "n", "=", "0", ";", "n", "<", "numFolds", ";", "n", "++", ")", "{", "Instances", "train", "=", "randData", ".", "trainCV", "(", "numFolds", ",", "n", ",", "random", ")", ";", "Instances", "test", "=", "randData", ".", "testCV", "(", "numFolds", ",", "n", ")", ";", "Classifier", "learner", "=", "candidate", ".", "copy", "(", ")", ";", "for", "(", "int", "num", "=", "0", ";", "num", "<", "train", ".", "numInstances", "(", ")", ";", "num", "++", ")", "{", "learner", ".", "trainOnInstance", "(", "train", ".", "instance", "(", "num", ")", ")", ";", "}", "candidateWeight", "+=", "computeWeight", "(", "learner", ",", "test", ")", ";", "}", "double", "resultWeight", "=", "candidateWeight", "/", "numFolds", ";", "if", "(", "Double", ".", "isInfinite", "(", "resultWeight", ")", ")", "{", "return", "Double", ".", "MAX_VALUE", ";", "}", "else", "{", "return", "resultWeight", ";", "}", "}" ]
Computes the weight of a candidate classifier. @param candidate Candidate classifier. @param chunk Data chunk of examples. @param numFolds Number of folds in candidate classifier cross-validation. @param useMseR Determines whether to use the MSEr threshold. @return Candidate classifier weight.
[ "Computes", "the", "weight", "of", "a", "candidate", "classifier", "." ]
395982e5100bfe75a3a4d26115462ce2cc74cbb0
https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/moa/classifiers/meta/AccuracyWeightedEnsemble.java#L247-L276
28,877
Waikato/moa
moa/src/main/java/moa/classifiers/meta/AccuracyWeightedEnsemble.java
AccuracyWeightedEnsemble.computeWeight
protected double computeWeight(Classifier learner, Instances chunk) { double mse_i = 0; double mse_r = 0; double f_ci; double voteSum; for (int i = 0; i < chunk.numInstances(); i++) { try { voteSum = 0; for (double element : learner.getVotesForInstance(chunk.instance(i))) { voteSum += element; } if (voteSum > 0) { f_ci = learner.getVotesForInstance(chunk.instance(i))[(int) chunk.instance(i).classValue()] / voteSum; mse_i += (1 - f_ci) * (1 - f_ci); } else { mse_i += 1; } } catch (Exception e) { mse_i += 1; } } mse_i /= this.chunkSize; mse_r = this.computeMseR(); return java.lang.Math.max(mse_r - mse_i, 0); }
java
protected double computeWeight(Classifier learner, Instances chunk) { double mse_i = 0; double mse_r = 0; double f_ci; double voteSum; for (int i = 0; i < chunk.numInstances(); i++) { try { voteSum = 0; for (double element : learner.getVotesForInstance(chunk.instance(i))) { voteSum += element; } if (voteSum > 0) { f_ci = learner.getVotesForInstance(chunk.instance(i))[(int) chunk.instance(i).classValue()] / voteSum; mse_i += (1 - f_ci) * (1 - f_ci); } else { mse_i += 1; } } catch (Exception e) { mse_i += 1; } } mse_i /= this.chunkSize; mse_r = this.computeMseR(); return java.lang.Math.max(mse_r - mse_i, 0); }
[ "protected", "double", "computeWeight", "(", "Classifier", "learner", ",", "Instances", "chunk", ")", "{", "double", "mse_i", "=", "0", ";", "double", "mse_r", "=", "0", ";", "double", "f_ci", ";", "double", "voteSum", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "chunk", ".", "numInstances", "(", ")", ";", "i", "++", ")", "{", "try", "{", "voteSum", "=", "0", ";", "for", "(", "double", "element", ":", "learner", ".", "getVotesForInstance", "(", "chunk", ".", "instance", "(", "i", ")", ")", ")", "{", "voteSum", "+=", "element", ";", "}", "if", "(", "voteSum", ">", "0", ")", "{", "f_ci", "=", "learner", ".", "getVotesForInstance", "(", "chunk", ".", "instance", "(", "i", ")", ")", "[", "(", "int", ")", "chunk", ".", "instance", "(", "i", ")", ".", "classValue", "(", ")", "]", "/", "voteSum", ";", "mse_i", "+=", "(", "1", "-", "f_ci", ")", "*", "(", "1", "-", "f_ci", ")", ";", "}", "else", "{", "mse_i", "+=", "1", ";", "}", "}", "catch", "(", "Exception", "e", ")", "{", "mse_i", "+=", "1", ";", "}", "}", "mse_i", "/=", "this", ".", "chunkSize", ";", "mse_r", "=", "this", ".", "computeMseR", "(", ")", ";", "return", "java", ".", "lang", ".", "Math", ".", "max", "(", "mse_r", "-", "mse_i", ",", "0", ")", ";", "}" ]
Computes the weight of a given classifie. @param learner Classifier to calculate weight for. @param chunk Data chunk of examples. @param useMseR Determines whether to use the MSEr threshold. @return The given classifier's weight.
[ "Computes", "the", "weight", "of", "a", "given", "classifie", "." ]
395982e5100bfe75a3a4d26115462ce2cc74cbb0
https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/moa/classifiers/meta/AccuracyWeightedEnsemble.java#L286-L315
28,878
Waikato/moa
moa/src/main/java/moa/classifiers/meta/AccuracyWeightedEnsemble.java
AccuracyWeightedEnsemble.getVotesForInstance
public double[] getVotesForInstance(Instance inst) { DoubleVector combinedVote = new DoubleVector(); if (this.trainingWeightSeenByModel > 0.0) { for (int i = 0; i < this.ensemble.length; i++) { if (this.ensembleWeights[i] > 0.0) { DoubleVector vote = new DoubleVector(this.ensemble[i].getVotesForInstance(inst)); if (vote.sumOfValues() > 0.0) { vote.normalize(); //scale weight and prevent overflow vote.scaleValues(this.ensembleWeights[i] / (1.0 * this.ensemble.length + 1)); combinedVote.addValues(vote); } } } } combinedVote.normalize(); return combinedVote.getArrayRef(); }
java
public double[] getVotesForInstance(Instance inst) { DoubleVector combinedVote = new DoubleVector(); if (this.trainingWeightSeenByModel > 0.0) { for (int i = 0; i < this.ensemble.length; i++) { if (this.ensembleWeights[i] > 0.0) { DoubleVector vote = new DoubleVector(this.ensemble[i].getVotesForInstance(inst)); if (vote.sumOfValues() > 0.0) { vote.normalize(); //scale weight and prevent overflow vote.scaleValues(this.ensembleWeights[i] / (1.0 * this.ensemble.length + 1)); combinedVote.addValues(vote); } } } } combinedVote.normalize(); return combinedVote.getArrayRef(); }
[ "public", "double", "[", "]", "getVotesForInstance", "(", "Instance", "inst", ")", "{", "DoubleVector", "combinedVote", "=", "new", "DoubleVector", "(", ")", ";", "if", "(", "this", ".", "trainingWeightSeenByModel", ">", "0.0", ")", "{", "for", "(", "int", "i", "=", "0", ";", "i", "<", "this", ".", "ensemble", ".", "length", ";", "i", "++", ")", "{", "if", "(", "this", ".", "ensembleWeights", "[", "i", "]", ">", "0.0", ")", "{", "DoubleVector", "vote", "=", "new", "DoubleVector", "(", "this", ".", "ensemble", "[", "i", "]", ".", "getVotesForInstance", "(", "inst", ")", ")", ";", "if", "(", "vote", ".", "sumOfValues", "(", ")", ">", "0.0", ")", "{", "vote", ".", "normalize", "(", ")", ";", "//scale weight and prevent overflow", "vote", ".", "scaleValues", "(", "this", ".", "ensembleWeights", "[", "i", "]", "/", "(", "1.0", "*", "this", ".", "ensemble", ".", "length", "+", "1", ")", ")", ";", "combinedVote", ".", "addValues", "(", "vote", ")", ";", "}", "}", "}", "}", "combinedVote", ".", "normalize", "(", ")", ";", "return", "combinedVote", ".", "getArrayRef", "(", ")", ";", "}" ]
Predicts a class for an example.
[ "Predicts", "a", "class", "for", "an", "example", "." ]
395982e5100bfe75a3a4d26115462ce2cc74cbb0
https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/moa/classifiers/meta/AccuracyWeightedEnsemble.java#L337-L356
28,879
Waikato/moa
moa/src/main/java/moa/classifiers/meta/AccuracyWeightedEnsemble.java
AccuracyWeightedEnsemble.removePoorestModelBytes
protected int removePoorestModelBytes() { int poorestIndex = Utils.minIndex(this.ensembleWeights); int byteSize = this.ensemble[poorestIndex].measureByteSize(); discardModel(poorestIndex); return byteSize; }
java
protected int removePoorestModelBytes() { int poorestIndex = Utils.minIndex(this.ensembleWeights); int byteSize = this.ensemble[poorestIndex].measureByteSize(); discardModel(poorestIndex); return byteSize; }
[ "protected", "int", "removePoorestModelBytes", "(", ")", "{", "int", "poorestIndex", "=", "Utils", ".", "minIndex", "(", "this", ".", "ensembleWeights", ")", ";", "int", "byteSize", "=", "this", ".", "ensemble", "[", "poorestIndex", "]", ".", "measureByteSize", "(", ")", ";", "discardModel", "(", "poorestIndex", ")", ";", "return", "byteSize", ";", "}" ]
Removes the poorest classifier from the model, thus decreasing the models size. @return the size of the removed classifier.
[ "Removes", "the", "poorest", "classifier", "from", "the", "model", "thus", "decreasing", "the", "models", "size", "." ]
395982e5100bfe75a3a4d26115462ce2cc74cbb0
https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/moa/classifiers/meta/AccuracyWeightedEnsemble.java#L437-L442
28,880
Waikato/moa
moa/src/main/java/moa/clusterers/outliers/AnyOut/util/EMTopDownTreeBuilder.java
EMTopDownTreeBuilder.splitDataSetUsingEM
private DataSet[] splitDataSetUsingEM(DataSet dataSet, int nrOfPartitions) throws Exception { if (dataSet.size() <= 1) throw new Exception("EMsplit needs at least 2 objects!"); EMProjectedClustering myEM = new EMProjectedClustering(); // iterate several times and take best solution int nrOfIterations = 1; // maximum --> 10 iterations // 10^2 objects --> 8 iterations // 10^6 objects --> 4 iteration // minimum --> 2 iterations // // #iterations = max{1, (10 - log_10(#objects)) } double log10 = Math.log(dataSet.size()*1.0)/Math.log(10.0); nrOfIterations = Math.max(1, (10 - ((Long) Math.round(log10)).intValue())); nrOfIterations = Math.min(10, nrOfIterations); int[][] emMapping = myEM.getEMClusteringVariancesBestChoice(dataSet.getFeaturesAsArray(), nrOfPartitions, nrOfIterations); DataSet[] subDataSets = new DataSet[emMapping.length]; for (int i = 0; i < subDataSets.length; i++) { subDataSets[i] = new DataSet(dataSet.getNrOfDimensions()); for (int j = 0; j < emMapping[i].length; j++) { subDataSets[i].addObject(dataSet.getObject(emMapping[i][j])); } } //////////////////////////////////////////////////////////////// // the EM part ends here // now we try to create at least 2 partitions // and make sure that each partition contains at least 2 objects //////////////////////////////////////////////////////////////// if (subDataSets.length < 2) { System.out.println("mean shift split"); subDataSets = splitDataSetUsingMeanShift(dataSet); } // decide what to do with kernels in inner nodes // by default they are allowed, i.e. no changes are made if the case occurs boolean changes = !ALLOW_KERNELS_IN_INNER_NODES; while (changes) { changes = false; for (int i = 0; i < subDataSets.length; i++) { if (subDataSets[i].size() == 1) { System.out.println("merge singular sets"); subDataSets = mergeDataSets(subDataSets, i); changes = true; break; } } } return subDataSets; }
java
private DataSet[] splitDataSetUsingEM(DataSet dataSet, int nrOfPartitions) throws Exception { if (dataSet.size() <= 1) throw new Exception("EMsplit needs at least 2 objects!"); EMProjectedClustering myEM = new EMProjectedClustering(); // iterate several times and take best solution int nrOfIterations = 1; // maximum --> 10 iterations // 10^2 objects --> 8 iterations // 10^6 objects --> 4 iteration // minimum --> 2 iterations // // #iterations = max{1, (10 - log_10(#objects)) } double log10 = Math.log(dataSet.size()*1.0)/Math.log(10.0); nrOfIterations = Math.max(1, (10 - ((Long) Math.round(log10)).intValue())); nrOfIterations = Math.min(10, nrOfIterations); int[][] emMapping = myEM.getEMClusteringVariancesBestChoice(dataSet.getFeaturesAsArray(), nrOfPartitions, nrOfIterations); DataSet[] subDataSets = new DataSet[emMapping.length]; for (int i = 0; i < subDataSets.length; i++) { subDataSets[i] = new DataSet(dataSet.getNrOfDimensions()); for (int j = 0; j < emMapping[i].length; j++) { subDataSets[i].addObject(dataSet.getObject(emMapping[i][j])); } } //////////////////////////////////////////////////////////////// // the EM part ends here // now we try to create at least 2 partitions // and make sure that each partition contains at least 2 objects //////////////////////////////////////////////////////////////// if (subDataSets.length < 2) { System.out.println("mean shift split"); subDataSets = splitDataSetUsingMeanShift(dataSet); } // decide what to do with kernels in inner nodes // by default they are allowed, i.e. no changes are made if the case occurs boolean changes = !ALLOW_KERNELS_IN_INNER_NODES; while (changes) { changes = false; for (int i = 0; i < subDataSets.length; i++) { if (subDataSets[i].size() == 1) { System.out.println("merge singular sets"); subDataSets = mergeDataSets(subDataSets, i); changes = true; break; } } } return subDataSets; }
[ "private", "DataSet", "[", "]", "splitDataSetUsingEM", "(", "DataSet", "dataSet", ",", "int", "nrOfPartitions", ")", "throws", "Exception", "{", "if", "(", "dataSet", ".", "size", "(", ")", "<=", "1", ")", "throw", "new", "Exception", "(", "\"EMsplit needs at least 2 objects!\"", ")", ";", "EMProjectedClustering", "myEM", "=", "new", "EMProjectedClustering", "(", ")", ";", "// iterate several times and take best solution\r", "int", "nrOfIterations", "=", "1", ";", "// maximum --> 10 iterations\r", "// 10^2 objects --> 8 iterations\r", "// 10^6 objects --> 4 iteration\r", "// minimum --> 2 iterations\r", "//\r", "// #iterations = max{1, (10 - log_10(#objects)) }\r", "double", "log10", "=", "Math", ".", "log", "(", "dataSet", ".", "size", "(", ")", "*", "1.0", ")", "/", "Math", ".", "log", "(", "10.0", ")", ";", "nrOfIterations", "=", "Math", ".", "max", "(", "1", ",", "(", "10", "-", "(", "(", "Long", ")", "Math", ".", "round", "(", "log10", ")", ")", ".", "intValue", "(", ")", ")", ")", ";", "nrOfIterations", "=", "Math", ".", "min", "(", "10", ",", "nrOfIterations", ")", ";", "int", "[", "]", "[", "]", "emMapping", "=", "myEM", ".", "getEMClusteringVariancesBestChoice", "(", "dataSet", ".", "getFeaturesAsArray", "(", ")", ",", "nrOfPartitions", ",", "nrOfIterations", ")", ";", "DataSet", "[", "]", "subDataSets", "=", "new", "DataSet", "[", "emMapping", ".", "length", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "subDataSets", ".", "length", ";", "i", "++", ")", "{", "subDataSets", "[", "i", "]", "=", "new", "DataSet", "(", "dataSet", ".", "getNrOfDimensions", "(", ")", ")", ";", "for", "(", "int", "j", "=", "0", ";", "j", "<", "emMapping", "[", "i", "]", ".", "length", ";", "j", "++", ")", "{", "subDataSets", "[", "i", "]", ".", "addObject", "(", "dataSet", ".", "getObject", "(", "emMapping", "[", "i", "]", "[", "j", "]", ")", ")", ";", "}", "}", "////////////////////////////////////////////////////////////////\r", "// the EM part ends here\r", "// now we try to create at least 2 partitions\r", "// and make sure that each partition contains at least 2 objects\r", "////////////////////////////////////////////////////////////////\r", "if", "(", "subDataSets", ".", "length", "<", "2", ")", "{", "System", ".", "out", ".", "println", "(", "\"mean shift split\"", ")", ";", "subDataSets", "=", "splitDataSetUsingMeanShift", "(", "dataSet", ")", ";", "}", "// decide what to do with kernels in inner nodes\r", "// by default they are allowed, i.e. no changes are made if the case occurs\r", "boolean", "changes", "=", "!", "ALLOW_KERNELS_IN_INNER_NODES", ";", "while", "(", "changes", ")", "{", "changes", "=", "false", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "subDataSets", ".", "length", ";", "i", "++", ")", "{", "if", "(", "subDataSets", "[", "i", "]", ".", "size", "(", ")", "==", "1", ")", "{", "System", ".", "out", ".", "println", "(", "\"merge singular sets\"", ")", ";", "subDataSets", "=", "mergeDataSets", "(", "subDataSets", ",", "i", ")", ";", "changes", "=", "true", ";", "break", ";", "}", "}", "}", "return", "subDataSets", ";", "}" ]
This methods splits the given data set into partitions using the EM algorithm. The resulting number of partitions is <= nrOfPartitions. If EM returns only one partition, the data set is split using mean shift. The size of each resulting partition is AT LEAST 2, i.e. partitions with size 1 are merged with the closest remaining partition. Hence, this method might return only one partition containing the whole data set. @param dataSet @param nrOfPartitions @return an array of DataSets containing the partitions (minimal 1, maximal nrOfPartitions) @throws Exception
[ "This", "methods", "splits", "the", "given", "data", "set", "into", "partitions", "using", "the", "EM", "algorithm", ".", "The", "resulting", "number", "of", "partitions", "is", "<", "=", "nrOfPartitions", ".", "If", "EM", "returns", "only", "one", "partition", "the", "data", "set", "is", "split", "using", "mean", "shift", ".", "The", "size", "of", "each", "resulting", "partition", "is", "AT", "LEAST", "2", "i", ".", "e", ".", "partitions", "with", "size", "1", "are", "merged", "with", "the", "closest", "remaining", "partition", ".", "Hence", "this", "method", "might", "return", "only", "one", "partition", "containing", "the", "whole", "data", "set", "." ]
395982e5100bfe75a3a4d26115462ce2cc74cbb0
https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/moa/clusterers/outliers/AnyOut/util/EMTopDownTreeBuilder.java#L158-L208
28,881
Waikato/moa
moa/src/main/java/moa/clusterers/streamkm/MTRandom.java
MTRandom.setSeed
private final void setSeed(int seed) { // Annoying runtime check for initialisation of internal data // caused by java.util.Random invoking setSeed() during init. // This is unavoidable because no fields in our instance will // have been initialised at this point, not even if the code // were placed at the declaration of the member variable. if (mt == null) mt = new int[N]; // ---- Begin Mersenne Twister Algorithm ---- mt[0] = seed; for (mti = 1; mti < N; mti++) { mt[mti] = (MAGIC_FACTOR1 * (mt[mti-1] ^ (mt[mti-1] >>> 30)) + mti); } // ---- End Mersenne Twister Algorithm ---- }
java
private final void setSeed(int seed) { // Annoying runtime check for initialisation of internal data // caused by java.util.Random invoking setSeed() during init. // This is unavoidable because no fields in our instance will // have been initialised at this point, not even if the code // were placed at the declaration of the member variable. if (mt == null) mt = new int[N]; // ---- Begin Mersenne Twister Algorithm ---- mt[0] = seed; for (mti = 1; mti < N; mti++) { mt[mti] = (MAGIC_FACTOR1 * (mt[mti-1] ^ (mt[mti-1] >>> 30)) + mti); } // ---- End Mersenne Twister Algorithm ---- }
[ "private", "final", "void", "setSeed", "(", "int", "seed", ")", "{", "// Annoying runtime check for initialisation of internal data", "// caused by java.util.Random invoking setSeed() during init.", "// This is unavoidable because no fields in our instance will", "// have been initialised at this point, not even if the code", "// were placed at the declaration of the member variable.", "if", "(", "mt", "==", "null", ")", "mt", "=", "new", "int", "[", "N", "]", ";", "// ---- Begin Mersenne Twister Algorithm ----", "mt", "[", "0", "]", "=", "seed", ";", "for", "(", "mti", "=", "1", ";", "mti", "<", "N", ";", "mti", "++", ")", "{", "mt", "[", "mti", "]", "=", "(", "MAGIC_FACTOR1", "*", "(", "mt", "[", "mti", "-", "1", "]", "^", "(", "mt", "[", "mti", "-", "1", "]", ">>>", "30", ")", ")", "+", "mti", ")", ";", "}", "// ---- End Mersenne Twister Algorithm ----", "}" ]
not be made public.
[ "not", "be", "made", "public", "." ]
395982e5100bfe75a3a4d26115462ce2cc74cbb0
https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/moa/clusterers/streamkm/MTRandom.java#L193-L208
28,882
Waikato/moa
moa/src/main/java/moa/clusterers/streamkm/MTRandom.java
MTRandom.setSeed
public final synchronized void setSeed(int[] buf) { int length = buf.length; if (length == 0) throw new IllegalArgumentException("Seed buffer may not be empty"); // ---- Begin Mersenne Twister Algorithm ---- int i = 1, j = 0, k = (N > length ? N : length); setSeed(MAGIC_SEED); for (; k > 0; k--) { mt[i] = (mt[i] ^ ((mt[i-1] ^ (mt[i-1] >>> 30)) * MAGIC_FACTOR2)) + buf[j] + j; i++; j++; if (i >= N) { mt[0] = mt[N-1]; i = 1; } if (j >= length) j = 0; } for (k = N-1; k > 0; k--) { mt[i] = (mt[i] ^ ((mt[i-1] ^ (mt[i-1] >>> 30)) * MAGIC_FACTOR3)) - i; i++; if (i >= N) { mt[0] = mt[N-1]; i = 1; } } mt[0] = UPPER_MASK; // MSB is 1; assuring non-zero initial array // ---- End Mersenne Twister Algorithm ---- }
java
public final synchronized void setSeed(int[] buf) { int length = buf.length; if (length == 0) throw new IllegalArgumentException("Seed buffer may not be empty"); // ---- Begin Mersenne Twister Algorithm ---- int i = 1, j = 0, k = (N > length ? N : length); setSeed(MAGIC_SEED); for (; k > 0; k--) { mt[i] = (mt[i] ^ ((mt[i-1] ^ (mt[i-1] >>> 30)) * MAGIC_FACTOR2)) + buf[j] + j; i++; j++; if (i >= N) { mt[0] = mt[N-1]; i = 1; } if (j >= length) j = 0; } for (k = N-1; k > 0; k--) { mt[i] = (mt[i] ^ ((mt[i-1] ^ (mt[i-1] >>> 30)) * MAGIC_FACTOR3)) - i; i++; if (i >= N) { mt[0] = mt[N-1]; i = 1; } } mt[0] = UPPER_MASK; // MSB is 1; assuring non-zero initial array // ---- End Mersenne Twister Algorithm ---- }
[ "public", "final", "synchronized", "void", "setSeed", "(", "int", "[", "]", "buf", ")", "{", "int", "length", "=", "buf", ".", "length", ";", "if", "(", "length", "==", "0", ")", "throw", "new", "IllegalArgumentException", "(", "\"Seed buffer may not be empty\"", ")", ";", "// ---- Begin Mersenne Twister Algorithm ----", "int", "i", "=", "1", ",", "j", "=", "0", ",", "k", "=", "(", "N", ">", "length", "?", "N", ":", "length", ")", ";", "setSeed", "(", "MAGIC_SEED", ")", ";", "for", "(", ";", "k", ">", "0", ";", "k", "--", ")", "{", "mt", "[", "i", "]", "=", "(", "mt", "[", "i", "]", "^", "(", "(", "mt", "[", "i", "-", "1", "]", "^", "(", "mt", "[", "i", "-", "1", "]", ">>>", "30", ")", ")", "*", "MAGIC_FACTOR2", ")", ")", "+", "buf", "[", "j", "]", "+", "j", ";", "i", "++", ";", "j", "++", ";", "if", "(", "i", ">=", "N", ")", "{", "mt", "[", "0", "]", "=", "mt", "[", "N", "-", "1", "]", ";", "i", "=", "1", ";", "}", "if", "(", "j", ">=", "length", ")", "j", "=", "0", ";", "}", "for", "(", "k", "=", "N", "-", "1", ";", "k", ">", "0", ";", "k", "--", ")", "{", "mt", "[", "i", "]", "=", "(", "mt", "[", "i", "]", "^", "(", "(", "mt", "[", "i", "-", "1", "]", "^", "(", "mt", "[", "i", "-", "1", "]", ">>>", "30", ")", ")", "*", "MAGIC_FACTOR3", ")", ")", "-", "i", ";", "i", "++", ";", "if", "(", "i", ">=", "N", ")", "{", "mt", "[", "0", "]", "=", "mt", "[", "N", "-", "1", "]", ";", "i", "=", "1", ";", "}", "}", "mt", "[", "0", "]", "=", "UPPER_MASK", ";", "// MSB is 1; assuring non-zero initial array", "// ---- End Mersenne Twister Algorithm ----", "}" ]
This method resets the state of this instance using the integer array of seed data provided. This is the canonical way of resetting the pseudo random number sequence. @param buf The non-empty integer array of seed information. @throws NullPointerException if the buffer is null. @throws IllegalArgumentException if the buffer has zero length.
[ "This", "method", "resets", "the", "state", "of", "this", "instance", "using", "the", "integer", "array", "of", "seed", "data", "provided", ".", "This", "is", "the", "canonical", "way", "of", "resetting", "the", "pseudo", "random", "number", "sequence", "." ]
395982e5100bfe75a3a4d26115462ce2cc74cbb0
https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/moa/clusterers/streamkm/MTRandom.java#L272-L291
28,883
Waikato/moa
moa/src/main/java/moa/core/AutoClassDiscovery.java
AutoClassDiscovery.initCache
protected static synchronized void initCache() { if (m_Cache == null) { m_Cache = new ClassCache(); // failed to locate any classes on the classpath, maybe inside Weka? // try loading fixed list of classes if (m_Cache.isEmpty()) { InputStream inputStream = null; try { inputStream = m_Cache.getClass().getResourceAsStream(CLASS_LIST); m_Cache = new ClassCache(new FixedClassListTraversal(inputStream)); } catch (Exception e) { System.err.println("Failed to initialize class cache from fixed list (" + CLASS_LIST + ")!"); e.printStackTrace(); } finally { if (inputStream != null) { try { inputStream.close(); } catch (Exception e) { // ignored } } } } } }
java
protected static synchronized void initCache() { if (m_Cache == null) { m_Cache = new ClassCache(); // failed to locate any classes on the classpath, maybe inside Weka? // try loading fixed list of classes if (m_Cache.isEmpty()) { InputStream inputStream = null; try { inputStream = m_Cache.getClass().getResourceAsStream(CLASS_LIST); m_Cache = new ClassCache(new FixedClassListTraversal(inputStream)); } catch (Exception e) { System.err.println("Failed to initialize class cache from fixed list (" + CLASS_LIST + ")!"); e.printStackTrace(); } finally { if (inputStream != null) { try { inputStream.close(); } catch (Exception e) { // ignored } } } } } }
[ "protected", "static", "synchronized", "void", "initCache", "(", ")", "{", "if", "(", "m_Cache", "==", "null", ")", "{", "m_Cache", "=", "new", "ClassCache", "(", ")", ";", "// failed to locate any classes on the classpath, maybe inside Weka?", "// try loading fixed list of classes", "if", "(", "m_Cache", ".", "isEmpty", "(", ")", ")", "{", "InputStream", "inputStream", "=", "null", ";", "try", "{", "inputStream", "=", "m_Cache", ".", "getClass", "(", ")", ".", "getResourceAsStream", "(", "CLASS_LIST", ")", ";", "m_Cache", "=", "new", "ClassCache", "(", "new", "FixedClassListTraversal", "(", "inputStream", ")", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "System", ".", "err", ".", "println", "(", "\"Failed to initialize class cache from fixed list (\"", "+", "CLASS_LIST", "+", "\")!\"", ")", ";", "e", ".", "printStackTrace", "(", ")", ";", "}", "finally", "{", "if", "(", "inputStream", "!=", "null", ")", "{", "try", "{", "inputStream", ".", "close", "(", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "// ignored", "}", "}", "}", "}", "}", "}" ]
Initializes the class cache
[ "Initializes", "the", "class", "cache" ]
395982e5100bfe75a3a4d26115462ce2cc74cbb0
https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/moa/core/AutoClassDiscovery.java#L57-L84
28,884
Waikato/moa
moa/src/main/java/moa/core/AutoClassDiscovery.java
AutoClassDiscovery.getAllClassNames
public static List<String> getAllClassNames() { List<String> result = new ArrayList<>(); Iterator<String> pkgs = m_Cache.packages(); while (pkgs.hasNext()) { String pkg = pkgs.next(); if (pkg.startsWith("moa")) { Set<String> classnames = m_Cache.getClassnames(pkg); result.addAll(classnames); } } return result; }
java
public static List<String> getAllClassNames() { List<String> result = new ArrayList<>(); Iterator<String> pkgs = m_Cache.packages(); while (pkgs.hasNext()) { String pkg = pkgs.next(); if (pkg.startsWith("moa")) { Set<String> classnames = m_Cache.getClassnames(pkg); result.addAll(classnames); } } return result; }
[ "public", "static", "List", "<", "String", ">", "getAllClassNames", "(", ")", "{", "List", "<", "String", ">", "result", "=", "new", "ArrayList", "<>", "(", ")", ";", "Iterator", "<", "String", ">", "pkgs", "=", "m_Cache", ".", "packages", "(", ")", ";", "while", "(", "pkgs", ".", "hasNext", "(", ")", ")", "{", "String", "pkg", "=", "pkgs", ".", "next", "(", ")", ";", "if", "(", "pkg", ".", "startsWith", "(", "\"moa\"", ")", ")", "{", "Set", "<", "String", ">", "classnames", "=", "m_Cache", ".", "getClassnames", "(", "pkg", ")", ";", "result", ".", "addAll", "(", "classnames", ")", ";", "}", "}", "return", "result", ";", "}" ]
Returns all class names stored in the cache. @return the class names
[ "Returns", "all", "class", "names", "stored", "in", "the", "cache", "." ]
395982e5100bfe75a3a4d26115462ce2cc74cbb0
https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/moa/core/AutoClassDiscovery.java#L90-L101
28,885
Waikato/moa
moa/src/main/java/moa/core/AutoClassDiscovery.java
AutoClassDiscovery.main
public static void main(String[] args) throws Exception { initCache(); List<String> allClassnames = getAllClassNames(); PrintStream out = System.out; if (args.length > 0) out = new PrintStream(new File(args[0])); Collections.sort(allClassnames); for (String clsname: allClassnames) out.println(clsname); out.flush(); if (args.length > 0) out.close(); }
java
public static void main(String[] args) throws Exception { initCache(); List<String> allClassnames = getAllClassNames(); PrintStream out = System.out; if (args.length > 0) out = new PrintStream(new File(args[0])); Collections.sort(allClassnames); for (String clsname: allClassnames) out.println(clsname); out.flush(); if (args.length > 0) out.close(); }
[ "public", "static", "void", "main", "(", "String", "[", "]", "args", ")", "throws", "Exception", "{", "initCache", "(", ")", ";", "List", "<", "String", ">", "allClassnames", "=", "getAllClassNames", "(", ")", ";", "PrintStream", "out", "=", "System", ".", "out", ";", "if", "(", "args", ".", "length", ">", "0", ")", "out", "=", "new", "PrintStream", "(", "new", "File", "(", "args", "[", "0", "]", ")", ")", ";", "Collections", ".", "sort", "(", "allClassnames", ")", ";", "for", "(", "String", "clsname", ":", "allClassnames", ")", "out", ".", "println", "(", "clsname", ")", ";", "out", ".", "flush", "(", ")", ";", "if", "(", "args", ".", "length", ">", "0", ")", "out", ".", "close", "(", ")", ";", "}" ]
Outputs all class names below "moa" either to stdout or to the file provided as first argument. @param args optional file for storing the classnames @throws Exception if writing to file fails
[ "Outputs", "all", "class", "names", "below", "moa", "either", "to", "stdout", "or", "to", "the", "file", "provided", "as", "first", "argument", "." ]
395982e5100bfe75a3a4d26115462ce2cc74cbb0
https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/moa/core/AutoClassDiscovery.java#L168-L180
28,886
Waikato/moa
moa/src/main/java/moa/clusterers/outliers/utils/mtree/MTree.java
MTree.add
public void add(DATA data) { if(root == null) { root = new RootLeafNode(data); try { root.addData(data, 0); } catch (SplitNodeReplacement e) { throw new RuntimeException("Should never happen!"); } } else { double distance = distanceFunction.calculate(data, root.data); try { root.addData(data, distance); } catch(SplitNodeReplacement e) { Node newRoot = new RootNode(data); root = newRoot; for(int i = 0; i < e.newNodes.length; i++) { @SuppressWarnings("unchecked") Node newNode = (Node) e.newNodes[i]; distance = distanceFunction.calculate(root.data, newNode.data); root.addChild(newNode, distance); } } } }
java
public void add(DATA data) { if(root == null) { root = new RootLeafNode(data); try { root.addData(data, 0); } catch (SplitNodeReplacement e) { throw new RuntimeException("Should never happen!"); } } else { double distance = distanceFunction.calculate(data, root.data); try { root.addData(data, distance); } catch(SplitNodeReplacement e) { Node newRoot = new RootNode(data); root = newRoot; for(int i = 0; i < e.newNodes.length; i++) { @SuppressWarnings("unchecked") Node newNode = (Node) e.newNodes[i]; distance = distanceFunction.calculate(root.data, newNode.data); root.addChild(newNode, distance); } } } }
[ "public", "void", "add", "(", "DATA", "data", ")", "{", "if", "(", "root", "==", "null", ")", "{", "root", "=", "new", "RootLeafNode", "(", "data", ")", ";", "try", "{", "root", ".", "addData", "(", "data", ",", "0", ")", ";", "}", "catch", "(", "SplitNodeReplacement", "e", ")", "{", "throw", "new", "RuntimeException", "(", "\"Should never happen!\"", ")", ";", "}", "}", "else", "{", "double", "distance", "=", "distanceFunction", ".", "calculate", "(", "data", ",", "root", ".", "data", ")", ";", "try", "{", "root", ".", "addData", "(", "data", ",", "distance", ")", ";", "}", "catch", "(", "SplitNodeReplacement", "e", ")", "{", "Node", "newRoot", "=", "new", "RootNode", "(", "data", ")", ";", "root", "=", "newRoot", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "e", ".", "newNodes", ".", "length", ";", "i", "++", ")", "{", "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "Node", "newNode", "=", "(", "Node", ")", "e", ".", "newNodes", "[", "i", "]", ";", "distance", "=", "distanceFunction", ".", "calculate", "(", "root", ".", "data", ",", "newNode", ".", "data", ")", ";", "root", ".", "addChild", "(", "newNode", ",", "distance", ")", ";", "}", "}", "}", "}" ]
Adds and indexes a data object. <p>An object that is already indexed should not be added. There is no validation regarding this, and the behavior is undefined if done. @param data The data object to index.
[ "Adds", "and", "indexes", "a", "data", "object", "." ]
395982e5100bfe75a3a4d26115462ce2cc74cbb0
https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/moa/clusterers/outliers/utils/mtree/MTree.java#L352-L375
28,887
Waikato/moa
moa/src/main/java/moa/clusterers/outliers/utils/mtree/MTree.java
MTree.remove
public boolean remove(DATA data) { if(root == null) { return false; } double distanceToRoot = distanceFunction.calculate(data, root.data); try { root.removeData(data, distanceToRoot); } catch(RootNodeReplacement e) { @SuppressWarnings("unchecked") Node newRoot = (Node) e.newRoot; root = newRoot; } catch(DataNotFound e) { return false; } catch (NodeUnderCapacity e) { throw new RuntimeException("Should have never happened", e); } return true; }
java
public boolean remove(DATA data) { if(root == null) { return false; } double distanceToRoot = distanceFunction.calculate(data, root.data); try { root.removeData(data, distanceToRoot); } catch(RootNodeReplacement e) { @SuppressWarnings("unchecked") Node newRoot = (Node) e.newRoot; root = newRoot; } catch(DataNotFound e) { return false; } catch (NodeUnderCapacity e) { throw new RuntimeException("Should have never happened", e); } return true; }
[ "public", "boolean", "remove", "(", "DATA", "data", ")", "{", "if", "(", "root", "==", "null", ")", "{", "return", "false", ";", "}", "double", "distanceToRoot", "=", "distanceFunction", ".", "calculate", "(", "data", ",", "root", ".", "data", ")", ";", "try", "{", "root", ".", "removeData", "(", "data", ",", "distanceToRoot", ")", ";", "}", "catch", "(", "RootNodeReplacement", "e", ")", "{", "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "Node", "newRoot", "=", "(", "Node", ")", "e", ".", "newRoot", ";", "root", "=", "newRoot", ";", "}", "catch", "(", "DataNotFound", "e", ")", "{", "return", "false", ";", "}", "catch", "(", "NodeUnderCapacity", "e", ")", "{", "throw", "new", "RuntimeException", "(", "\"Should have never happened\"", ",", "e", ")", ";", "}", "return", "true", ";", "}" ]
Removes a data object from the M-Tree. @param data The data object to be removed. @return {@code true} if and only if the object was found.
[ "Removes", "a", "data", "object", "from", "the", "M", "-", "Tree", "." ]
395982e5100bfe75a3a4d26115462ce2cc74cbb0
https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/moa/clusterers/outliers/utils/mtree/MTree.java#L383-L401
28,888
Waikato/moa
moa/src/main/java/moa/clusterers/outliers/utils/mtree/MTree.java
MTree.getNearestByRange
public Query getNearestByRange(DATA queryData, double range) { return getNearest(queryData, range, Integer.MAX_VALUE); }
java
public Query getNearestByRange(DATA queryData, double range) { return getNearest(queryData, range, Integer.MAX_VALUE); }
[ "public", "Query", "getNearestByRange", "(", "DATA", "queryData", ",", "double", "range", ")", "{", "return", "getNearest", "(", "queryData", ",", "range", ",", "Integer", ".", "MAX_VALUE", ")", ";", "}" ]
Performs a nearest-neighbors query on the M-Tree, constrained by distance. @param queryData The query data object. @param range The maximum distance from {@code queryData} to fetched neighbors. @return A {@link Query} object used to iterate on the results.
[ "Performs", "a", "nearest", "-", "neighbors", "query", "on", "the", "M", "-", "Tree", "constrained", "by", "distance", "." ]
395982e5100bfe75a3a4d26115462ce2cc74cbb0
https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/moa/clusterers/outliers/utils/mtree/MTree.java#L410-L412
28,889
Waikato/moa
moa/src/main/java/moa/clusterers/outliers/utils/mtree/MTree.java
MTree.getNearestByLimit
public Query getNearestByLimit(DATA queryData, int limit) { return getNearest(queryData, Double.POSITIVE_INFINITY, limit); }
java
public Query getNearestByLimit(DATA queryData, int limit) { return getNearest(queryData, Double.POSITIVE_INFINITY, limit); }
[ "public", "Query", "getNearestByLimit", "(", "DATA", "queryData", ",", "int", "limit", ")", "{", "return", "getNearest", "(", "queryData", ",", "Double", ".", "POSITIVE_INFINITY", ",", "limit", ")", ";", "}" ]
Performs a nearest-neighbors query on the M-Tree, constrained by the number of neighbors. @param queryData The query data object. @param limit The maximum number of neighbors to fetch. @return A {@link Query} object used to iterate on the results.
[ "Performs", "a", "nearest", "-", "neighbors", "query", "on", "the", "M", "-", "Tree", "constrained", "by", "the", "number", "of", "neighbors", "." ]
395982e5100bfe75a3a4d26115462ce2cc74cbb0
https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/moa/clusterers/outliers/utils/mtree/MTree.java#L422-L424
28,890
Waikato/moa
moa/src/main/java/moa/clusterers/outliers/utils/mtree/MTree.java
MTree.getNearest
public Query getNearest(DATA queryData) { return new Query(queryData, Double.POSITIVE_INFINITY, Integer.MAX_VALUE); }
java
public Query getNearest(DATA queryData) { return new Query(queryData, Double.POSITIVE_INFINITY, Integer.MAX_VALUE); }
[ "public", "Query", "getNearest", "(", "DATA", "queryData", ")", "{", "return", "new", "Query", "(", "queryData", ",", "Double", ".", "POSITIVE_INFINITY", ",", "Integer", ".", "MAX_VALUE", ")", ";", "}" ]
Performs a nearest-neighbor query on the M-Tree, without constraints. @param queryData The query data object. @return A {@link Query} object used to iterate on the results.
[ "Performs", "a", "nearest", "-", "neighbor", "query", "on", "the", "M", "-", "Tree", "without", "constraints", "." ]
395982e5100bfe75a3a4d26115462ce2cc74cbb0
https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/moa/clusterers/outliers/utils/mtree/MTree.java#L444-L446
28,891
Waikato/moa
moa/src/main/java/moa/clusterers/clustream/WithKmeans.java
WithKmeans.distance
private static double distance(double[] pointA, double [] pointB) { double distance = 0.0; for (int i = 0; i < pointA.length; i++) { double d = pointA[i] - pointB[i]; distance += d * d; } return Math.sqrt(distance); }
java
private static double distance(double[] pointA, double [] pointB) { double distance = 0.0; for (int i = 0; i < pointA.length; i++) { double d = pointA[i] - pointB[i]; distance += d * d; } return Math.sqrt(distance); }
[ "private", "static", "double", "distance", "(", "double", "[", "]", "pointA", ",", "double", "[", "]", "pointB", ")", "{", "double", "distance", "=", "0.0", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "pointA", ".", "length", ";", "i", "++", ")", "{", "double", "d", "=", "pointA", "[", "i", "]", "-", "pointB", "[", "i", "]", ";", "distance", "+=", "d", "*", "d", ";", "}", "return", "Math", ".", "sqrt", "(", "distance", ")", ";", "}" ]
Distance between two vectors. @param pointA @param pointB @return dist
[ "Distance", "between", "two", "vectors", "." ]
395982e5100bfe75a3a4d26115462ce2cc74cbb0
https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/moa/clusterers/clustream/WithKmeans.java#L216-L223
28,892
Waikato/moa
moa/src/main/java/moa/clusterers/clustream/WithKmeans.java
WithKmeans.cleanUpKMeans
protected static Clustering cleanUpKMeans(Clustering kMeansResult, ArrayList<CFCluster> microclusters) { /* Convert k-means result to CFClusters */ int k = kMeansResult.size(); CFCluster[] converted = new CFCluster[k]; for (CFCluster mc : microclusters) { // Find closest kMeans cluster double minDistance = Double.MAX_VALUE; int closestCluster = 0; for (int i = 0; i < k; i++) { double distance = distance(kMeansResult.get(i).getCenter(), mc.getCenter()); if (distance < minDistance) { closestCluster = i; minDistance = distance; } } // Add to cluster if ( converted[closestCluster] == null ) { converted[closestCluster] = (CFCluster)mc.copy(); } else { converted[closestCluster].add(mc); } } // Clean up int count = 0; for (int i = 0; i < converted.length; i++) { if (converted[i] != null) count++; } CFCluster[] cleaned = new CFCluster[count]; count = 0; for (int i = 0; i < converted.length; i++) { if (converted[i] != null) cleaned[count++] = converted[i]; } return new Clustering(cleaned); }
java
protected static Clustering cleanUpKMeans(Clustering kMeansResult, ArrayList<CFCluster> microclusters) { /* Convert k-means result to CFClusters */ int k = kMeansResult.size(); CFCluster[] converted = new CFCluster[k]; for (CFCluster mc : microclusters) { // Find closest kMeans cluster double minDistance = Double.MAX_VALUE; int closestCluster = 0; for (int i = 0; i < k; i++) { double distance = distance(kMeansResult.get(i).getCenter(), mc.getCenter()); if (distance < minDistance) { closestCluster = i; minDistance = distance; } } // Add to cluster if ( converted[closestCluster] == null ) { converted[closestCluster] = (CFCluster)mc.copy(); } else { converted[closestCluster].add(mc); } } // Clean up int count = 0; for (int i = 0; i < converted.length; i++) { if (converted[i] != null) count++; } CFCluster[] cleaned = new CFCluster[count]; count = 0; for (int i = 0; i < converted.length; i++) { if (converted[i] != null) cleaned[count++] = converted[i]; } return new Clustering(cleaned); }
[ "protected", "static", "Clustering", "cleanUpKMeans", "(", "Clustering", "kMeansResult", ",", "ArrayList", "<", "CFCluster", ">", "microclusters", ")", "{", "/* Convert k-means result to CFClusters */", "int", "k", "=", "kMeansResult", ".", "size", "(", ")", ";", "CFCluster", "[", "]", "converted", "=", "new", "CFCluster", "[", "k", "]", ";", "for", "(", "CFCluster", "mc", ":", "microclusters", ")", "{", "// Find closest kMeans cluster", "double", "minDistance", "=", "Double", ".", "MAX_VALUE", ";", "int", "closestCluster", "=", "0", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "k", ";", "i", "++", ")", "{", "double", "distance", "=", "distance", "(", "kMeansResult", ".", "get", "(", "i", ")", ".", "getCenter", "(", ")", ",", "mc", ".", "getCenter", "(", ")", ")", ";", "if", "(", "distance", "<", "minDistance", ")", "{", "closestCluster", "=", "i", ";", "minDistance", "=", "distance", ";", "}", "}", "// Add to cluster", "if", "(", "converted", "[", "closestCluster", "]", "==", "null", ")", "{", "converted", "[", "closestCluster", "]", "=", "(", "CFCluster", ")", "mc", ".", "copy", "(", ")", ";", "}", "else", "{", "converted", "[", "closestCluster", "]", ".", "add", "(", "mc", ")", ";", "}", "}", "// Clean up", "int", "count", "=", "0", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "converted", ".", "length", ";", "i", "++", ")", "{", "if", "(", "converted", "[", "i", "]", "!=", "null", ")", "count", "++", ";", "}", "CFCluster", "[", "]", "cleaned", "=", "new", "CFCluster", "[", "count", "]", ";", "count", "=", "0", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "converted", ".", "length", ";", "i", "++", ")", "{", "if", "(", "converted", "[", "i", "]", "!=", "null", ")", "cleaned", "[", "count", "++", "]", "=", "converted", "[", "i", "]", ";", "}", "return", "new", "Clustering", "(", "cleaned", ")", ";", "}" ]
Rearrange the k-means result into a set of CFClusters, cleaning up the redundancies. @param kMeansResult @param microclusters @return
[ "Rearrange", "the", "k", "-", "means", "result", "into", "a", "set", "of", "CFClusters", "cleaning", "up", "the", "redundancies", "." ]
395982e5100bfe75a3a4d26115462ce2cc74cbb0
https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/moa/clusterers/clustream/WithKmeans.java#L365-L405
28,893
Waikato/moa
moa/src/main/java/moa/clusterers/clustree/Entry.java
Entry.clear
protected void clear() { this.data.clear(); this.buffer.clear(); this.child = null; this.timestamp = Entry.defaultTimestamp; }
java
protected void clear() { this.data.clear(); this.buffer.clear(); this.child = null; this.timestamp = Entry.defaultTimestamp; }
[ "protected", "void", "clear", "(", ")", "{", "this", ".", "data", ".", "clear", "(", ")", ";", "this", ".", "buffer", ".", "clear", "(", ")", ";", "this", ".", "child", "=", "null", ";", "this", ".", "timestamp", "=", "Entry", ".", "defaultTimestamp", ";", "}" ]
Clear the Entry. All points in the buffer and in the data cluster are lost, the connection to the child is lost and the timestamp is set to the default value.
[ "Clear", "the", "Entry", ".", "All", "points", "in", "the", "buffer", "and", "in", "the", "data", "cluster", "are", "lost", "the", "connection", "to", "the", "child", "is", "lost", "and", "the", "timestamp", "is", "set", "to", "the", "default", "value", "." ]
395982e5100bfe75a3a4d26115462ce2cc74cbb0
https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/moa/clusterers/clustree/Entry.java#L166-L171
28,894
Waikato/moa
moa/src/main/java/moa/clusterers/clustree/Entry.java
Entry.makeOlder
protected void makeOlder(long currentTime, double negLambda) { // assert (currentTime > this.timestamp) : "currentTime : " // + currentTime + ", this.timestamp: " + this.timestamp; long diff = currentTime - this.timestamp; this.buffer.makeOlder(diff, negLambda); this.data.makeOlder(diff, negLambda); this.timestamp = currentTime; }
java
protected void makeOlder(long currentTime, double negLambda) { // assert (currentTime > this.timestamp) : "currentTime : " // + currentTime + ", this.timestamp: " + this.timestamp; long diff = currentTime - this.timestamp; this.buffer.makeOlder(diff, negLambda); this.data.makeOlder(diff, negLambda); this.timestamp = currentTime; }
[ "protected", "void", "makeOlder", "(", "long", "currentTime", ",", "double", "negLambda", ")", "{", "// assert (currentTime > this.timestamp) : \"currentTime : \"", "// + currentTime + \", this.timestamp: \" + this.timestamp;", "long", "diff", "=", "currentTime", "-", "this", ".", "timestamp", ";", "this", ".", "buffer", ".", "makeOlder", "(", "diff", ",", "negLambda", ")", ";", "this", ".", "data", ".", "makeOlder", "(", "diff", ",", "negLambda", ")", ";", "this", ".", "timestamp", "=", "currentTime", ";", "}" ]
Ages this entrie's data AND buffer according to the given time and aging constant. @param currentTime the current time @param negLambda the aging constant
[ "Ages", "this", "entrie", "s", "data", "AND", "buffer", "according", "to", "the", "given", "time", "and", "aging", "constant", "." ]
395982e5100bfe75a3a4d26115462ce2cc74cbb0
https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/moa/clusterers/clustree/Entry.java#L454-L462
28,895
Waikato/moa
moa/src/main/java/moa/classifiers/oneclass/HSTrees.java
HSTrees.resetLearningImpl
@Override public void resetLearningImpl() { this.windowSize = this.windowSizeOption.getValue(); this.numTrees = this.numTreesOption.getValue(); this.maxDepth = this.maxDepthOption.getValue(); this.sizeLimit = this.sizeLimitOption.getValue(); this.numInstances = 0; this.forest = new HSTreeNode[numTrees]; this.referenceWindow = true; this.anomalyThreshold = this.anomalyThresholdOption.getValue(); }
java
@Override public void resetLearningImpl() { this.windowSize = this.windowSizeOption.getValue(); this.numTrees = this.numTreesOption.getValue(); this.maxDepth = this.maxDepthOption.getValue(); this.sizeLimit = this.sizeLimitOption.getValue(); this.numInstances = 0; this.forest = new HSTreeNode[numTrees]; this.referenceWindow = true; this.anomalyThreshold = this.anomalyThresholdOption.getValue(); }
[ "@", "Override", "public", "void", "resetLearningImpl", "(", ")", "{", "this", ".", "windowSize", "=", "this", ".", "windowSizeOption", ".", "getValue", "(", ")", ";", "this", ".", "numTrees", "=", "this", ".", "numTreesOption", ".", "getValue", "(", ")", ";", "this", ".", "maxDepth", "=", "this", ".", "maxDepthOption", ".", "getValue", "(", ")", ";", "this", ".", "sizeLimit", "=", "this", ".", "sizeLimitOption", ".", "getValue", "(", ")", ";", "this", ".", "numInstances", "=", "0", ";", "this", ".", "forest", "=", "new", "HSTreeNode", "[", "numTrees", "]", ";", "this", ".", "referenceWindow", "=", "true", ";", "this", ".", "anomalyThreshold", "=", "this", ".", "anomalyThresholdOption", ".", "getValue", "(", ")", ";", "}" ]
Reset the classifier's parameters and data structures.
[ "Reset", "the", "classifier", "s", "parameters", "and", "data", "structures", "." ]
395982e5100bfe75a3a4d26115462ce2cc74cbb0
https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/moa/classifiers/oneclass/HSTrees.java#L113-L124
28,896
Waikato/moa
moa/src/main/java/moa/classifiers/oneclass/HSTrees.java
HSTrees.trainOnInstanceImpl
@Override public void trainOnInstanceImpl(Instance inst) { // If this is the first instance, then initialize the forest. if(this.numInstances == 0) { this.buildForest(inst); } // Update the mass profile of every HSTree in the forest for(int i = 0 ; i < this.numTrees ; i++) { forest[i].updateMass(inst, referenceWindow); } if(this.numInstances > 50) referenceWindow = false; // If this is the last instance of the window, update every HSTree's model if(this.numInstances % windowSize == 0) { for(int i = 0 ; i < this.numTrees ; i++) { forest[i].updateModel(); } } this.numInstances++; }
java
@Override public void trainOnInstanceImpl(Instance inst) { // If this is the first instance, then initialize the forest. if(this.numInstances == 0) { this.buildForest(inst); } // Update the mass profile of every HSTree in the forest for(int i = 0 ; i < this.numTrees ; i++) { forest[i].updateMass(inst, referenceWindow); } if(this.numInstances > 50) referenceWindow = false; // If this is the last instance of the window, update every HSTree's model if(this.numInstances % windowSize == 0) { for(int i = 0 ; i < this.numTrees ; i++) { forest[i].updateModel(); } } this.numInstances++; }
[ "@", "Override", "public", "void", "trainOnInstanceImpl", "(", "Instance", "inst", ")", "{", "// If this is the first instance, then initialize the forest.", "if", "(", "this", ".", "numInstances", "==", "0", ")", "{", "this", ".", "buildForest", "(", "inst", ")", ";", "}", "// Update the mass profile of every HSTree in the forest", "for", "(", "int", "i", "=", "0", ";", "i", "<", "this", ".", "numTrees", ";", "i", "++", ")", "{", "forest", "[", "i", "]", ".", "updateMass", "(", "inst", ",", "referenceWindow", ")", ";", "}", "if", "(", "this", ".", "numInstances", ">", "50", ")", "referenceWindow", "=", "false", ";", "// If this is the last instance of the window, update every HSTree's model", "if", "(", "this", ".", "numInstances", "%", "windowSize", "==", "0", ")", "{", "for", "(", "int", "i", "=", "0", ";", "i", "<", "this", ".", "numTrees", ";", "i", "++", ")", "{", "forest", "[", "i", "]", ".", "updateModel", "(", ")", ";", "}", "}", "this", ".", "numInstances", "++", ";", "}" ]
Update the forest with the argument instance @param inst the instance to pass to the forest
[ "Update", "the", "forest", "with", "the", "argument", "instance" ]
395982e5100bfe75a3a4d26115462ce2cc74cbb0
https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/moa/classifiers/oneclass/HSTrees.java#L131-L159
28,897
Waikato/moa
moa/src/main/java/moa/classifiers/oneclass/HSTrees.java
HSTrees.buildForest
private void buildForest(Instance inst) { this.dimensions = inst.numAttributes(); double[]max = new double[dimensions]; double[]min = new double[dimensions]; double sq; for (int i = 0 ; i < this.numTrees ; i++) { for(int j = 0 ; j < this.dimensions ; j++) { sq = this.classifierRandom.nextDouble(); min[j] = sq - (2.0*Math.max(sq, 1.0-sq)); max[j] = sq + (2.0*Math.max(sq, 1.0-sq)); } forest[i] = new HSTreeNode(min, max, 1, maxDepth); } }
java
private void buildForest(Instance inst) { this.dimensions = inst.numAttributes(); double[]max = new double[dimensions]; double[]min = new double[dimensions]; double sq; for (int i = 0 ; i < this.numTrees ; i++) { for(int j = 0 ; j < this.dimensions ; j++) { sq = this.classifierRandom.nextDouble(); min[j] = sq - (2.0*Math.max(sq, 1.0-sq)); max[j] = sq + (2.0*Math.max(sq, 1.0-sq)); } forest[i] = new HSTreeNode(min, max, 1, maxDepth); } }
[ "private", "void", "buildForest", "(", "Instance", "inst", ")", "{", "this", ".", "dimensions", "=", "inst", ".", "numAttributes", "(", ")", ";", "double", "[", "]", "max", "=", "new", "double", "[", "dimensions", "]", ";", "double", "[", "]", "min", "=", "new", "double", "[", "dimensions", "]", ";", "double", "sq", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "this", ".", "numTrees", ";", "i", "++", ")", "{", "for", "(", "int", "j", "=", "0", ";", "j", "<", "this", ".", "dimensions", ";", "j", "++", ")", "{", "sq", "=", "this", ".", "classifierRandom", ".", "nextDouble", "(", ")", ";", "min", "[", "j", "]", "=", "sq", "-", "(", "2.0", "*", "Math", ".", "max", "(", "sq", ",", "1.0", "-", "sq", ")", ")", ";", "max", "[", "j", "]", "=", "sq", "+", "(", "2.0", "*", "Math", ".", "max", "(", "sq", ",", "1.0", "-", "sq", ")", ")", ";", "}", "forest", "[", "i", "]", "=", "new", "HSTreeNode", "(", "min", ",", "max", ",", "1", ",", "maxDepth", ")", ";", "}", "}" ]
Build the forest of Streaming Half-Space Trees @param inst an example instance
[ "Build", "the", "forest", "of", "Streaming", "Half", "-", "Space", "Trees" ]
395982e5100bfe75a3a4d26115462ce2cc74cbb0
https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/moa/classifiers/oneclass/HSTrees.java#L166-L184
28,898
Waikato/moa
moa/src/main/java/moa/classifiers/oneclass/HSTrees.java
HSTrees.getVotesForInstance
@Override public double[] getVotesForInstance(Instance inst) { double[] votes = {0.5, 0.5}; if(!referenceWindow) { votes[1] = this.getAnomalyScore(inst) + 0.5 - this.anomalyThreshold; votes[0] = 1.0 - votes[1]; } return votes; }
java
@Override public double[] getVotesForInstance(Instance inst) { double[] votes = {0.5, 0.5}; if(!referenceWindow) { votes[1] = this.getAnomalyScore(inst) + 0.5 - this.anomalyThreshold; votes[0] = 1.0 - votes[1]; } return votes; }
[ "@", "Override", "public", "double", "[", "]", "getVotesForInstance", "(", "Instance", "inst", ")", "{", "double", "[", "]", "votes", "=", "{", "0.5", ",", "0.5", "}", ";", "if", "(", "!", "referenceWindow", ")", "{", "votes", "[", "1", "]", "=", "this", ".", "getAnomalyScore", "(", "inst", ")", "+", "0.5", "-", "this", ".", "anomalyThreshold", ";", "votes", "[", "0", "]", "=", "1.0", "-", "votes", "[", "1", "]", ";", "}", "return", "votes", ";", "}" ]
Combine the anomaly scores from each HSTree in the forest and convert into a vote score. @param inst the instance to get votes for @return the votes for the instance's label [normal, outlier]
[ "Combine", "the", "anomaly", "scores", "from", "each", "HSTree", "in", "the", "forest", "and", "convert", "into", "a", "vote", "score", "." ]
395982e5100bfe75a3a4d26115462ce2cc74cbb0
https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/moa/classifiers/oneclass/HSTrees.java#L193-L205
28,899
Waikato/moa
moa/src/main/java/moa/classifiers/oneclass/HSTrees.java
HSTrees.getAnomalyScore
public double getAnomalyScore(Instance inst) { if(this.referenceWindow) return 0.5; else { double accumulatedScore = 0.0; int massLimit = (int) (Math.ceil(this.sizeLimit*this.windowSize)); double maxScore = this.windowSize * Math.pow(2.0, this.maxDepth); for(int i = 0 ; i < this.numTrees ; i++) { accumulatedScore += (forest[i].score(inst, massLimit) / maxScore); } accumulatedScore = accumulatedScore / (((double) this.numTrees)); return 0.5 - accumulatedScore + this.anomalyThreshold; } }
java
public double getAnomalyScore(Instance inst) { if(this.referenceWindow) return 0.5; else { double accumulatedScore = 0.0; int massLimit = (int) (Math.ceil(this.sizeLimit*this.windowSize)); double maxScore = this.windowSize * Math.pow(2.0, this.maxDepth); for(int i = 0 ; i < this.numTrees ; i++) { accumulatedScore += (forest[i].score(inst, massLimit) / maxScore); } accumulatedScore = accumulatedScore / (((double) this.numTrees)); return 0.5 - accumulatedScore + this.anomalyThreshold; } }
[ "public", "double", "getAnomalyScore", "(", "Instance", "inst", ")", "{", "if", "(", "this", ".", "referenceWindow", ")", "return", "0.5", ";", "else", "{", "double", "accumulatedScore", "=", "0.0", ";", "int", "massLimit", "=", "(", "int", ")", "(", "Math", ".", "ceil", "(", "this", ".", "sizeLimit", "*", "this", ".", "windowSize", ")", ")", ";", "double", "maxScore", "=", "this", ".", "windowSize", "*", "Math", ".", "pow", "(", "2.0", ",", "this", ".", "maxDepth", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "this", ".", "numTrees", ";", "i", "++", ")", "{", "accumulatedScore", "+=", "(", "forest", "[", "i", "]", ".", "score", "(", "inst", ",", "massLimit", ")", "/", "maxScore", ")", ";", "}", "accumulatedScore", "=", "accumulatedScore", "/", "(", "(", "(", "double", ")", "this", ".", "numTrees", ")", ")", ";", "return", "0.5", "-", "accumulatedScore", "+", "this", ".", "anomalyThreshold", ";", "}", "}" ]
Returns the anomaly score for the argument instance. @param inst the argument instance @return inst's anomaly score
[ "Returns", "the", "anomaly", "score", "for", "the", "argument", "instance", "." ]
395982e5100bfe75a3a4d26115462ce2cc74cbb0
https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/moa/classifiers/oneclass/HSTrees.java#L214-L233