ptolemy.matlab
Class Engine

java.lang.Object
  extended by ptolemy.matlab.Engine

public class Engine
extends java.lang.Object

Provides a java API to the matlab environment. It uses an intermediary C++ language layer (ptmatlab) that converts between the java environment using the Java Native Interface and the matlab environment using the matlab engine API and associated mx-functions.

The intermediary layer is built as a DLL on Windows systems (ptmatlab.dll). This shared library is placed into the $PTII/bin directory (that should be in the user's path) when this package is built. Ptmatlab depends on matlab's engine API shared libraries (libeng and libmx) that should also be installed in the user's path (usually the case when matlab is installed and matlab's bin directory is added to the path).

The bulk of the work done by this class is the conversion between PtolemyII Tokens and matlab variables ("mxArrays").

get(long[] eng, String name) and get(long[], String, Engine.ConversionParameters) convert a matlab engine mxArray (ma) variable to a Ptolemy II Token. Recursion is used if ma is a struct or cell. The type of the Token returned is determined according to the following table:

Conversion from matlab to PtolemyII types (get())
Matlab TypePtolemyII Token
'double' Double, if mxArray dimension is 1x1 and Engine.ConversionParameters.getScalarMatrices is true, DoubleMatrix otherwise. Complex, if mxArray is mxCOMPLEX, 1x1, and Engine.ConversionParameters.getScalarMatrices is true, ComplexMatrix otherwise.
Note: If Engine.ConversionParameters.getIntMatrices is true and all matrix double values can be cast to integers without loss of precision then an IntToken or IntTokenMatrix is returned.
'struct' RecordToken, if mxArray dimension 1x1, ArrayToken of ArrayTokens of RecordTokens {{RecordToken,...}, {...}} ("two-dimensional" ArrayToken) otherwise.
'cell' ArrayToken of whatever Tokens the cell elements resolve to through recursion of _convertMxArrayToToken(). In the special case of a cell array of doubles, an {int} is always returned if all cell double values can be losslessly converted to integers. Note that PtolemyII is more restrictive here in that it requires all array elements to be of the same type (not all matlab cell variables may be converted to PtolemyII ArrayTokens).
'char' StringToken, if the mxArray is 1xn, ArrayToken of StringTokens otherwise.

put(long[] eng, String name, Token t) converts a PtolemyII Token to a matlab engine mxArray. Recursion is used if t is a RecordToken or ArrayToken. The type of mxArray created is determined according to the following table.

Conversion from PtolemyII to matlab types (put())
PtolemyII TokenMatlab type
ArrayToken 'cell', 1xn, elements are determined by recursing this method on ArrayToken elements.
RecordToken 'struct', 1x1, fields are determined by recursing this method on RecordToken fields
StringToken 'char', 1xn
ComplexMatrixToken 'double', mxCOMPLEX, nxm
MatrixToken 'double', mxREAL, nxm
ComplexToken 'double', mxCOMPLEX, 1x1
ScalarToken 'double', mxREAL, 1x1

Debug statements to stdout are enabled by calling setDebugging(byte) with a byte parameter > 0. 1 enables basic tracing, 2 includes traces from the dll as well.

evalString(long[] eng, String) send a string to the matlab engine for evaluation. open() and close(long[]) are used to open / close the connection to the matlab engine.

All callers share the same matlab engine and its workspace. Methods of Engine synchronize on the static semaphore to prevent overlapping calls to the same method from different threads. Use Engine. semaphore to synchronize across multiple method calls if needed.

Since:
Ptolemy II 2.0
Version:
$Id: Engine.java 57731 2010-04-29 20:46:06Z crawl $
Author:
Zoltan Kemenczy and Sean Simmons, Research in Motion Limited.
Accepted Rating:
Red (cxh)
Proposed Rating:
Yellow (zkemenczy)

Nested Class Summary
static class Engine.ConversionParameters
          Data conversion parameters used by get(long[], String, Engine.ConversionParameters).
 
Field Summary
private  byte debug
           
(package private) static int engOutputBufferSize
          Output buffer (allocated for each opened instance) size.
(package private) static java.lang.String errNotOpened
          Copy of a common error message.
static java.lang.Object semaphore
          Used for synchronization.
 
Constructor Summary
Engine()
          Construct an instance of the matlab engine interface.
 
Method Summary
private  Token _convertMxArrayToToken(long ma, Engine.ConversionParameters par)
           
private  long _createMxArray(java.lang.String name, Token t)
           
private  boolean _doubleisInteger(double d)
           
 int close(long[] eng)
          Close a connection to a matlab engine.
 int evalString(long[] eng, java.lang.String evalStr)
          Send a string for evaluation to the matlab engine.
 Token get(long[] eng, java.lang.String name)
          Return a Token from the matlab engine using default Engine.ConversionParameters values.
 Token get(long[] eng, java.lang.String name, Engine.ConversionParameters par)
          Return a Token from the matlab engine using specified Engine.ConversionParameters values.
 StringToken getOutput(long[] eng)
          Get last matlab stdout.
 long[] open()
          Open a connection to the default matlab engine installed on this host with its output buffered.
 long[] open(boolean needOutput)
          Open a connection to the default matlab engine installed on this host with specified output buffering.
 long[] open(java.lang.String startCmd, boolean needOutput)
          Open a connection to a matlab engine.
private  long ptmatlabCreateCellMatrix(java.lang.String name, int n, int m)
           
private  long ptmatlabCreateComplexMatrix(java.lang.String name, Complex[][] a, int n, int m)
           
private  long ptmatlabCreateComplexMatrixOneDim(java.lang.String name, Complex[] a, int length)
           
private  long ptmatlabCreateDoubleMatrix(java.lang.String name, double[][] a, int n, int m)
           
private  long ptmatlabCreateDoubleMatrixOneDim(java.lang.String name, double[] a, int length)
           
private  long ptmatlabCreateString(java.lang.String name, java.lang.String s, int n, int m)
           
private  long ptmatlabCreateStructMatrix(java.lang.String name, java.lang.Object[] fieldNames, int n, int m)
           
private  void ptmatlabDestroy(long mxArray, java.lang.String name)
           
private  int ptmatlabEngClose(long e, long outputBuffer)
           
private  int ptmatlabEngEvalString(long e, java.lang.String s)
           
private  long ptmatlabEngGetArray(long e, java.lang.String name)
           
private  long ptmatlabEngOpen(java.lang.String startCmd)
           
private  long ptmatlabEngOutputBuffer(long e, int n)
           
private  int ptmatlabEngPutArray(long e, java.lang.String name, long mxArray)
           
private  long ptmatlabGetCell(long mxArray, int n, int m)
           
private  java.lang.String ptmatlabGetClassName(long mxArray)
           
private  Complex[][] ptmatlabGetComplexMatrix(long mxArray, int n, int m)
           
private  int[] ptmatlabGetDimensions(long mxArray)
           
private  double[][] ptmatlabGetDoubleMatrix(long mxArray, int n, int m)
           
private  long ptmatlabGetFieldByNumber(long mxArray, int k, int n, int m)
           
private  java.lang.String ptmatlabGetFieldNameByNumber(long mxArray, int k)
           
private  int[][] ptmatlabGetLogicalMatrix(long mxArray, int nRows, int nCols)
           
private  int ptmatlabGetNumberOfFields(long mxArray)
           
private  java.lang.String ptmatlabGetOutput(long outputBuffer, int n)
           
private  java.lang.String ptmatlabGetString(long mxArray, int n)
           
private  boolean ptmatlabIsComplex(long mxArray)
           
private  void ptmatlabSetCell(java.lang.String name, long mxArray, int n, int m, long valueMxArray)
           
private  void ptmatlabSetString(java.lang.String name, long mxArray, int n, java.lang.String s, int slen)
           
private  void ptmatlabSetStructField(java.lang.String name, long mxArray, java.lang.String fieldName, int n, int m, long valueMxArray)
           
 int put(long[] eng, java.lang.String name, Token t)
          Create a matlab variable using name and a Token.
 void setDebugging(byte d)
          Enable/disable debug statements to stdout.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

engOutputBufferSize

static int engOutputBufferSize
Output buffer (allocated for each opened instance) size.


semaphore

public static final java.lang.Object semaphore
Used for synchronization.


errNotOpened

static java.lang.String errNotOpened
Copy of a common error message.


debug

private byte debug
Constructor Detail

Engine

public Engine()
Construct an instance of the matlab engine interface. The matlab engine is not activated at this time.

Ptmatlab.dll is loaded by the system library loader the first time this class is loaded.

See Also:
open()
Method Detail

setDebugging

public void setDebugging(byte d)
Enable/disable debug statements to stdout.

Parameters:
d - Non-zero to enable debug statements, zero to disable.

open

public long[] open()
            throws IllegalActionException
Open a connection to the default matlab engine installed on this host with its output buffered.

Returns:
long[2] retval engine handle; retval[0] is the real engine handle, retval[1] is a pointer to the engine output buffer; both should be preserved and passed to subsequent engine calls.
Throws:
IllegalActionException - If the matlab engine open is unsuccessful. This will typically occur if ptmatlab (.dll) cannot be located or if the matlab bin directory is not in the path.
See Also:
open(String, boolean)

open

public long[] open(boolean needOutput)
            throws IllegalActionException
Open a connection to the default matlab engine installed on this host with specified output buffering.

Parameters:
needOutput - selects whether the output should be buffered or not.
Returns:
long[2] retval engine handle; retval[0] is the real engine handle, retval[1] is a pointer to the engine output buffer; both should be preserved and passed to subsequent engine calls.
Throws:
IllegalActionException - If the matlab engine open is unsuccessful. This will typically occur if ptmatlab (.dll) cannot be located or if the matlab bin directory is not in the path.
See Also:
open(String, boolean)

open

public long[] open(java.lang.String startCmd,
                   boolean needOutput)
            throws IllegalActionException
Open a connection to a matlab engine.

For more information, see the matlab engine API reference engOpen()

Parameters:
startCmd - hostname or command to use to start the engine.
needOutput - selects whether the output should be buffered or not.
Returns:
long[2] retval engine handle; retval[0] is the real engine handle, retval[1] is a pointer to the engine output buffer; both should be preserved and passed to subsequent engine calls.
Throws:
IllegalActionException - If the matlab engine open is unsuccessful. This will typically occur if ptmatlab (.dll) cannot be located or if the matlab bin directory is not in the path.
See Also:
getOutput(long[])

close

public int close(long[] eng)
Close a connection to a matlab engine. This will also close the matlab engine if this instance was the last user of the matlab engine.

For more information, see matlab engine API reference engClose()

Parameters:
eng - An array of longs with length 2. eng[0] is the real engine handle, eng[1] is a pointer to the engine output buffer.
Returns:
The value returned by calling engClose() in the Matlab interface.

evalString

public int evalString(long[] eng,
                      java.lang.String evalStr)
               throws IllegalActionException
Send a string for evaluation to the matlab engine.

Parameters:
eng - An array of two longs; eng[0] is the real engine handle, eng[1] is a pointer to the engine output buffer.
evalStr - string to evaluate.
Returns:
The value returned by the ptmatlabEngEvalString() native method.
Throws:
IllegalActionException - If the matlab engine is not opened.

get

public Token get(long[] eng,
                 java.lang.String name)
          throws IllegalActionException
Return a Token from the matlab engine using default Engine.ConversionParameters values.

Parameters:
eng - An array of longs with length 2. eng[0] is the real engine handle, eng[1] is a pointer to the engine output buffer.
name - Matlab variable name used to initialize the returned Token
Returns:
PtolemyII Token.
Throws:
IllegalActionException - If the matlab engine is not opened, or if the matlab variable was not found in the engine. In this case, the matlab engine's stdout is included in the exception message.
See Also:
Expression

get

public Token get(long[] eng,
                 java.lang.String name,
                 Engine.ConversionParameters par)
          throws IllegalActionException
Return a Token from the matlab engine using specified Engine.ConversionParameters values.

Parameters:
eng - An array of longs with length 2. eng[0] is the real engine handle, eng[1] is a pointer to the engine output buffer.
name - Matlab variable name used to initialize the returned Token
par - The ConversionParameter to use.
Returns:
PtolemyII Token.
Throws:
IllegalActionException - If the matlab engine is not opened, or if the matlab variable was not found in the engine. In this case, the matlab engine's stdout is included in the exception message.
See Also:
Expression

getOutput

public StringToken getOutput(long[] eng)
Get last matlab stdout.

Parameters:
eng - An array of longs with length 2. eng[0] is the real engine handle, eng[1] is a pointer to the engine output buffer.
Returns:
PtolemyII StringToken

put

public int put(long[] eng,
               java.lang.String name,
               Token t)
        throws IllegalActionException
Create a matlab variable using name and a Token.

Parameters:
eng - An array of longs with length 2. eng[0] is the real engine handle, eng[1] is a pointer to the engine output buffer.
name - matlab variable name.
t - Token to provide value.
Returns:
The result of calling engPutArray() in the Matlab C library.
Throws:
IllegalActionException - If the engine is not opened.
See Also:
Engine

ptmatlabEngOpen

private long ptmatlabEngOpen(java.lang.String startCmd)

ptmatlabEngClose

private int ptmatlabEngClose(long e,
                             long outputBuffer)

ptmatlabEngEvalString

private int ptmatlabEngEvalString(long e,
                                  java.lang.String s)

ptmatlabEngGetArray

private long ptmatlabEngGetArray(long e,
                                 java.lang.String name)

ptmatlabEngPutArray

private int ptmatlabEngPutArray(long e,
                                java.lang.String name,
                                long mxArray)

ptmatlabEngOutputBuffer

private long ptmatlabEngOutputBuffer(long e,
                                     int n)

ptmatlabCreateCellMatrix

private long ptmatlabCreateCellMatrix(java.lang.String name,
                                      int n,
                                      int m)

ptmatlabCreateString

private long ptmatlabCreateString(java.lang.String name,
                                  java.lang.String s,
                                  int n,
                                  int m)

ptmatlabCreateDoubleMatrixOneDim

private long ptmatlabCreateDoubleMatrixOneDim(java.lang.String name,
                                              double[] a,
                                              int length)

ptmatlabCreateDoubleMatrix

private long ptmatlabCreateDoubleMatrix(java.lang.String name,
                                        double[][] a,
                                        int n,
                                        int m)

ptmatlabCreateComplexMatrixOneDim

private long ptmatlabCreateComplexMatrixOneDim(java.lang.String name,
                                               Complex[] a,
                                               int length)

ptmatlabCreateComplexMatrix

private long ptmatlabCreateComplexMatrix(java.lang.String name,
                                         Complex[][] a,
                                         int n,
                                         int m)

ptmatlabCreateStructMatrix

private long ptmatlabCreateStructMatrix(java.lang.String name,
                                        java.lang.Object[] fieldNames,
                                        int n,
                                        int m)

ptmatlabDestroy

private void ptmatlabDestroy(long mxArray,
                             java.lang.String name)

ptmatlabGetCell

private long ptmatlabGetCell(long mxArray,
                             int n,
                             int m)

ptmatlabGetClassName

private java.lang.String ptmatlabGetClassName(long mxArray)

ptmatlabGetDimensions

private int[] ptmatlabGetDimensions(long mxArray)

ptmatlabGetComplexMatrix

private Complex[][] ptmatlabGetComplexMatrix(long mxArray,
                                             int n,
                                             int m)

ptmatlabGetDoubleMatrix

private double[][] ptmatlabGetDoubleMatrix(long mxArray,
                                           int n,
                                           int m)

ptmatlabGetLogicalMatrix

private int[][] ptmatlabGetLogicalMatrix(long mxArray,
                                         int nRows,
                                         int nCols)

ptmatlabGetFieldNameByNumber

private java.lang.String ptmatlabGetFieldNameByNumber(long mxArray,
                                                      int k)

ptmatlabGetFieldByNumber

private long ptmatlabGetFieldByNumber(long mxArray,
                                      int k,
                                      int n,
                                      int m)

ptmatlabGetNumberOfFields

private int ptmatlabGetNumberOfFields(long mxArray)

ptmatlabGetString

private java.lang.String ptmatlabGetString(long mxArray,
                                           int n)

ptmatlabGetOutput

private java.lang.String ptmatlabGetOutput(long outputBuffer,
                                           int n)

ptmatlabIsComplex

private boolean ptmatlabIsComplex(long mxArray)

ptmatlabSetCell

private void ptmatlabSetCell(java.lang.String name,
                             long mxArray,
                             int n,
                             int m,
                             long valueMxArray)

ptmatlabSetString

private void ptmatlabSetString(java.lang.String name,
                               long mxArray,
                               int n,
                               java.lang.String s,
                               int slen)

ptmatlabSetStructField

private void ptmatlabSetStructField(java.lang.String name,
                                    long mxArray,
                                    java.lang.String fieldName,
                                    int n,
                                    int m,
                                    long valueMxArray)

_convertMxArrayToToken

private Token _convertMxArrayToToken(long ma,
                                     Engine.ConversionParameters par)
                              throws IllegalActionException
Throws:
IllegalActionException

_createMxArray

private long _createMxArray(java.lang.String name,
                            Token t)
                     throws IllegalActionException
Throws:
IllegalActionException

_doubleisInteger

private boolean _doubleisInteger(double d)