ptolemy.data.expr
Class UtilityFunctions

java.lang.Object
  extended byptolemy.data.expr.UtilityFunctions

public class UtilityFunctions
extends java.lang.Object

This class provides additional functions for use in the Ptolemy II expression language. All of the methods in this class are static and return an instance of Token. The expression language identifies the appropriate method to use by using reflection, matching the types of the arguments.

Since:
Ptolemy II 0.2
Version:
$Id: UtilityFunctions.java,v 1.113 2004/04/23 03:38:52 cxh Exp $
Author:
Neil Smyth, Christopher Hylands, Bart Kienhuis, Edward A. Lee, Steve Neuendorffer
Accepted Rating:
Red (cxh)
Proposed Rating:
Yellow (eal)

Constructor Summary
UtilityFunctions()
           
 
Method Summary
static java.lang.String asURL(java.lang.String fileName)
          Convert the argument from a fileName to a URL that begins with "file:".
static Token cast(Token token1, Token token2)
          Convert the second token to the type of the first.
static RecordToken constants()
          Return a record token that contains the names of all the constants and their values.
static java.lang.String findFile(java.lang.String name)
          Find a file or directory.
static LongToken freeMemory()
          Return the approximate number of bytes available for future object allocation.
static DoubleToken gaussian(double mean, double standardDeviation)
          Return a Gaussian random number.
static ArrayToken gaussian(double mean, double standardDeviation, int length)
          Return an array of Gaussian random numbers.
static DoubleMatrixToken gaussian(double mean, double standardDeviation, int rows, int columns)
          Return a matrix of Gaussian random numbers.
static java.lang.String getProperty(java.lang.String propertyName)
          Deprecated. Use StringUtilities.getProperty(String) instead
static java.lang.String inferType(java.lang.String string)
          Infer the type of the given string as an expression in the expression language.
static Token intersect(RecordToken record1, RecordToken record2)
          Find the intersection of two records.
static ArrayToken iterate(FunctionToken function, int length, Token initial)
          Iterate the specified function to produce an array of the specified length.
static Type iterateReturnType(Type functionType, Type lengthType, Type initialType)
          Return the return type of the iterate method, given the types of the argument.
static void loadLibrary(java.lang.String library)
          Load a library by first using the default platform dependent System.loadLibrary() method.
static ArrayToken map(FunctionToken function, ArrayToken array)
          Apply the specified function to the specified array and return an array with the results.
static Type mapReturnType(Type functionType, Type arrayTokenType)
          Return the return type of the map method, given the types of the argument.
static ScalarToken max(ArrayToken array)
          Return the maximum of the contents of the array.
static UnsignedByteToken max(UnsignedByteToken x, UnsignedByteToken y)
          Return the maximum of two unsigned bytes.
static Type maxReturnType(Type type)
          Return the (exact) return type of the max function above.
static ScalarToken min(ArrayToken array)
          Return the minimum of the contents of the array.
static UnsignedByteToken min(UnsignedByteToken x, UnsignedByteToken y)
          Return the minimum of two unsigned bytes.
static Type minReturnType(Type type)
          Return the (exact) return type of the min function above.
static ObjectToken model(java.lang.String classname)
          FIXME.
static StringToken property(java.lang.String propertyName)
          Get the specified property from the environment.
static ArrayToken random(int length)
          Return an array of IID random numbers with value greater than or equal to 0.0 and less than 1.0.
static DoubleMatrixToken random(int rows, int columns)
          Return a matrix of IID random numbers with value greater than or equal to 0.0 and less than 1.0.
static Type randomReturnType(Type type)
          Return the (exact) return type of the random function above.
static StringToken readFile(java.lang.String filename)
          Get the string text contained in the specified file.
static DoubleMatrixToken readMatrix(java.lang.String filename)
          Deprecated. Use eval(readFile()) instead.
static StringToken readResource(java.lang.String name)
          Get the string text contained in the specified resource, which is a file that is specified relative to the Java classpath.
static ArrayToken repeat(IntToken numberOfTimes, Token element)
          Create an array that contains the specified element repeated the specified number of times.
static Type repeatReturnType(Type type1, Type type2)
          Return the (exact) return type of the repeat function above.
static ArrayToken sort(ArrayToken array)
          Return a new array that is the sorted contents of a specified array, in ascending order.
static ArrayToken sortAscending(ArrayToken array)
          Return a new array that is the sorted contents of a specified array, in ascending order.
static Type sortAscendingReturnType(Type type)
          Return the (exact) return type of the sortAscending function above.
static ArrayToken sortDescending(ArrayToken array)
          Return a new array that is the sorted contents of a specified array, in descending order.
static Type sortDescendingReturnType(Type type)
          Return the (exact) return type of the sortDescending function above.
static Type sortReturnType(Type type)
          Return the (exact) return type of the sort function above.
static Token sum(ArrayToken array)
          Return the sum of the elements in the specified array.
static Type sumReturnType(Type type)
          Return the (exact) return type of the sum function above.
static LongToken totalMemory()
          Return the approximate number of bytes used by current objects and available for future object allocation.
static java.lang.String traceEvaluation(java.lang.String string)
          Evaluate the given string as an expression in the expression language.
static BooleanToken within(Token token1, Token token2, double distance)
          Return true if the first argument is close in value to the second, where "close" means that it is within the distance given by the third argument.
static DoubleMatrixToken zeroMatrix(int rows, int columns)
          Deprecated. Use zeroMatrixDouble instead.
static ComplexMatrixToken zeroMatrixComplex(int rows, int columns)
          Return a complex zero matrix with the given number of rows and columns.
static DoubleMatrixToken zeroMatrixDouble(int rows, int columns)
          Return a double zero matrix with the given number of rows and columns.
static IntMatrixToken zeroMatrixInt(int rows, int columns)
          Return a int zero matrix with the given number of rows and columns.
static LongMatrixToken zeroMatrixLong(int rows, int columns)
          Return a long zero matrix with the given number of rows and columns.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

UtilityFunctions

public UtilityFunctions()
Method Detail

asURL

public static java.lang.String asURL(java.lang.String fileName)
Convert the argument from a fileName to a URL that begins with "file:".

Parameters:
fileName - The name of the file to be converted.
Returns:
the URL that is equivalent to the file

cast

public static Token cast(Token token1,
                         Token token2)
                  throws IllegalActionException
Convert the second token to the type of the first.

Throws:
IllegalActionException - If the token cannot be converted.

constants

public static RecordToken constants()
Return a record token that contains the names of all the constants and their values.

Returns:
A token containing the names of all the constants and their values.
Since:
Ptolemy II 2.1

findFile

public static java.lang.String findFile(java.lang.String name)
Find a file or directory. If the file does not exist as is, then search the current working directory, the user's home directory, and finally, the classpath.

Parameters:
name - Path of a file or directory to find.
Returns:
Canonical absolute path if the file or directory is found, otherwise the argument is returned unchanged.

freeMemory

public static LongToken freeMemory()
Return the approximate number of bytes available for future object allocation. Note that requesting a garbage collection may change this value.

Returns:
The approximate number of bytes available.
See Also:
totalMemory()

gaussian

public static DoubleToken gaussian(double mean,
                                   double standardDeviation)
Return a Gaussian random number.

Parameters:
mean - The mean.
standardDeviation - The standard deviation.
Returns:
An observation of a Gaussian random variable.

gaussian

public static ArrayToken gaussian(double mean,
                                  double standardDeviation,
                                  int length)
Return an array of Gaussian random numbers.

Parameters:
mean - The mean.
standardDeviation - The standard deviation.
length - The length of the array.
Returns:
An array of doubles with IID Gaussian random variables.

gaussian

public static DoubleMatrixToken gaussian(double mean,
                                         double standardDeviation,
                                         int rows,
                                         int columns)
Return a matrix of Gaussian random numbers.

Parameters:
mean - The mean.
standardDeviation - The standard deviation.
rows - The number of rows.
columns - The number of columns.
Returns:
A matrix of observations of a Gaussian random variable.

getProperty

public static java.lang.String getProperty(java.lang.String propertyName)
Deprecated. Use StringUtilities.getProperty(String) instead

Get the specified property from the environment. An empty string is returned if the argument environment variable does not exist, though if certain properties are not defined, then we make various attempts to determine them and then set them. See the javadoc page for java.util.System.getProperties() for a list of system properties.

The following properties are handled specially

"ptolemy.ptII.dir"
vergil usually sets the ptolemy.ptII.dir property to the value of $PTII. However, if we are running under Web Start, then this property might not be set, in which case we look for "ptolemy/kernel/util/NamedObj.class" and set the property accordingly.
"ptolemy.ptII.dirAsURL"
Return $PTII as a URL. For example, if $PTII was c:\ptII, then return file:/c:/ptII/.
"user.dir"
Return the canonical path name to the current working directory. This is necessary because under JDK1.4.1 System.getProperty() returns c:/foo whereas most of the other methods that operate on path names return C:/foo.

Parameters:
propertyName - The name of property.
Returns:
A String containing the string value of the property.

inferType

public static java.lang.String inferType(java.lang.String string)
                                  throws IllegalActionException
Infer the type of the given string as an expression in the expression language. Return a string representation of the given type.

Parameters:
string - The string to be parsed and evaluated.
Returns:
A string representing an inferred type.
Throws:
IllegalActionException

intersect

public static Token intersect(RecordToken record1,
                              RecordToken record2)
                       throws IllegalActionException
Find the intersection of two records. The field names are intersected, and the values are taken from the first record.

Example: intersect({a = 1, b = 2}, {a = 3, c = 4}) returns {a = 1}.

Parameters:
record1 - The first record to intersect. The result gets its values from this record.
record2 - The second record to intersect.
Returns:
A RecordToken containing the result.
Throws:
IllegalActionException

iterate

public static ArrayToken iterate(FunctionToken function,
                                 int length,
                                 Token initial)
                          throws IllegalActionException
Iterate the specified function to produce an array of the specified length. The first element of the output array is the initial argument, the second is the result of applying the function to initial, the third is the result of applying the function to that result, etc. The length argument is required to be greater than 1.

Parameters:
function - A single-argument function to iterate.
length - The length of the resulting array.
initial - The first element of the result.
Returns:
A new array that is the result of applying the function repeatedly.
Throws:
IllegalActionException - If the specified function does not take exactly one argument, or if an error occurs applying the function.

iterateReturnType

public static Type iterateReturnType(Type functionType,
                                     Type lengthType,
                                     Type initialType)
                              throws IllegalActionException
Return the return type of the iterate method, given the types of the argument.

Parameters:
functionType - The type of the function to iterate.
lengthType - The type of the length argument.
initialType - The type of the first element of the result.
Returns:
The type of the result.
Throws:
IllegalActionException - If the specified function does not take exactly one argument, or if the type signature of the function is not compatible with the other arguments.

loadLibrary

public static void loadLibrary(java.lang.String library)
Load a library by first using the default platform dependent System.loadLibrary() method. If the library cannot be loaded using System.loadLibrary(), then search for the library using findFile(String) and if the library is found, load it using System.load(). If the library is not found by findFile() and the pathname contains a / then we call System.loadLibrary() the filename after the last /. This step is necessary to support native methods under Webstart, which looks for libraries at the top level. If all of the above fails, we throw the initial exception.

Parameters:
library - the name of the library to be loaded. The name should not include the platform dependent suffix.

map

public static ArrayToken map(FunctionToken function,
                             ArrayToken array)
                      throws IllegalActionException
Apply the specified function to the specified array and return an array with the results. The function must take at least one argument. If the function takes more than one argument, then the specified array should be an array of arrays, where each subarray is a set of arguments. Since arrays in the expression language can only contain elements of the same type, this method will only work for functions whose arguments are all of the same type.

Parameters:
function - A function with at least one argument.
array - The array to which to apply the function.
Returns:
A new array that is the result of applying the function to the specified array.
Throws:
IllegalActionException - If the specified function does not take at least one argument, or if an error occurs applying the function, or if the number of arguments does not match the subarray lengths.

mapReturnType

public static Type mapReturnType(Type functionType,
                                 Type arrayTokenType)
                          throws IllegalActionException
Return the return type of the map method, given the types of the argument.

Parameters:
functionType - The type of the function to map.
arrayTokenType - The type of array to apply the specified function on.
Returns:
The type of the result.
Throws:
IllegalActionException - If the specified function does not take at least one argument, or if the type signature of the function is not compatible with the array elements, or if the specified function has different argument type.

max

public static UnsignedByteToken max(UnsignedByteToken x,
                                    UnsignedByteToken y)
Return the maximum of two unsigned bytes.

Parameters:
x - An unsigned byte.
y - An unsigned byte.
Returns:
The maximum of x and y.

max

public static ScalarToken max(ArrayToken array)
                       throws IllegalActionException
Return the maximum of the contents of the array.

Parameters:
array - An array of scalar tokens.
Returns:
The largest element of the array.
Throws:
IllegalActionException - If the array is empty or it contains tokens that are not scalar or it contains complex tokens.

maxReturnType

public static Type maxReturnType(Type type)
Return the (exact) return type of the max function above. If the argument is an array type, then return its element type, otherwise return BaseType.UNKNOWN.

Parameters:
type - The type of the argument to the corresponding function.
Returns:
The type of the value returned from the corresponding function.

min

public static UnsignedByteToken min(UnsignedByteToken x,
                                    UnsignedByteToken y)
Return the minimum of two unsigned bytes.

Parameters:
x - An unsigned byte.
y - An unsigned byte.
Returns:
The minimum of x and y.

min

public static ScalarToken min(ArrayToken array)
                       throws IllegalActionException
Return the minimum of the contents of the array.

Parameters:
array - An array of scalar tokens.
Returns:
The largest element of the array.
Throws:
IllegalActionException - If the array is empty or it contains tokens that are not scalar or it contains complex tokens.

minReturnType

public static Type minReturnType(Type type)
Return the (exact) return type of the min function above. If the argument is an array type, then return its element type, otherwise return BaseType.UNKNOWN.

Parameters:
type - The type of the argument to the corresponding function.
Returns:
The type of the value returned from the corresponding function.

model

public static ObjectToken model(java.lang.String classname)
                         throws IllegalActionException
FIXME. Placeholder for a function that will return a model.

Throws:
IllegalActionException

property

public static StringToken property(java.lang.String propertyName)
Get the specified property from the environment. An empty string is returned if the argument environment variable does not exist. See the javadoc page for java.util.System.getProperties() for a list of system properties. Example properties include:
"java.version"
the version of the JDK.
"ptolemy.ptII.dir"
The value of $PTII, which is the name of the directory in which Ptolemy II is installed.
"ptolemy.ptII.dirAsURL"
The value of $PTII as a URL, which is the name of the directory in which Ptolemy II is installed.
"user.dir"
The canonical path name to the current working directory.

Parameters:
propertyName - The name of property.
Returns:
A token containing the string value of the property.
See Also:
StringUtilities.getProperty(String)

random

public static ArrayToken random(int length)
Return an array of IID random numbers with value greater than or equal to 0.0 and less than 1.0.

Parameters:
length - The length of the array.
Returns:
An array of doubles with IID random variables.

random

public static DoubleMatrixToken random(int rows,
                                       int columns)
Return a matrix of IID random numbers with value greater than or equal to 0.0 and less than 1.0.

Parameters:
rows - The number of rows.
columns - The number of columns.
Returns:
A matrix of IID random variables.

randomReturnType

public static Type randomReturnType(Type type)
Return the (exact) return type of the random function above. If the argument is BaseType.INT, then return and ArrayType of BaseType.DOUBLE, otherwise return BaseType.UNKNOWN.

Parameters:
type - The type of the argument to the corresponding function.
Returns:
The type of the value returned from the corresponding function.

readFile

public static StringToken readFile(java.lang.String filename)
                            throws IllegalActionException
Get the string text contained in the specified file. The argument is first interpreted using findFile(), so file names relative to the current working directory, the user's home directory, or the classpath are understood. If the file contains text that is a valid expression in the expression language, then that text can interpreted using the eval() function in ptolemy.data.expr.ASTPtFunctionApplicationNode. For example: eval(readFile("filename"))

Note that readFile() does not work inside applets, use readResource(String) instead.

Parameters:
filename - The name of the file to read from.
Returns:
A StringToken containing the text contained in the specified file.
Throws:
IllegalActionException - If the file cannot be opened.
See Also:
ASTPtFunctionApplicationNode, readResource(String)

readMatrix

public static DoubleMatrixToken readMatrix(java.lang.String filename)
                                    throws IllegalActionException
Deprecated. Use eval(readFile()) instead.

Read a file that contains a matrix of reals in Matlab notation.

Parameters:
filename - The filename.
Returns:
The matrix defined in the file.
Throws:
IllegalActionException - If the file cannot be opened.

readResource

public static StringToken readResource(java.lang.String name)
                                throws IllegalActionException
Get the string text contained in the specified resource, which is a file that is specified relative to the Java classpath. Resource strings look like filenames without a leading slash. If the file contains text that is a valid expression in the expression language, then that text can interpreted using the eval() function in ptolemy.data.expr.ASTPtFunctionApplicationNode. For example: eval(readFile("filename"))

Parameters:
name - The name of the resource to read from.
Returns:
A StringToken containing the text contained in the specified resource.
Throws:
IllegalActionException - If the resource cannot be opened.
See Also:
ASTPtFunctionApplicationNode, readFile(String)

repeat

public static ArrayToken repeat(IntToken numberOfTimes,
                                Token element)
Create an array that contains the specified element repeated the specified number of times.

Parameters:
numberOfTimes - The number of times to repeat the element.
element - The element to repeat.
Returns:
A new array containing the specified element repeated the specified number of times.

repeatReturnType

public static Type repeatReturnType(Type type1,
                                    Type type2)
Return the (exact) return type of the repeat function above. This function always returns an ArrayType whose element type is the second argument.

Parameters:
type1 - The type of the first argument to the corresponding function.
type2 - The type of the second argument to the corresponding function.
Returns:
The type of the value returned from the corresponding function.

sort

public static ArrayToken sort(ArrayToken array)
                       throws IllegalActionException
Return a new array that is the sorted contents of a specified array, in ascending order. The specified array can contain scalar tokens (except complex) or string tokens. If the specified array is empty, then it is returned.

Parameters:
array - An array of scalar tokens.
Returns:
A new sorted array.
Throws:
IllegalActionException - If the array contains tokens that are complex or are not scalar or string tokens.

sortReturnType

public static Type sortReturnType(Type type)
Return the (exact) return type of the sort function above. If the argument is an array type with elements that are strings or scalars other than complex, then return the argument; otherwise return BaseType.UNKNOWN.

Parameters:
type - The type of the argument to the corresponding function.
Returns:
The type of the value returned from the corresponding function.

sortAscending

public static ArrayToken sortAscending(ArrayToken array)
                                throws IllegalActionException
Return a new array that is the sorted contents of a specified array, in ascending order. The specified array can contain scalar tokens (except complex) or string tokens. If the specified array is empty, then it is returned. This method is identical to sort(), and is provided only for naming uniformity.

Parameters:
array - An array of scalar tokens.
Returns:
A new sorted array.
Throws:
IllegalActionException - If the array contains tokens that are complex or are not scalar or string tokens.
See Also:
sort(ArrayToken), sortDescending(ArrayToken)

sortAscendingReturnType

public static Type sortAscendingReturnType(Type type)
Return the (exact) return type of the sortAscending function above. If the argument is an array type with elements that are strings or scalars other than complex, then return the argument; otherwise return BaseType.UNKNOWN.

Parameters:
type - The type of the argument to the corresponding function.
Returns:
The type of the value returned from the corresponding function.

sortDescending

public static ArrayToken sortDescending(ArrayToken array)
                                 throws IllegalActionException
Return a new array that is the sorted contents of a specified array, in descending order. The specified array can contain scalar tokens (except complex) or string tokens. If the specified array is empty, then it is returned.

Parameters:
array - An array of scalar tokens.
Returns:
A new sorted array.
Throws:
IllegalActionException - If the array contains tokens that are complex or are not scalar or string tokens.

sortDescendingReturnType

public static Type sortDescendingReturnType(Type type)
Return the (exact) return type of the sortDescending function above. If the argument is an array type with elements that are strings or scalars other than complex, then return the argument; otherwise return BaseType.UNKNOWN.

Parameters:
type - The type of the argument to the corresponding function.
Returns:
The type of the value returned from the corresponding function.

sum

public static final Token sum(ArrayToken array)
                       throws IllegalActionException
Return the sum of the elements in the specified array. This method is polymorphic in that it can sum any array whose elements support addition.

Parameters:
array - An array.
Returns:
The sum of the elements of the array.
Throws:
IllegalActionException - If the length of the array is zero, or if the array elements do not support addition.

sumReturnType

public static Type sumReturnType(Type type)
Return the (exact) return type of the sum function above. If the argument is an array type, then return its element type, otherwise return BaseType.UNKNOWN.

Parameters:
type - The type of the argument to the corresponding function.
Returns:
The type of the value returned from the corresponding function.

totalMemory

public static LongToken totalMemory()
Return the approximate number of bytes used by current objects and available for future object allocation.

Returns:
The total number of bytes used by the JVM.
See Also:
freeMemory()

traceEvaluation

public static java.lang.String traceEvaluation(java.lang.String string)
                                        throws IllegalActionException
Evaluate the given string as an expression in the expression language. Instead of returning the resulting value, return a trace of the evaluation, including such useful information as what registered method is actually invoked.

Parameters:
string - The string to be parsed and evaluated.
Returns:
A string representing an evaluation trace.
Throws:
IllegalActionException

within

public static BooleanToken within(Token token1,
                                  Token token2,
                                  double distance)
                           throws IllegalActionException
Return true if the first argument is close in value to the second, where "close" means that it is within the distance given by the third argument. Exactly what this means depends on the data type. This method uses the isCloseTo() method of the first token.

Parameters:
token1 - The first token.
token2 - The second token.
distance - The distance criterion.
Returns:
a true-valued token if the first two arguments are close enough.
Throws:
IllegalActionException - If the first two arguments cannot be compared.

zeroMatrix

public static DoubleMatrixToken zeroMatrix(int rows,
                                           int columns)
Deprecated. Use zeroMatrixDouble instead.

Return a double zero matrix with the given number of rows and columns.

Returns:
The zero matrix with the given number of rows and columns.

zeroMatrixComplex

public static ComplexMatrixToken zeroMatrixComplex(int rows,
                                                   int columns)
Return a complex zero matrix with the given number of rows and columns.

Returns:
The zero matrix with the given number of rows and columns.

zeroMatrixDouble

public static DoubleMatrixToken zeroMatrixDouble(int rows,
                                                 int columns)
Return a double zero matrix with the given number of rows and columns.

Returns:
The zero matrix with the given number of rows and columns.

zeroMatrixInt

public static IntMatrixToken zeroMatrixInt(int rows,
                                           int columns)
Return a int zero matrix with the given number of rows and columns.

Returns:
The zero matrix with the given number of rows and columns.

zeroMatrixLong

public static LongMatrixToken zeroMatrixLong(int rows,
                                             int columns)
Return a long zero matrix with the given number of rows and columns.

Returns:
The zero matrix with the given number of rows and columns.