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 get_error_handler() and set_error_handler().

  • 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 get_output_handler() and set_output_handler().

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

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

TypeError: if the AMPL visualization command does not succeed for one of the reasons listed above.

RuntimeError: if there are issues with the data.

Returns:

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

get_entity(name)

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

Args:

name: Name of the entity.

Raises:

KeyError: if the specified entity does not exist.

Returns:

The AMPL entity with the specified name.

get_variable(name)

Get the variable with the corresponding name.

Args:

name: Name of the variable to be found.

Raises:

KeyError: if the specified variable does not exist.

get_constraint(name)

Get the constraint with the corresponding name.

Args:

name: Name of the constraint to be found.

Raises:

KeyError: if the specified constraint does not exist.

get_objective(name)

Get the objective with the corresponding name.

Args:

name: Name of the objective to be found.

Raises:

KeyError: if the specified objective does not exist.

get_set(name)

Get the set with the corresponding name.

Args:

name: Name of the set to be found.

Raises:

KeyError: if the specified set does not exist.

get_parameter(name)

Get the parameter with the corresponding name.

Args:

name: Name of the parameter to be found.

Raises:

KeyError: if the specified parameter does not exist.

eval(statements, **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:

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

get_output(statements)

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

Args:

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

is_running()

Returns true if the underlying engine is running.

is_busy()

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.

read_async(filename, callback=None, **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.

read_data_async(filename, callback=None)

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.

eval_async(statements, callback=None, **kwargs)

Interpret the given AMPL statement asynchronously.

Args:

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

solve_async(callback=None)

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.

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

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

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

get_value(scalar_expression)

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

Args:

scalar_expression: An AMPL expression which evaluates to a scalar value.

Returns:

The value of the expression.

set_data(data, set_name=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.

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

read_table(table_name)

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

read table table_name;
Args:

table_name: Name of the table to be read.

write_table(table_name)

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

write table table_name;
Args:

table_name: Name of the table to be written.

display(*ampl_expressions)

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:

ampl_expressions: Expressions to be evaluated.

set_output_handler(output_handler)

Sets a new output handler.

Args:

output_handler: The function handling the AMPL output derived from interpreting user commands.

set_error_handler(error_handler)

Sets a new error handler.

Args:

error_handler: The object handling AMPL errors and warnings.

get_output_handler()

Get the current output handler.

Returns:

The current output handler.

get_error_handler()

Get the current error handler.

Returns:

The current error handler.

get_variables()

Get all the variables declared.

get_constraints()

Get all the constraints declared.

get_objectives()

Get all the objectives declared.

get_sets()

Get all the sets declared.

get_parameters()

Get all the parameters declared.

get_current_objective()

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

property var

Get/Set a variable.

property con

Get/Set a constraint.

property obj

Get an objective.

property set

Get/Set a set.

property param

Get/Set a parameter.

property option

Get/Set an option.

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

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

evalAsync(statements, callback=None, **kwargs)

Interpret the given AMPL statement asynchronously.

Args:

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

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

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

getConstraint(name)

Get the constraint with the corresponding name.

Args:

name: Name of the constraint to be found.

Raises:

KeyError: if the specified constraint does not exist.

getConstraints()

Get all the constraints declared.

getCurrentObjective()

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

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:

TypeError: if the AMPL visualization command does not succeed for one of the reasons listed above.

RuntimeError: if there are issues with the data.

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:

KeyError: if the specified entity does not exist.

Returns:

The AMPL entity with the specified name.

getErrorHandler()

Get the current error handler.

Returns:

The current error handler.

getObjective(name)

Get the objective with the corresponding name.

Args:

name: Name of the objective to be found.

Raises:

KeyError: if the specified objective does not exist.

getObjectives()

Get all the objectives declared.

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.

getOutput(statements)

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

Args:

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

Returns:

A string with the output.

getOutputHandler()

Get the current output handler.

Returns:

The current output handler.

getParameter(name)

Get the parameter with the corresponding name.

Args:

name: Name of the parameter to be found.

Raises:

KeyError: if the specified parameter does not exist.

getParameters()

Get all the parameters declared.

getSet(name)

Get the set with the corresponding name.

Args:

name: Name of the set to be found.

Raises:

KeyError: if the specified set does not exist.

getSets()

Get all the sets declared.

getValue(scalar_expression)

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

Args:

scalar_expression: An AMPL expression which evaluates to a scalar value.

Returns:

The value of the expression.

getVariable(name)

Get the variable with the corresponding name.

Args:

name: Name of the variable to be found.

Raises:

KeyError: if the specified variable does not exist.

getVariables()

Get all the variables declared.

isBusy()

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

isRunning()

Returns true if the underlying engine is running.

readAsync(filename, callback=None, **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.

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.

readDataAsync(filename, callback=None)

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.

readTable(table_name)

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

read table table_name;
Args:

table_name: Name of the table to be read.

setData(data, set_name=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.

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

setErrorHandler(error_handler)

Sets a new error handler.

Args:

error_handler: The object handling AMPL errors and warnings.

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.

setOutputHandler(output_handler)

Sets a new output handler.

Args:

output_handler: The function handling the AMPL output derived from interpreting user commands.

solveAsync(callback=None)

Solve the current model asynchronously.

Args:

callback: Callback to be executed when the solver is done.

__module__ = 'amplpy.ampl'
writeTable(table_name)

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

write table table_name;
Args:

table_name: Name of the table to be written.

class amplpy.EntityMap(obj, entity_class)
__init__(obj, entity_class)
__getitem__(key)
size()
__len__()
__module__ = 'amplpy.iterators'