public final class Utils extends Object implements RevisionHandler
Modifier and Type | Field and Description |
---|---|
static double |
log2
The natural logarithm of 2.
|
static String[] |
ORDINAL_SUFFIXES
Suffixes for ordinal representation of indices.
|
static double |
SMALL
The small deviation allowed in double comparisons.
|
Constructor and Description |
---|
Utils() |
Modifier and Type | Method and Description |
---|---|
static String |
arrayToString(Object array)
Returns the given Array in a string representation.
|
static String |
backQuoteChars(String string)
Converts carriage returns and new lines in a string into \r and \n.
|
static String[] |
breakUp(String s,
int columns)
Breaks up the string, if wider than "columns" characters.
|
static <T> T |
cast(Object x)
Casting an object without "unchecked" compile-time warnings.
|
static void |
checkForRemainingOptions(String[] options)
Checks if the given array contains any non-empty options.
|
static Range |
configureRangeFromRangeStringOrAttributeNameList(Instances instanceInfo,
String rangeString)
Returns a configured Range object given a 1-based range index string (such
as 1-20,35,last) or a comma-separated list of attribute names.
|
static String |
convertNewLines(String string)
Converts carriage returns and new lines in a string into \r and \n.
|
static File |
convertToRelativePath(File absolute)
Converts a File's absolute path to a path relative to the user (ie start)
directory.
|
static double |
correlation(double[] y1,
double[] y2,
int n)
Returns the correlation coefficient of two double vectors.
|
static double |
dateToMillis(String dateString,
String dateFormat)
Turns a given date string into Java's internal representation (milliseconds
from 1 January 1970).
|
static String |
doubleToString(double value,
int afterDecimalPoint)
Rounds a double and converts it into String.
|
static String |
doubleToString(double value,
int width,
int afterDecimalPoint)
Rounds a double and converts it into a formatted decimal-justified String.
|
static boolean |
eq(double a,
double b)
Tests if a is equal to b.
|
static Object |
forName(Class<?> classType,
String className,
String[] options)
Creates a new instance of an object given it's class name and (optional)
arguments to pass to it's setOptions method.
|
static Class<?> |
getArrayClass(Class<?> c)
Returns the basic class of an array class (handles multi-dimensional
arrays).
|
static int |
getArrayDimensions(Class<?> array)
Returns the dimensions of the given array.
|
static int |
getArrayDimensions(Object array)
Returns the dimensions of the given array.
|
static boolean |
getDontShowDialog(String dialogName)
For a named dialog, returns true if the user has opted not to view it again
in the future.
|
static String |
getDontShowDialogResponse(String dialogName)
For a named dialog, if the user has opted not to view it again, returns the
answer the answer the user supplied when they closed the dialog.
|
static boolean |
getFlag(char flag,
String[] options)
Checks if the given array contains the flag "-Char".
|
static boolean |
getFlag(String flag,
String[] options)
Checks if the given array contains the flag "-String".
|
static String |
getGlobalInfo(Object object,
boolean addCapabilities)
Utility method for grabbing the global info help (if it exists) from an
arbitrary object.
|
static String |
getOption(char flag,
String[] options)
Gets an option indicated by a flag "-Char" from the given array of strings.
|
static String |
getOption(String flag,
String[] options)
Gets an option indicated by a flag "-String" from the given array of
strings.
|
static int |
getOptionPos(char flag,
String[] options)
Gets the index of an option or flag indicated by a flag "-Char" from the
given array of strings.
|
static int |
getOptionPos(String flag,
String[] options)
Gets the index of an option or flag indicated by a flag "-String" from the
given array of strings.
|
String |
getRevision()
Returns the revision string.
|
static JFrame |
getWekaJFrame(String title,
Component component)
Returns a JFrame with the given title.
|
static boolean |
gr(double a,
double b)
Tests if a is greater than b.
|
static boolean |
grOrEq(double a,
double b)
Tests if a is greater or equal to b.
|
static String |
indexToOrdinal(int i)
Turns a zero-based index into its ordinal representation, e.g., the integer 0 will be turned into the string "1st",
1 will be turned into the string "2nd", etc.
|
static double |
info(int[] counts)
Computes entropy for an array of integers.
|
static boolean |
isMissingValue(double val)
Tests if the given value codes "missing".
|
static String |
joinOptions(String[] optionArray)
Joins all the options in an option array into a single string, as might be
used on the command line.
|
static double |
kthSmallestValue(double[] array,
int k)
Returns the kth-smallest value in the array
|
static int |
kthSmallestValue(int[] array,
int k)
Returns the kth-smallest value in the array.
|
static String |
lineWrap(String input,
int maxLineWidth)
Implements simple line breaking.
|
static double |
log2(double a)
Returns the logarithm of a for base 2.
|
static double[] |
logs2probs(double[] a)
Converts an array containing the natural logarithms of probabilities stored
in a vector back into probabilities.
|
static void |
main(String[] ops)
Main method for testing this class.
|
static int |
maxIndex(double[] doubles)
Returns index of maximum element in a given array of doubles.
|
static int |
maxIndex(int[] ints)
Returns index of maximum element in a given array of integers.
|
static double |
mean(double[] vector)
Computes the mean for an array of doubles.
|
static String |
millisToDate(double millis,
String dateFormat)
The inverse of dateToMillis(String, String).
|
static int |
minIndex(double[] doubles)
Returns index of minimum element in a given array of doubles.
|
static int |
minIndex(int[] ints)
Returns index of minimum element in a given array of integers.
|
static double |
missingValue()
Returns the value used to code a missing value.
|
static void |
normalize(double[] doubles)
Normalizes the doubles in the array by their sum.
|
static void |
normalize(double[] doubles,
double sum)
Normalizes the doubles in the array using the given value.
|
static String |
padLeft(String inString,
int length)
Pads a string to a specified length, inserting spaces on the left as
required.
|
static String |
padLeftAndAllowOverflow(String inString,
int length)
Pads a string to a specified length, inserting spaces on the left as
required.
|
static String |
padRight(String inString,
int length)
Pads a string to a specified length, inserting spaces on the right as
required.
|
static String |
padRightAndAllowOverflow(String inString,
int length)
Pads a string to a specified length, inserting spaces on the right as
required.
|
static String[] |
partitionOptions(String[] options)
Returns the secondary set of options (if any) contained in the supplied
options array.
|
static int |
probRound(double value,
Random rand)
Rounds a double to the next nearest integer value in a probabilistic
fashion (e.g.
|
static double |
probToLogOdds(double prob)
Returns the log-odds for a given probabilitiy.
|
static String |
quote(String string)
Quotes a string if it contains special characters.
|
static Properties |
readProperties(String resourceName)
Reads properties that inherit from three locations.
|
static Properties |
readProperties(String resourceName,
ClassLoader loader)
Reads properties that inherit from three locations.
|
static String |
removeSubstring(String inString,
String substring)
Removes all occurrences of a string from another string.
|
static void |
replaceMissingWithMAX_VALUE(double[] array)
Replaces all "missing values" in the given array of double values with
MAX_VALUE.
|
static String |
replaceStrings(String string,
String[] charsFind,
char[] charsReplace)
Converts the specified strings in the given string to the specified characters.
|
static String |
replaceSubstring(String inString,
String subString,
String replaceString)
Replaces with a new string, all occurrences of a string from another
string.
|
static String |
revertNewLines(String string)
Reverts \r and \n in a string into carriage returns and new lines.
|
static int |
round(double value)
Rounds a double to the next nearest integer value.
|
static double |
roundDouble(double value,
int afterDecimalPoint)
Rounds a double to the given number of decimal places.
|
static void |
setDontShowDialog(String dialogName)
Specify that the named dialog is not to be displayed in the future.
|
static void |
setDontShowDialogResponse(String dialogName,
String response)
Specify that the named dialog is not to be shown again in the future.
|
static boolean |
sm(double a,
double b)
Tests if a is smaller than b.
|
static boolean |
smOrEq(double a,
double b)
Tests if a is smaller or equal to b.
|
static int[] |
sort(double[] array)
Sorts a given array of doubles in ascending order and returns an array of
integers with the positions of the elements of the original array in the
sorted array.
|
static int[] |
sort(int[] array)
Sorts a given array of integers in ascending order and returns an array of
integers with the positions of the elements of the original array in the
sorted array.
|
static int[] |
sortWithNoMissingValues(double[] array)
Sorts a given array of doubles in ascending order and returns an array of
integers with the positions of the elements of the original array in the
sorted array.
|
static String[] |
splitOptions(String quotedOptionString)
Split up a string containing options into an array of strings, one for each
option.
|
static String[] |
splitOptions(String quotedOptionString,
String[] toReplace,
char[] replacements)
Split up a string containing options into an array of strings, one for each option.
|
static int[] |
stableSort(double[] array)
Sorts a given array of doubles in ascending order and returns an array of
integers with the positions of the elements of the original array in the
sorted array.
|
static double |
sum(double[] doubles)
Computes the sum of the elements of an array of doubles.
|
static int |
sum(int[] ints)
Computes the sum of the elements of an array of integers.
|
static int[] |
takeSample(double[] weights,
Random random)
Takes a sample based on the given array of weights based on Walker's method.
|
static String |
toCommandLine(Object obj)
Generates a commandline of the given object.
|
static String |
unbackQuoteChars(String string)
The inverse operation of backQuoteChars().
|
static String |
unquote(String string)
unquotes are previously quoted string (but only if necessary), i.e., it
removes the single quotes around it.
|
static double |
variance(double[] vector)
Computes the variance for an array of doubles.
|
static double |
xlogx(int c)
Returns c*log2(c) for a given integer value c.
|
public static double log2
public static double SMALL
public static String[] ORDINAL_SUFFIXES
public static double dateToMillis(String dateString, String dateFormat) throws ParseException
dateString
- the string representing the datedateFormat
- the date format as a stringParseException
public static String millisToDate(double millis, String dateFormat)
millis
- the milliseconds from 1 January 1970, given as a doubledateFormat
- the date format as a stringpublic static String indexToOrdinal(int i)
i
- the 0-based index for which the ordinal representation is required (as a string)public static boolean isMissingValue(double val)
val
- the value to be testedpublic static double missingValue()
public static <T> T cast(Object x)
public static Properties readProperties(String resourceName) throws Exception
resourceName
- the location of the resource that should be loaded.
e.g.: "weka/core/Utils.props". (The use of hardcoded forward
slashes here is OK - see jdk1.1/docs/guide/misc/resources.html)
This routine will also look for the file (in this case)
"Utils.props" in the users home directory and the current
directory.Exception
- if no default properties are defined, or if an error
occurs reading the properties files.public static Properties readProperties(String resourceName, ClassLoader loader) throws Exception
resourceName
- the location of the resource that should be loaded.
e.g.: "weka/core/Utils.props". (The use of hardcoded forward
slashes here is OK - see jdk1.1/docs/guide/misc/resources.html)
This routine will also look for the file (in this case)
"Utils.props" in the users home directory and the current
directory.loader
- the class loader to use when loading propertiesException
- if no default properties are defined, or if an error
occurs reading the properties files.public static final double correlation(double[] y1, double[] y2, int n)
y1
- double vector 1y2
- double vector 2n
- the length of two double vectorspublic static String removeSubstring(String inString, String substring)
inString
- the string to remove substrings from.substring
- the substring to remove.public static String replaceSubstring(String inString, String subString, String replaceString)
inString
- the string to replace substrings in.subString
- the substring to replace.replaceString
- the replacement substringpublic static String padLeftAndAllowOverflow(String inString, int length)
inString
- the input stringlength
- the desired length of the output stringpublic static String padRightAndAllowOverflow(String inString, int length)
inString
- the input stringlength
- the desired length of the output stringpublic static String padLeft(String inString, int length)
inString
- the input stringlength
- the desired length of the output stringpublic static String padRight(String inString, int length)
inString
- the input stringlength
- the desired length of the output stringpublic static String doubleToString(double value, int afterDecimalPoint)
value
- the double valueafterDecimalPoint
- the (maximum) number of digits permitted after the
decimal pointpublic static String doubleToString(double value, int width, int afterDecimalPoint)
value
- the double valuewidth
- the width of the stringafterDecimalPoint
- the number of digits after the decimal pointpublic static Class<?> getArrayClass(Class<?> c)
c
- the array to inspectpublic static int getArrayDimensions(Class<?> array)
array
- the array to determine the dimensions forpublic static int getArrayDimensions(Object array)
array
- the array to determine the dimensions forpublic static String arrayToString(Object array)
array
- the array to return in a string representationpublic static boolean eq(double a, double b)
a
- a doubleb
- a doublepublic static void checkForRemainingOptions(String[] options) throws Exception
options
- an array of stringsException
- if there are any non-empty optionspublic static boolean getFlag(char flag, String[] options) throws Exception
flag
- the character indicating the flag.options
- the array of strings containing all the options.Exception
- if an illegal option was foundpublic static boolean getFlag(String flag, String[] options) throws Exception
flag
- the String indicating the flag.options
- the array of strings containing all the options.Exception
- if an illegal option was foundpublic static String getOption(char flag, String[] options) throws Exception
flag
- the character indicating the option.options
- the array of strings containing all the options.Exception
- if the option indicated by the flag can't be foundpublic static String getOption(String flag, String[] options) throws Exception
flag
- the String indicating the option.options
- the array of strings containing all the options.Exception
- if the option indicated by the flag can't be foundpublic static int getOptionPos(char flag, String[] options)
flag
- the character indicating the option.options
- the array of strings containing all the options.public static int getOptionPos(String flag, String[] options)
flag
- the String indicating the option.options
- the array of strings containing all the options.public static String quote(String string)
string
- the string to be quotedunquote(String)
public static String unquote(String string)
string
- the string to processquote(String)
public static String backQuoteChars(String string)
string
- the stringunbackQuoteChars(String)
public static String convertNewLines(String string)
string
- the stringpublic static String revertNewLines(String string)
string
- the stringpublic static String[] partitionOptions(String[] options)
options
- the input array of optionspublic static String unbackQuoteChars(String string)
string
- the stringbackQuoteChars(String)
public static String replaceStrings(String string, String[] charsFind, char[] charsReplace)
string
- the string to operate oncharsFind
- the strings to replacecharsReplace
- the characters to replace these withpublic static String[] splitOptions(String quotedOptionString) throws Exception
quotedOptionString
- the string containing the optionsException
- in case of an unterminated string, unknown character or a
parse errorpublic static String[] splitOptions(String quotedOptionString, String[] toReplace, char[] replacements) throws Exception
quotedOptionString
- the string containing the optionstoReplace
- strings to replace in each option (e.g., backquoted characters)replacements
- the characters to replace the strings withException
- in case of an unterminated string, unknown character or a
parse errorpublic static String joinOptions(String[] optionArray)
optionArray
- the array of optionspublic static Object forName(Class<?> classType, String className, String[] options) throws Exception
String classifierName = Utils.getOption('W', options);
Classifier c = (Classifier)Utils.forName(Classifier.class,
classifierName,
options);
setClassifier(c);
classType
- the class that the instantiated object should be
assignable to -- an exception is thrown if this is not the caseclassName
- the fully qualified class name of the objectoptions
- an array of options suitable for passing to setOptions. May
be null. Any options accepted by the object will be removed from
the array.Exception
- if the class name is invalid, or if the class is not
assignable to the desired class type, or the options supplied
are not acceptable to the objectpublic static JFrame getWekaJFrame(String title, Component component)
title
- the title of the windowcomponent
- the component for which the ancestor window is foundpublic static String toCommandLine(Object obj)
obj
- the object to turn into a commandlinepublic static double info(int[] counts)
counts
- array of countspublic static boolean smOrEq(double a, double b)
a
- a doubleb
- a doublepublic static boolean grOrEq(double a, double b)
a
- a doubleb
- a doublepublic static boolean sm(double a, double b)
a
- a doubleb
- a doublepublic static boolean gr(double a, double b)
a
- a doubleb
- a doublepublic static int kthSmallestValue(int[] array, int k)
array
- the array of integersk
- the value of kpublic static double kthSmallestValue(double[] array, int k)
array
- the array of doublek
- the value of kpublic static double log2(double a)
a
- a doublepublic static int maxIndex(double[] doubles)
doubles
- the array of doublespublic static int maxIndex(int[] ints)
ints
- the array of integerspublic static double mean(double[] vector)
vector
- the arraypublic static int minIndex(int[] ints)
ints
- the array of integerspublic static int minIndex(double[] doubles)
doubles
- the array of doublespublic static void normalize(double[] doubles)
doubles
- the array of doubleIllegalArgumentException
- if sum is Zero or NaNpublic static void normalize(double[] doubles, double sum)
doubles
- the array of doublesum
- the value by which the doubles are to be normalizedIllegalArgumentException
- if sum is zero or NaNpublic static double[] logs2probs(double[] a)
a
- an array holding the natural logarithms of the probabilitiespublic static double probToLogOdds(double prob)
prob
- the probabilitiypublic static int round(double value)
value
- the double valuepublic static int probRound(double value, Random rand)
value
- the double valuerand
- the random number generatorpublic static void replaceMissingWithMAX_VALUE(double[] array)
array
- the array to be modified.public static double roundDouble(double value, int afterDecimalPoint)
value
- the double valueafterDecimalPoint
- the number of digits after the decimal pointpublic static int[] sort(int[] array)
array
- this array is not changed by the method!public static int[] sort(double[] array)
array
- this array is not changed by the method!public static int[] sortWithNoMissingValues(double[] array)
array
- the array to be sorted, which is modified if it has missing
valuespublic static int[] stableSort(double[] array)
array
- this array is not changed by the method!public static double variance(double[] vector)
vector
- the arraypublic static double sum(double[] doubles)
doubles
- the array of doublepublic static int sum(int[] ints)
ints
- the array of integerspublic static double xlogx(int c)
c
- an integer valuepublic static File convertToRelativePath(File absolute) throws Exception
absolute
- the File to convert to relative pathException
- if the path cannot be constructedpublic static boolean getDontShowDialog(String dialogName)
dialogName
- the name of the dialog to check (e.g.
weka.gui.GUICHooser.HowToFindPackageManager).public static void setDontShowDialog(String dialogName) throws Exception
dialogName
- the name of the dialog not to show again (e.g.
weka.gui.GUIChooser.HowToFindPackageManager).Exception
- if the marker file that is used to indicate that a named
dialog is not to be shown can't be created. This file lives in
$WEKA_HOME/systemDialogspublic static String getDontShowDialogResponse(String dialogName) throws Exception
dialogName
- the name of the dialog to check (e.g.
weka.gui.GUICHooser.HowToFindPackageManager).Exception
public static void setDontShowDialogResponse(String dialogName, String response) throws Exception
dialogName
- the name of the dialog to no longer displayresponse
- the user selected response when they closed the dialogException
- if there is a problem saving the informationpublic static String[] breakUp(String s, int columns)
s
- the string to processcolumns
- the width in columnspublic static String getGlobalInfo(Object object, boolean addCapabilities)
object
- the object to grab global info fromaddCapabilities
- true if capabilities information is to be added to
the resultpublic static String lineWrap(String input, int maxLineWidth)
input
- the string to line wrapmaxLineWidth
- the maximum permitted number of characters in a linepublic static Range configureRangeFromRangeStringOrAttributeNameList(Instances instanceInfo, String rangeString) throws Exception
instanceInfo
- the header of the instances to configure the range forrangeString
- a string containing a range of attribute indexes, or a
comma-separated list of attribute namesException
- if a problem occuredpublic static int[] takeSample(double[] weights, Random random)
weights
- the (positive) weights to be used to determine sample probabilities by normalizationrandom
- the random number generator to be usedpublic String getRevision()
getRevision
in interface RevisionHandler
public static void main(String[] ops)
ops
- some dummy optionsCopyright © 2020 University of Waikato, Hamilton, NZ. All rights reserved.