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.

exportModel(modfile)

Create a .mod file with the model that has been loaded.

Args:
modfile: Path to the file (Relative to the current working directory or absolute).
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(gurobiDriver='gurobi', verbose=False)

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

Args:
gurobiDriver: The name or the path of the Gurobi solver driver. verbose: Whether should generate verbose output.
Returns:
A gurobipy.Model object with the model loaded.
importGurobiSolution(grbmodel)

Import the solution from a gurobipy.Model object.

Args:
grbmodel: A gurobipy.Model object with the model solved.
__dict__ = dict_proxy({'getObjectives': <function getObjectives>, '__module__': 'amplpy.ampl', 'set': <property object>, 'getConstraints': <function getConstraints>, '_param': <function _param>, 'readData': <function readData>, 'solveAsync': <function solveAsync>, 'cd': <function cd>, 'readAsync': <function readAsync>, 'getOutput': <function getOutput>, '_var': <function _var>, 'getCurrentObjective': <function getCurrentObjective>, 'exportData': <function exportData>, 'getObjective': <function getObjective>, 'getSet': <function getSet>, 'getValue': <function getValue>, '__weakref__': <attribute '__weakref__' of 'AMPL' objects>, '__init__': <function __init__>, 'getSets': <function getSets>, 'display': <function display>, '_startRecording': <function _startRecording>, 'setOption': <function setOption>, 'getParameter': <function getParameter>, 'param': <property object>, 'getOutputHandler': <function getOutputHandler>, '__dict__': <attribute '__dict__' of 'AMPL' objects>, 'writeTable': <function writeTable>, '_obj': <function _obj>, '_option': <function _option>, 'setOutputHandler': <function setOutputHandler>, 'getVariable': <function getVariable>, 'var': <property object>, 'isBusy': <function isBusy>, 'getData': <function getData>, '__doc__': 'An AMPL translator.\n\n An object of this class can be used to do the following tasks:\n\n - Run AMPL code. See :func:`~amplpy.AMPL.eval` and\n :func:`~amplpy.AMPL.evalAsync`.\n - Read models and data from files. See :func:`~amplpy.AMPL.read`,\n :func:`~amplpy.AMPL.readData`, :func:`~amplpy.AMPL.readAsync`, and\n :func:`~amplpy.AMPL.readDataAsync`.\n - Solve optimization problems constructed from model and data (see\n :func:`~amplpy.AMPL.solve` and :func:`~amplpy.AMPL.solveAsync`).\n - Access single Elements of an optimization problem. See\n :func:`~amplpy.AMPL.getVariable`, :func:`~amplpy.AMPL.getConstraint`,\n :func:`~amplpy.AMPL.getObjective`, :func:`~amplpy.AMPL.getSet`,\n and :func:`~amplpy.AMPL.getParameter`.\n - Access lists of available entities of an optimization problem. See\n :func:`~amplpy.AMPL.getVariables`, :func:`~amplpy.AMPL.getConstraints`,\n :func:`~amplpy.AMPL.getObjectives`, :func:`~amplpy.AMPL.getSets`,\n and :func:`~amplpy.AMPL.getParameters`.\n\n Error handling is two-faced:\n\n - Errors coming from the underlying AMPL translator (e.g. syntax errors and\n warnings obtained calling the eval method) are handled by\n the :class:`~amplpy.ErrorHandler` which can be set and get via\n :func:`~amplpy.AMPL.getErrorHandler` and\n :func:`~amplpy.AMPL.setErrorHandler`.\n - Generic errors coming from misusing the API, which are detected in\n Python, are thrown as exceptions.\n\n The default implementation of the error handler throws exceptions on errors\n and prints to console on warnings.\n\n The output of every user interaction with the underlying translator is\n handled implementing the abstract class :class:`~amplpy.OutputHandler`.\n The (only) method is called at each block of output from the translator.\n The current output handler can be accessed and set via\n :func:`~amplpy.AMPL.getOutputHandler` and\n :func:`~amplpy.AMPL.setOutputHandler`.\n ', 'getOption': <function getOption>, 'setData': <function setData>, 'option': <property object>, 'read': <function read>, 'getErrorHandler': <function getErrorHandler>, 'getVariables': <function getVariables>, 'readDataAsync': <function readDataAsync>, 'setErrorHandler': <function setErrorHandler>, '__del__': <function __del__>, 'readTable': <function readTable>, 'getEntity': <function getEntity>, '_con': <function _con>, 'eval': <function eval>, 'interrupt': <function interrupt>, 'getConstraint': <function getConstraint>, 'getParameters': <function getParameters>, 'wait': <function wait>, 'reset': <function reset>, 'isRunning': <function isRunning>, 'importGurobiSolution': <function importGurobiSolution>, 'close': <function close>, 'exportGurobiModel': <function exportGurobiModel>, '_loadSession': <function _loadSession>, '_stopRecording': <function _stopRecording>, 'solve': <function solve>, 'obj': <property object>, 'evalAsync': <function evalAsync>, 'exportModel': <function exportModel>, '_set': <function _set>, 'con': <property object>})
__module__ = 'amplpy.ampl'
__weakref__

list of weak references to the object (if defined)

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'