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

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.

## Fields¶

### AMPLParser¶

AMPLParser AMPLParser

### APIVERSIONBUILD¶

static int APIVERSIONBUILD

### APIVERSIONMAJOR¶

static int APIVERSIONMAJOR

### APIVERSIONMINOR¶

static int APIVERSIONMINOR

### ASYNCDEBUG¶

static boolean ASYNCDEBUG

### DEBUG¶

static boolean DEBUG

### ENABLETABLES¶

static boolean ENABLETABLES

### EnableTablesMinVersion¶

static int EnableTablesMinVersion

### RELEASE_DATE¶

static final int RELEASE_DATE

### engine¶

Engine engine

### hasBeenClosed¶

boolean hasBeenClosed

### util¶

public Util util

## 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) LicenseException – If no valid AMPL license has been found RuntimeException – If the translator cannot be started for any other reason.

## Methods¶

public synchronized void addOutputListener(OutputListener lis)

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

### checkFile¶

void checkFile(String fileName)

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

### diagnose¶

void diagnose(AMPLException ex)

### 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 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 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 java.io.IOException – from the writer IllegalArgumentException – if an empty array of objects is passed

### engine¶

Engine engine()

### 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 IllegalArgumentException – if the input is not a complete AMPL statement

### evalAsync¶

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) 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 statement

expand e1, e2, .., en;


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

Parameters: entities – Entities to expand. 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 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. IllegalArgumentException – If an empty array of objects is passed IOException – From the writer

### 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 NumberFormatException – If the option did not have a value which could be casted to boolean IllegalArgumentException – if the option name is not valid or not existent Value of the option (boolean)

### getConstraint¶

public Constraint getConstraint(String name)

Get constraint with the corresponding name

Parameters: name – Constraint name Constraint, null if specified constraint does not exist

### getConstraints¶

public EntityList<Constraint> getConstraints()

Get all the currently defined constraints

Returns: Immutable and self updating EntityList of all the constraints

### 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. AMPLException – if the AMPL visualisation command does not succeed for one of the reasons listed above. 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 NumberFormatException – If the option did not have a value which could be casted to double IllegalArgumentException – if the option name is not valid or not existent 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 Entity, if found. Null otherwise

### getErrorHandler¶

public ErrorHandler getErrorHandler()

Get the current error handler

Returns: The currently used ErrorHandler.

### getInnerDiagnosticHandler¶

InternalDiagnostic getInnerDiagnosticHandler()

### getIntOption¶

public int getIntOption(String name)

Get the current value of the specified integer option

Parameters: name – Option name (alphanumeric) NumberFormatException – If the option did not have a value which could be casted to integer IllegalArgumentException – if the option name is not valid or not existent Value of the option (integer)

### getObjective¶

public Objective getObjective(String name)

Get objective with the corresponding name

Parameters: name – Objective name Objective, null if specified objective does not exist

### getObjectives¶

public EntityList<Objective> getObjectives()

Get all the currently defined objectives

Returns: Immutable and self updating EntityList of all the objectives

### getOption¶

public String getOption(String name)

Get the current value of the specified option

Parameters: name – Option name (alphanumeric) IllegalArgumentException – if the option name is not valid Value of the option, as a string. Returns null if an option with that name is not defined.

### 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 Parameter, null if specified parameter does not exist

### getParameters¶

public EntityList<Parameter> getParameters()

Get all the currently defined parameters

Returns: Immutable and self updating EntityList of all the parameters

### getProblem¶

Problem getProblem(String name)

Get parameter with the corresponding name

Parameters: name – Parameter name Parameter, null if specified parameter does not exist

### getSet¶

public Set getSet(String name)

Get set with the corresponding name

Parameters: name – Set name Set, null if specified set does not exist

### getSets¶

public EntityList<Set> getSets()

Get all the currently defined sets

Returns: Immutable and self updating EntityList of all the sets

### getTable¶

Table getTable(String name)

Get parameter with the corresponding name

Parameters: name – Parameter name Parameter, null if specified parameter does not exist

### 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 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 Variable, null if specified variable does not exist

### getVariables¶

public EntityList<Variable> getVariables()

Get all the currently defined variables

Returns: Immutable and self updating EntityList of all the variables

### innerDiagnose¶

void innerDiagnose(RuntimeException ex)

### innerGetConstraints¶

Map<String, Constraint> innerGetConstraints()

Get constraints

Returns: Map of all constraints

### innerGetObjectives¶

Map<String, Objective> innerGetObjectives()

Get objectives

Returns: Map of all objectives

### innerGetParameters¶

Map<String, Parameter> innerGetParameters()

Get all parameters

Returns: Map of all parameters

### innerGetProblems¶

Map<String, Problem> innerGetProblems()

Get all parameters

Returns: Map of all parameters

### innerGetSets¶

Map<String, Set> innerGetSets()

Get all sets

Returns: Map of all sets

### innerGetTables¶

Map<String, Table> innerGetTables()

Get all parameters

Returns: Map of all parameters

### innerGetVariables¶

Map<String, Variable> innerGetVariables()

Get variables

Returns: Map of all 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

### notifyOutput¶

public void notifyOutput(AMPLOutput out)

### preCheckName¶

boolean preCheckName(String name)

### printAsyncDebug¶

static void printAsyncDebug(String msg, Object... objects)

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 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 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 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 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 registerMatlabOutputHandler()

### removeOutputListener¶

public synchronized void removeOutputListener(OutputListener lis)

### 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 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 AMPLException – 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 AMPLException – 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 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 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 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 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. 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 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 IllegalArgumentException – if an empty array of objects is passed IOException – from the writer

### solve¶

public void solve()

Solve the current model

Returns: Output derived from the solution of the current model

### solveAsync¶

public void solveAsync(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)

### updateAllEntities¶

void updateAllEntities()

Force update of all runtime entities to reflect changes in the engine. Provided for compatibility, the current version is automatically consistent. Updates just declarations and indexing sets, the actual instances are initialised lazily.

### updateEntitiesList¶

void updateEntitiesList(EntityType type)

### updateEntitiesList¶

<T extends Entity<K>, K> boolean updateEntitiesList(EntityType t, Map<String, T> map)

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