AMPL

class amplpy.AMPL(environment=None, langext=None)

An AMPL translator.

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

Error handling is two-faced:

  • Errors coming from the underlying AMPL translator (e.g. syntax errors and warnings obtained calling the eval method) are handled by the ErrorHandler which can be set and get via getErrorHandler() and setErrorHandler().
  • Generic errors coming from misusing the API, which are detected in Python, 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 abstract class OutputHandler. The (only) method is called at each block of output from the translator. The current output handler can be accessed and set via getOutputHandler() and setOutputHandler().

__init__(environment=None, langext=None)

Constructor: creates a new AMPL instance with the specified environment if provided.

Args:
environment (Environment): This allows the user to specify the location of the AMPL binaries to be used and to modify the environment variables in which the AMPL interpreter will run.
Raises:
RuntimeError: If no valid AMPL license has been found or if the translator cannot be started for any other reason.
__del__()

Default destructor: releases all the resources related to the AMPL instance (most notably kills the underlying interpreter).

getData(*statements)

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.

Args:
statements: The display statements to be fetched.
Raises:
RuntimeError: if the AMPL visualization command does not succeed for one of the reasons listed above.
Returns:
DataFrame capturing the output of the display command in tabular form.
getEntity(name)

Get entity corresponding to the specified name (looks for it in all types of entities).

Args:
name: Name of the entity.
Raises:
TypeError: if the specified entity does not exist.
Returns:
The AMPL entity with the specified name.
getVariable(name)

Get the variable with the corresponding name.

Args:
name: Name of the variable to be found.
Raises:
TypeError: if the specified variable does not exist.
getConstraint(name)

Get the constraint with the corresponding name.

Args:
name: Name of the constraint to be found.
Raises:
TypeError: if the specified constraint does not exist.
getObjective(name)

Get the objective with the corresponding name.

Args:
name: Name of the objective to be found.
Raises:
TypeError: if the specified objective does not exist.
getSet(name)

Get the set with the corresponding name.

Args:
name: Name of the set to be found.
Raises:
TypeError: if the specified set does not exist.
getParameter(name)

Get the parameter with the corresponding name.

Args:
name: Name of the parameter to be found.
Raises:
TypeError: if the specified parameter does not exist.
eval(amplstatements, **kwargs)

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 getOutputHandler and setOutputHandler).

By default, errors and warnings are printed on stdout. This behavior can be changed reassigning an ErrorHandler using setErrorHandler.

Args:
amplstatements: A collection of AMPL statements and declarations to be passed to the interpreter.
Raises:
RuntimeError: if the input is not a complete AMPL statement (e.g. if it does not end with semicolon) or if the underlying interpreter is not running.
getOutput(amplstatements)

Equivalent to eval() but returns the output as a string.

Args:
amplstatements: A collection of AMPL statements and declarations to be passed to the interpreter.
Returns:
A string with the output.
reset()

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

close()

Stops the underlying engine, and release all any further attempt to execute optimization commands without restarting it will throw an exception.

isRunning()

Returns true if the underlying engine is running.

isBusy()

Returns true if the underlying engine is doing an async operation.

solve()

Solve the current model.

Raises:
RuntimeError: if the underlying interpreter is not running.
readAsync(fileName, callback, **kwargs)

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

Args:

fileName: Path to the file (Relative to the current working directory or absolute).

callback: Callback to be executed when the file has been interpreted.

readDataAsync(fileName, 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)

Args:

fileName: Full path to the file.

callback: Callback to be executed when the file has been interpreted.

evalAsync(amplstatements, callback, **kwargs)

Interpret the given AMPL statement asynchronously.

Args:

amplstatements: A collection of AMPL statements and declarations to be passed to the interpreter.

callback: Callback to be executed when the statement has been interpreted.

Raises:
RuntimeError: if the input is not a complete AMPL statement (e.g. if it does not end with semicolon) or if the underlying interpreter is not running.
solveAsync(callback)

Solve the current model asynchronously.

Args:
callback: Callback to be executed when the solver is done.
wait()

Wait for the current async operation to finish.

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 and the solver are idle.

cd(path=None)

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

Args:
path: New working directory or None (to display the working directory).
Returns:
Current working directory.
setOption(name, value)

Set an AMPL option to a specified value.

Args:

name: Name of the option to be set (alphanumeric without spaces).

value: The value the option must be set to.

Raises:

InvalidArgumet: if the option name is not valid.

TypeError: if the value has an invalid type.

getOption(name)

Get the current value of the specified option. If the option does not exist, returns None.

Args:
name: Option name.
Returns:
Value of the option.
Raises:
InvalidArgumet: if the option name is not valid.
read(fileName, **kwargs)

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

Args:
fileName: Full path to the file.
Raises:
RuntimeError: in case the file does not exist.
readData(fileName)

Interprets the specified file as an AMPL data 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). After reading the file, the interpreter is put back to “model” mode.

Args:
fileName: Full path to the file.
Raises:
RuntimeError: in case the file does not exist.
getValue(scalarExpression)

Get a scalar value from the underlying AMPL interpreter, as a double or a string.

Args:
scalarExpression: An AMPL expression which evaluates to a scalar value.
Returns:
The value of the expression.
setData(data, setName=None)

Assign the data in the dataframe to the AMPL entities with the names corresponding to the column names.

Args:

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

Raises:
AMPLException: if the data assignment procedure was not successful.
readTable(tableName)

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

read table tableName;
Args:
tableName: Name of the table to be read.
writeTable(tableName)

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

write table tableName;
Args:
tableName: Name of the table to be written.
display(*amplExpressions)

Writes on the current OutputHandler the outcome of the AMPL statement.

display e1, e2, .., en;

where e1, …, en are the strings passed to the procedure.

Args:
amplExpressions: Expressions to be evaluated.
setOutputHandler(outputhandler)

Sets a new output handler.

Args:
outputhandler: The function handling the AMPL output derived from interpreting user commands.
setErrorHandler(errorhandler)

Sets a new error handler.

Args:
errorhandler: The object handling AMPL errors and warnings.
getOutputHandler()

Get the current output handler.

Returns:
The current output handler.
getErrorHandler()

Get the current error handler.

Returns:
The current error handler.
getVariables()

Get all the variables declared.

getConstraints()

Get all the constraints declared.

getObjectives()

Get all the objectives declared.

getSets()

Get all the sets declared.

getParameters()

Get all the parameters declared.

getCurrentObjective()

Get the the current objective. Returns None if no objective is set.

var

Get/Set a variable.

con

Get/Set a constraint.

obj

Get an objective.

set

Get/Set a set.

param

Get/Set a parameter.

option

Get/Set an option.

exportData(datfile)

Create a .dat file with the data that has been loaded.

Args:
datfile: Path to the file (Relative to the current working directory or absolute).
exportGurobiModel()

Export the model to Gurobi as a gurobipy.Model object.

importGurobiSolution(grbmodel)

Import the solution from a gurobipy.Model object.

__module__ = 'amplpy.ampl'
class amplpy.EntityMap(obj, entityClass)
__init__(obj, entityClass)

x.__init__(…) initializes x; see help(type(x)) for signature

__getitem__(key)
size()
__len__()
__module__ = 'amplpy.iterators'