AMPL

public class AMPL implements Closeable

An AMPL translator. An object of this class can be used to do the following tasks:

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 initialisation 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 to AMPL.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 the ErrorHandler which can be set and get via AMPL.getErrorHandler() and AMPL.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 via AMPL.getOutputHandler and AMPL.setOutputHandler.

Constructors

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.
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

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

public String cd()

Get the current working directory from the underlying interpreter (see https://en.wikipedia.org/wiki/Working_directory ).

Returns:Current working directory
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.

public void display(Object... objects)

Writes on the current OutputHandler the outcome of the AMPL statement

display o1, o2, .., on;

where o1...on are the objects passed to the procedure.

Parameters:
  • objects – Objects to write
Throws:
public void display(Writer out, Object... objects)

Writes in the writer out the outcome of the AMPL statement

display 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:
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 (see AMPL.getOutputHandler and AMPL.setOutputHandler).

By default, errors are reported as exceptions and warnings are printed on stdout. This behaviour can be changed reassigning a ErrorHandler using AMPL.setErrorHandler.

Parameters:
  • s – A collection of AMPL statements to be passed to the interpreter
Throws:
public void evalAsync(String s, 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 (see AMPL.getOutputHandler and AMPL.setOutputHandler).

By default, errors are reported as exceptions and warnings are printed on stdout. This behaviour can be changed reassigning a ErrorHandler using AMPL.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:
public void expand(Entity<?>... entities)

Writes on the current OutputHandler the outcome of the AMPL statement

expand e1, e2, .., en;

where e1...en are the entites passed to the procedure.

Parameters:
  • entities – Entities to expand.
Throws:
public void expand(Writer out, Entity<?>... entities)

Writes in the writer out the output of the AMPL statement

expand e1, e2, .., en;

where e1...en are the entites passed to the procedure.

Parameters:
  • out – Writer to output the expand command to
  • entities – Entities to expand.
Throws:
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:
Returns:

Value of the option (boolean)

public Constraint getConstraint(String name)

Get constraint with the corresponding name

Parameters:
  • name – Constraint name
Returns:

Constraint, null if specified constraint does not exist

public EntityList<Constraint> getConstraints()

Get all the currently defined constraints

Returns:Immutable and self updating EntityList of all the constraints
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.

Parameters:
  • displayStatements – The display statements to be fetched.
Throws:
  • AMPLException – if the AMPL visualisation command does not succeed for one of the reasons listed above.
Returns:

A DataFrame capturing the output of the display command in tabular form.

public double getDblOption(String name)

Get the current value of the specified double option

Parameters:
  • name – Option name
Throws:
Returns:

Value of the option (double)

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
Returns:

Entity, if found. Null otherwise

public ErrorHandler getErrorHandler()

Get the current error handler

Returns:The currently used ErrorHandler.
public int getIntOption(String name)

Get the current value of the specified integer option

Parameters:
  • name – Option name (alphanumeric)
Throws:
Returns:

Value of the option (integer)

public Objective getObjective(String name)

Get objective with the corresponding name

Parameters:
  • name – Objective name
Returns:

Objective, null if specified objective does not exist

public EntityList<Objective> getObjectives()

Get all the currently defined objectives

Returns:Immutable and self updating EntityList of all the objectives
public String getOption(String name)

Get the current value of the specified option

Parameters:
  • name – Option name (alphanumeric)
Throws:
Returns:

Value of the option, as a string. Returns null if an option with that name is not defined.

public OutputHandler getOutputHandler()

Get the current output handler. See setOutputHandler.

Returns:The current outputHandler
public Parameter getParameter(String name)

Get parameter with the corresponding name

Parameters:
  • name – Parameter name
Returns:

Parameter, null if specified parameter does not exist

public EntityList<Parameter> getParameters()

Get all the currently defined parameters

Returns:Immutable and self updating EntityList of all the parameters
public Set getSet(String name)

Get set with the corresponding name

Parameters:
  • name – Set name
Returns:

Set, null if specified set does not exist

public EntityList<Set> getSets()

Get all the currently defined sets

Returns:Immutable and self updating EntityList of all the sets
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

public Variable getVariable(String name)

Get variable with the corresponding name

Parameters:
  • name – Variable name
Returns:

Variable, null if specified variable does not exist

public EntityList<Variable> getVariables()

Get all the currently defined variables

Returns:Immutable and self updating EntityList of all the variables
public void interrupt()

Interrupt an underlying async operation. Does nothing if the engine is not busy or if the engine (AMPL executable version) does not allow interrupting.

public boolean isBusy()

Check if the engine is busy doing an async operation

Returns:True if busy
public boolean isRunning()

Check if the underlying engine is running

Returns:True if it is running
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
public void readAsync(String fileName, 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
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
public void readDataAsync(String fileName, 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
public void readTable(String tableName)

Read the table corresponding to the specified name, equivalent to the AMPL statement:

read table tableName;
Parameters:
  • tableName – Name of the table to be read
public void reset()

Clears all entities in the underlying AMPL interpreter, clears all maps and invalidates all entities

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:
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:
  • AMPLException – If the data assignment procedure was not successful.
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.

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:
  • AMPLException – If the data assignment procedure was not successful.
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:
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:
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:
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:
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
public void show(Entity<?>... entities)

Writes on the current OutputHandler the outcome of the AMPL statement

show e1, e2, .., en;

where e1...en are the objects passed to the procedure.

Parameters:
  • entities – Entities to show.
Throws:
public void show(Writer out, Entity<?>... entities)

Writes in the writer out the output of the AMPL statement

show e1, e2, .., en;

where e1...en are the entites passed to the procedure.

Parameters:
  • out – Writer to output the show command to
  • entities – Entities to write
Throws:
public void solve()

Solve the current model

Returns:Output derived from the solution of the current model
public void solveAsync(Runnable callback)

Solve the current model asynchronously

Parameters:
  • callback – Function to be called when solver is done
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)

public void writeTable(String tableName)

Write the table corresponding to the specified name, equivalent to the AMPL statement

write table tableName;
Parameters:
  • tableName – Name of the table to be written