AMPL

class amplpy.AMPL(environment=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)

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)

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.

solve(problem='', solver='', verbose=True, return_output=False, **kwargs)

Solve the current model or the problem specified by problem.

Args:

problem: Name of the problem to solve.

solver: Name of the solver to use.

verbose: Display verbose output if set to True.

return_output: Return output as a string if set to True.

kwargs: Pass solvername_options as additional arguments.

Raises:

RuntimeError: if the underlying interpreter is not running.

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)

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(filename='')

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

Args:

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

export_data(filename='')

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

Args:

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

snapshot(filename='', model=True, data=True, options=True)

Create a snapshot file that replicates the current session.

Args:

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

model: include model declaration if set to True.

data: include data declaration if set to True.

options: include options if set to True.

write(filename, auxfiles='')

Invoke write command with filename as argument and set auxfiles if non-empty.

Args:

filename: outuput filename. auxfiles: auxfiles to export.

property solve_result

Return solve_result value, which indicates if the problem has been solved.

Number

String

Interpretation

0-99

solved

Optimal solution found

100-199

solved?

Optimal solution indicated, but error likely

200-299

infeasible

Constraints cannot be satisfied

300-399

unbounded

Objective can be improved without limit

400-499

limit

Stopped by a limit that you set (such as on iterations)

500-599

failure

Stopped by an error condition in the solver routines

property solve_result_num

Return solve_result_num value, which indicates if the problem has been solved.

Number

String

Interpretation

0-99

solved

Optimal solution found

100-199

solved?

Optimal solution indicated, but error likely

200-299

infeasible

Constraints cannot be satisfied

300-399

unbounded

Objective can be improved without limit

400-499

limit

Stopped by a limit that you set (such as on iterations)

500-599

failure

Stopped by an error condition in the solver routines

class amplpy.EntityMap(obj, entity_class)
__getitem__(key)
size()
__len__()