AMPL#

public class AMPL extends AMPLBase 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 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 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#

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#

static void addLibraryPath(String pathToAdd)#

Adds the specified path to the java library path

Parameters:
  • pathToAdd – the path to add

Throws:

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 statement

display o1, o2, .., on;

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

Parameters:
  • objects – Objects to write

Throws:

display#

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:

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

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

expand#

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:

expand#

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:

exportData#

public String exportData()#

Get all the data currently loaded in dat format

exportData#

public void exportData(String fileName)#

Writes all the data currently loaded to file in dat format

Parameters:
  • fileName – The file to write

exportModel#

public String exportModel()#

Returns all the declarations in the current AMPL instance

exportModel#

public void exportModel(String fileName)#

Writes the declarations in the current AMPL instance to file

Parameters:
  • fileName – The file to write

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

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

Parameters:
  • displayStatements – The display statements to be fetched.

Throws:
  • Exception – 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.

getDblOption#

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)

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

Value of the option (integer)

getObjective#

public Objective getObjective(String name)#

Get objective with the corresponding name

Parameters:
  • name – Objective name

Returns:

Objective, null if specified objective does not exist

getObjectives#

public EntityMap<Objective> getObjectives()#

Get all the currently defined objectives

Returns:

An EntityMap with all the objectives

getOption#

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.

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:

getOutputHandler#

public OutputHandler getOutputHandler()#

Get the current output handler. See setOutputHandler.

Returns:

The current outputHandler

getParameter#

public Parameter getParameter(String name)#

Get parameter with the corresponding name

Parameters:
  • name – Parameter name

Returns:

Parameter, null if specified parameter does not exist

getParameters#

public EntityMap<Parameter> getParameters()#

Get all the currently defined parameters

Returns:

An EntityMap with all the parameters

getSet#

public Set getSet(String name)#

Get set with the corresponding name

Parameters:
  • name – Set name

Returns:

Set, null if specified set does not exist

getSets#

public EntityMap<Set> getSets()#

Get all the currently defined sets

Returns:

An EntityMap with all the sets

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#

public Variable getVariable(String name)#

Get variable with the corresponding name

Parameters:
  • name – Variable name

Returns:

Variable, null if specified variable does not exist

getVariables#

public EntityMap<Variable> getVariables()#

Get all the currently defined variables

Returns:

An EntityMap with all the variables

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:

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:

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:

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:

readTable#

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

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:

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:

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:

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:

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:

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 statement

show e1, e2, .., en;

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

Parameters:
  • entities – Entities to show.

Throws:

show#

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:

snapshot#

public String snapshot()#

Take a snapshot of the AMPL session.

snapshot#

public void snapshot(String fileName)#

Writes a snapshot of the AMPL session to file

Parameters:
  • fileName – The file to write

snapshot#

public String snapshot(String fileName, boolean model)#

Writes or returns a snapshot of the AMPL session

Parameters:
  • fileName – Name of the option to be set

  • model – Include the model or not

snapshot#

public String snapshot(String fileName, boolean model, boolean data)#

Writes or returns a snapshot of the AMPL session

Parameters:
  • fileName – Name of the option to be set

  • model – Include the model or not

  • data – Include the data or not

snapshot#

public String snapshot(String fileName, boolean model, boolean data, boolean options)#

Writes or returns a snapshot of the AMPL session

Parameters:
  • fileName – Name of the option to be set

  • model – Include the model or not

  • data – Include the data or not

  • options – Include the options or not

solve#

public void solve()#

Solve the current model

solve#

public void solve(String problem)#

Solve the problem specified

Parameters:
  • problem – Problem to solve

solve#

public void solve(String problem, String solver)#

Solve a problem with the solver specified

Parameters:
  • problem – Problem to solve

  • solver – Solver to use

solveAsync#

public void solveAsync(java.lang.Runnable callback)#

Solve the current model asynchronously

Parameters:
  • callback – Function to be called when solver is done

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)

writeTable#

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