AMPL#
- public class AMPL extends AMPLBase implements Closeable#
An AMPL translator. An object of this class can be used to do the following tasks:
Run AMPL code. See
AMPL.eval
.Read models and data from files. See
AMPL.read
andAMPL.readData
.Solve optimization problems constructed from model and data (see
AMPL.solve
).Access single elements of an optimization problem. See the generic
AMPL.getEntity
and the genericAMPL.getVariable
,AMPL.getObjective
,AMPL.getConstraint
,AMPL.getSet
andAMPL.getParameter
.Access lists of available elements of an optimization problem. See
AMPL.getVariables
,AMPL.getObjectives
,AMPL.getConstraints
,AMPL.getSets
andAMPL.getParameters
.
AMPL stores one or more problems which may consume substantial amount of memory. An AMPL object without any references to it will eventually be freed by the Java garbage collector and all the memory and other resources associated with it will be released. This includes any resources which are out of scope of the garbage collector such as open files or memory managed by the native code. Call
AMPL.close
to release these resources explicitly.The initialization of the Java representation of the AMPL entities (any class derived from
Entity
) is lazy and consists of two steps. When a function listing available elements is called, only a shallow list with names, types and declarations of the elements is populated. The same happens when a reference to a Java representation of one entity is obtained (through a call toAMPL.getEntity
or any other single entity factory function). When accessing any instance of an entity (through the methods ‘get’ of any class), the (memory hungry) list of instances for that entity is created.Consistency is maintained automatically. Any command issued to the translator through
AMPL.eval
and similar functions invalidates all entities, and any further access to any entity will require communication between the native translator and the Java code. Conversely, any operation called through the Java equivalent function, like fixing variables or solving the model will invalidate only the entities involved. A list of dependencies between entities is automatically updated.Error handling is two-faced:
Errors coming from the underlying AMPL translator (e.g. syntax errors and warnings obtained calling the
AMPL.eval
method) are handled by theErrorHandler
which can be set and get viaAMPL.getErrorHandler()
andAMPL.setErrorHandler()
.Generic errors coming from misusing the API, which are detected in Java, are thrown as exceptions.
The default implementation of the error handler throws exceptions on errors and prints to console on warnings.
The output of every user interaction with the underlying translator is handled implementing the interface
OutputHandler
. The (only) method is called at each block of output from the translator. The current output handler can be accessed and set viaAMPL.getOutputHandler
andAMPL.setOutputHandler
.
Constructors#
AMPL#
- public AMPL()#
Default constructor: creates a new AMPL instance with the default environment.
- Throws:
LicenseException – If no valid AMPL license has been found
RuntimeException – if the translator cannot be started for any other reason.
AMPL#
- public AMPL(Environment env)#
Constructor: creates a new AMPL instance with an ad-hoc environment. The environment can specify the location of the AMPL translator, the location of the licence file and any system environment variable.
- Parameters:
env – The environment in which the AMPL instance has to be created (can specify position of the license or other environment variables)
- Throws:
LicenseException – If no valid AMPL license has been found
RuntimeException – If the translator cannot be started for any other reason.
Methods#
addLibraryPath#
attachShutDownHook#
- public void attachShutDownHook()#
cd#
- public String cd(String path)#
Change or display the current working directory (see https://en.wikipedia.org/wiki/Working_directory ).
- Parameters:
path – New working directory or null (to display the working directory)
- Returns:
Current working directory
cd#
- public String cd()#
Get the current working directory from the underlying interpreter (see https://en.wikipedia.org/wiki/Working_directory ).
- Returns:
Current working directory
close#
- public void close()#
Stops the underlying engine, and release all any further attempt to execute optimisation commands without restarting it will throw an exception. It does not invalidate the currently generated entities, so that their values can be read and used.
delete#
- public void delete()#
display#
- public void display(Object... objects)#
Writes on the current
OutputHandler
the outcome of the AMPL statementdisplay o1, o2, .., on;
where
o1...on
are the objects passed to the procedure.- Parameters:
objects – Objects to write
- Throws:
IllegalArgumentException
– if an empty array of objects is passed
display#
- public void display(Writer out, Object... objects)#
Writes in the writer
out
the outcome of the AMPL statementdisplay o1, o2, .., on;
where
o1...on
are the objects passed to the procedure.- Parameters:
out – Writer to output the display command to
objects – Objects to write
- Throws:
IllegalArgumentException
– if an empty array of objects is passedjava.io.IOException
– from the writer
enableErrorRedirection#
- public void enableErrorRedirection()#
eval#
- public void eval(String s)#
Parses AMPL code and evaluates it as a possibly empty sequence of AMPL declarations and statements.
As a side effect, it invalidates all entities (as the passed statements can contain any arbitrary command); the lists of entities will be re-populated lazily (at first access)
The output of interpreting the statements is passed to the current
OutputHandler
(seeAMPL.getOutputHandler
andAMPL.setOutputHandler
).By default, errors are reported as exceptions and warnings are printed on stdout. This behaviour can be changed reassigning a
ErrorHandler
usingAMPL.setErrorHandler
.- Parameters:
s – A collection of AMPL statements to be passed to the interpreter
- Throws:
IllegalArgumentException
– if the input is not a complete AMPL statement
evalAsync#
- public void evalAsync(String s, java.lang.Runnable callback)#
Interprets the input statements asynchronously passing them to the underlying interpreter. As a side effect, it invalidates all entities (as the passed statements can contain any arbitrary command); the lists of entities will be re-populated lazily (at first access)
The output of interpreting the statements is passed to the current
OutputHandler
(seeAMPL.getOutputHandler
andAMPL.setOutputHandler
).By default, errors are reported as exceptions and warnings are printed on stdout. This behaviour can be changed reassigning a
ErrorHandler
usingAMPL.setErrorHandler
.- Parameters:
s – A collection of AMPL statements to be passed to the interpreter
callback – Callback to be called when AMPL has finished interpreting (or it is interrupted)
- Throws:
IllegalArgumentException
– if the input is not a complete AMPL statement
expand#
- public void expand(Entity... entities)#
Writes on the current
OutputHandler
the outcome of the AMPL statementexpand e1, e2, .., en;
where
e1...en
are the entites passed to the procedure.- Parameters:
entities – Entities to expand.
- Throws:
IllegalArgumentException
– if an empty array of objects is passed
expand#
- public void expand(Writer out, Entity... entities)#
Writes in the writer
out
the output of the AMPL statementexpand e1, e2, .., en;
where
e1...en
are the entites passed to the procedure.- Parameters:
out – Writer to output the
expand
command toentities – Entities to expand.
- Throws:
IllegalArgumentException
– If an empty array of objects is passedIOException
– From the writer
exportData#
exportData#
exportModel#
exportModel#
finalize#
- protected void finalize()#
getBoolOption#
- public boolean getBoolOption(String name)#
Get the current value of the specified boolean option. In AMPL, boolean options are represented as integer: 0 for false, 1 for true
- Parameters:
name – Option name
- Throws:
IllegalArgumentException
– if the option name is not valid or not existentNumberFormatException
– If the option did not have a value which could be casted to boolean
- Returns:
Value of the option (boolean)
getConstraint#
- public Constraint getConstraint(String name)#
Get constraint with the corresponding name
- Parameters:
name – Constraint name
- Returns:
Constraint, null if specified constraint does not exist
getConstraints#
- public EntityMap<Constraint> getConstraints()#
Get all the currently defined constraints
- Returns:
An
EntityMap
with all the constraints
getCurrentObjectiveName#
getData#
- public DataFrame getData(String... displayStatements)#
Get the data corresponding to the display statements. The statements can be AMPL expressions, or entities. It captures the equivalent of the command:
display ds1, ..., dsn;
where ds1, …, dsn are the
displayStatements
with which the function is called.As only one DataFrame is returned, the operation will fail if the results of the display statements cannot be indexed over the same set. As a result, any attempt to get data from more than one set, or to get data for multiple parameters with a different number of indexing sets will fail.
getDblOption#
- public double getDblOption(String name)#
Get the current value of the specified double option
- Parameters:
name – Option name
- Throws:
IllegalArgumentException
– if the option name is not valid or not existentNumberFormatException
– If the option did not have a value which could be casted to double
- Returns:
Value of the option (double)
getEntity#
- public Entity getEntity(String name)#
Get entity corresponding to the specified name (looks for it in all types of entities)
- Parameters:
name – Name of the entity
- Throws:
IllegalArgumentException
– if the specified entity does not exist
- Returns:
The AMPL entity with the specified name
getErrorHandler#
- public ErrorHandler getErrorHandler()#
Get the current error handler
- Returns:
The currently used
ErrorHandler
.
getIntOption#
- public int getIntOption(String name)#
Get the current value of the specified integer option
- Parameters:
name – Option name (alphanumeric)
- Throws:
IllegalArgumentException
– if the option name is not valid or not existentNumberFormatException
– If the option did not have a value which could be casted to integer
- Returns:
Value of the option (integer)
getObjective#
getObjectives#
getOption#
- public String getOption(String name)#
Get the current value of the specified option
- Parameters:
name – Option name (alphanumeric)
- Throws:
IllegalArgumentException
– if the option name is not valid
- Returns:
Value of the option, as a string. Returns
null
if an option with that name is not defined.
getOutput#
- public String getOutput(String s)#
Equivalent to
AMPL.eval
but returns the output as a string.- Parameters:
s – A collection of AMPL statements to be passed to the interpreter
- Throws:
IllegalArgumentException
– if the input is not a complete AMPL statement
getOutputHandler#
- public OutputHandler getOutputHandler()#
Get the current output handler. See
setOutputHandler
.- Returns:
The current outputHandler
getParameter#
getParameters#
getSet#
getSets#
getValue#
- public Object getValue(String scalarValueExpression)#
Get a scalar value from the underlying AMPL interpreter, as a double or a string.
- Parameters:
scalarValueExpression – An AMPL expression which evaluates to a scalar value
- Returns:
A string or a double number which represent the value of the expression
getVariable#
getVariables#
interrupt#
- public void interrupt()#
Interrupt an underlying asynchronous operation (execution of AMPL code by the AMPL interpreter). An asynchronous operation can be started via evalAsync(), solveAsync(), readAsync() and readDataAsync(). Does nothing if the engine or the solver are not busy. Note that on Windows interrupting is only possible when AMPLSig.dll is loaded in the underlying AMPL interpreter. It is started automatically when the AMPL API is instantiated if present in the AMPL executable directory
isBusy#
- public boolean isBusy()#
Check if the engine is busy doing an async operation
- Returns:
True if busy
isRunning#
- public boolean isRunning()#
Check if the underlying engine is running
- Returns:
True if it is running
loadLibrary#
- static void loadLibrary()#
read#
- public void read(String fileName)#
Interprets the specified file (script or model or mixed) As a side effect, it invalidates all entities (as the passed file can contain any arbitrary command); the lists of entities will be re-populated lazily (at first access)
- Parameters:
fileName – Full path to the file
- Throws:
IOException
– In case the file does not exist
readAsync#
- public void readAsync(String fileName, java.lang.Runnable callback)#
Interprets the specified file asynchronously, interpreting it as a model or a script file. As a side effect, it invalidates all entities (as the passed file can contain any arbitrary command); the lists of entities will be re-populated lazily (at first access)
- Parameters:
fileName – Full path to the file
callback – Callback to be executed when the file has been interpreted
- Throws:
IOException
– In case the file does not exist
readData#
- public void readData(String fileName)#
Interprets the specified file as data file The underlying AMPL instance will be set back to “model” mode after the execution. As a side effect, it invalidates all entities (as the passed file can contain any arbitrary command); the lists of entities will be re-populated lazily (at first access)
- Parameters:
fileName – Full path to the file
- Throws:
IOException
– In case the file does not exist
readDataAsync#
- public void readDataAsync(String fileName, java.lang.Runnable callback)#
Interprets the specified data file asynchronously. When interpreting is over, the specified callback is called. The file is interpreted as data. As a side effect, it invalidates all entities (as the passed file can contain any arbitrary command); the lists of entities will be re-populated lazily (at first access)
- Parameters:
fileName – Full path to the file
callback – Callback to be executed when the file has been interpreted
- Throws:
IOException
– In case the file does not exist
readTable#
reset#
- public void reset()#
Clears all entities in the underlying AMPL interpreter, clears all maps and invalidates all entities
setBoolOption#
- public void setBoolOption(String name, boolean value)#
Set an AMPL option to a specified boolean value. Note that in AMPL, boolean options are represented as integer: 0 for false, 1 for true
- Parameters:
name – Name of the option to be set
value – The boolean value the option must be set to
- Throws:
IllegalArgumentException
– if the option name is not valid
setData#
- public void setData(DataFrame df)#
Assign the data in the dataframe to the AMPL entities with the corresponding names. The indices values are not assigned; equivalent to:
setData(df, null);
- Parameters:
df – The dataframe containing the data to be assigned
- Throws:
Exception
– If the data assignment procedure was not successful.
setData#
- public void setData(DataFrame df, String setName)#
Assign the data in the dataframe to the AMPL entities with the names corresponding to the column names. If setName is null, only the parameters value will be assigned. If the dataframe has only index columns, it can be used to assign values to an AMPL set, which name must be specified in setName.
- Parameters:
df – The dataframe containing the data to be assigned
setName – The name of the set to which the indices values of the DataFrame are to be assigned
- Throws:
Exception
– If the data assignment procedure was not successful.
setDblOption#
- public void setDblOption(String name, double value)#
Set an AMPL option to a specified double value.
- Parameters:
name – Name of the option to be set
value – The double value the option must be set to
- Throws:
IllegalArgumentException
– if the option name is not valid
setErrorHandler#
- public void setErrorHandler(ErrorHandler errorHandler)#
Set error handler. An error handler could for example redirect all error messages to stdout, or throw exception at all errors and print to console in case of warnings (see
ErrorHandler
).- Parameters:
errorHandler –
ErrorHandler
to be used
setIntOption#
- public void setIntOption(String name, int value)#
Set an AMPL option to a specified integer value.
- Parameters:
name – Name of the option to be set
value – The integer value the option must be set to
- Throws:
IllegalArgumentException
– if the option name is not valid
setOption#
- public void setOption(String name, String value)#
Set an AMPL option to a specified value.
- Parameters:
name – Name of the option to be set (alphanumeric without spaces)
value – String representing the value the option must be set to
- Throws:
IllegalArgumentException
– if the option name is not valid
setOutputHandler#
- public void setOutputHandler(OutputHandler outputHandler)#
Set the AMPL output handler. Every time AMPL executes a statement, the output is passed to this handler for processing (see
OutputHandler
). The default handler prints to stdout.- Parameters:
outputHandler – The outputHandler to set
- Throws:
ConcurrentModificationException
– If called while the engine is busy doing an async operation
show#
- public void show(Entity... entities)#
Writes on the current
OutputHandler
the outcome of the AMPL statementshow e1, e2, .., en;
where
e1...en
are the objects passed to the procedure.- Parameters:
entities – Entities to show.
- Throws:
IllegalArgumentException
– if an empty array of objects is passed
show#
- public void show(Writer out, Entity... entities)#
Writes in the writer
out
the output of the AMPL statementshow e1, e2, .., en;
where
e1...en
are the entites passed to the procedure.- Parameters:
out – Writer to output the
show
command toentities – Entities to write
- Throws:
IllegalArgumentException
– if an empty array of objects is passedIOException
– from the writer
snapshot#
snapshot#
snapshot#
snapshot#
snapshot#
solve#
- public void solve()#
Solve the current model
solve#
solve#
solveAsync#
toString#
- public String toString()#
Get a string describing the object. Returns the version of the interpreter or the message “AMPL is not running” if the interpreter is not running (e.g. due to unexpected internal error or to a call to
AMPL.close
)