AMPL¶
-
class
AMPL
¶ An AMPL translator.
An object of this class can be used to do the following tasks:
- Run AMPL code. See eval() and evalAsync().
- Read models and data from files. See read(), readData(), readAsync() and readDataAsync().
- Solve optimization problems constructed from model and data (see solve() and solveAsync()).
- Access single Elements of an optimization problem. See getVariable(), getObjective(), getConstraint(), getSet() and getParameter().
- Access lists of available entities of an optimization problem. See getVariables(), getObjectives(), getConstraints(), getSets() and getParameters().
AMPL stores one or more problems which may consume substantial amount of memory. The AMPL object has a destructor which automaticallly closes the underlying AMPL interpreter and deletes all C++ entitites linked to it. Some entities (notably all instances of DataFrame and DataFrame::Slice) are not owned by the AMPL object and are not therefore deleted.
The initialization of the C++ representation of the AMPL entities (any class derived from ampl::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 C++ representation of one entity is obtained (through a call to 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 eval and similar functions invalidates all entities, and any further access to any entity will require communication between the native translator and the C++ code. Conversely, any operation called through the C++ 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:
- 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 C++, 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 ampl::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().
Public Functions
-
AMPL
()¶ Default constructor: creates a new AMPL instance with the default environment.
- Exceptions
std::runtime_error
: If no valid AMPL license has been found or if the translator cannot be started for any other reason.
-
AMPL
(const Environment &e)¶ Constructor: creates a new AMPL instance with the specified 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
- Exceptions
std::runtime_error
: If no valid AMPL license has been found or if the translator cannot be started for any other reason.
-
~AMPL
()¶ Default destructor Releases all the resources related to the AMPL instance (most notably kills the underlying interpreter.
-
DataFrame
getData
(StringArgs statements) const¶ 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 thedisplayStatements
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.
- Return
- DataFrame capturing the output of the display command in tabular form.
- Exceptions
AMPLException
: if the AMPL visualization command does not succeed for one of the reasons listed above.
- Parameters
statements
: The display statements to be fetched.
-
std::string
exportData
(bool includeSets = true) const¶ Get all data loaded in the current instance.
- Parameters
includeSets
: Set to false to export only the parameter values, to true to include the sets too
-
void
exportData
(fmt::CStringRef dataFileName, bool includeSets = true)¶ Write all data loaded in the current instance to a file.
- Parameters
dataFileName
: The file where to write the data toincludeSets
: Set to false to export only the parameter values, to true to include the sets too
-
void
exportModel
(fmt::CStringRef fileName) const¶ Write the declarations that were made in the current AMPL instance to a file.
- Parameters
fileName
: The file where to write the declarations to
-
Entity
getEntity
(fmt::CStringRef name) const¶ Get entity corresponding to the specified name (looks for it in all types of entities)
- Return
- The AMPL entity with the specified name
- Parameters
name
: Name of the entity
- Exceptions
std::out_of_range
: exception if the specified entity does not exist
-
Variable
getVariable
(fmt::CStringRef name) const¶ Get the variable with the corresponding name.
- Parameters
name
: Name of the variable to be found
- Exceptions
std::out_of_range
: exception if the specified variable does not exist
-
Constraint
getConstraint
(fmt::CStringRef name) const¶ Get the constraint with the corresponding name.
- Parameters
name
: Name of the constraint to be found
- Exceptions
std::out_of_range
: exception if the specified constraint does not exist
-
Objective
getObjective
(fmt::CStringRef name) const¶ Get the objective with the corresponding name.
- Parameters
name
: Name of the objective to be found
- Exceptions
An
: std::out_of_range exception if the specified objective does not exist
-
Set
getSet
(fmt::CStringRef name) const¶ Get the set with the corresponding name.
- Parameters
name
: Name of the set to be found
- Exceptions
std::out_of_range
: exception if the specified set does not exist
-
Parameter
getParameter
(fmt::CStringRef name) const¶ Get the parameter with the corresponding name.
- Parameters
name
: Name of the parameter to be found
- Exceptions
std::out_of_range
: exception if the specified parameter does not exist
-
void
eval
(fmt::CStringRef amplstatements)¶ 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 are reported as exceptions and warnings are printed on stdout. This behavior can be changed reassigning an ErrorHandler using setErrorHandler.
- Parameters
amplstatements
: A collection of AMPL statements and declarations to be passed to the interpreter
- Exceptions
std::runtime_error
: 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
-
void
reset
()¶ Clears all entities in the underlying AMPL interpreter, clears all maps and invalidates all entities.
-
void
close
()¶ Stops the underlying engine, and release all any further attempt to execute optimisation commands without restarting it will throw an exception.
-
bool
isRunning
() const¶ Returns true if the underlying engine is running.
-
bool
isBusy
() const¶ Returns true if the underlying engine is doing an async operation.
-
void
solve
()¶ Solve the current model.
- Exceptions
std::runtime_error
: If the underlying interpreter is not running
-
void
readAsync
(fmt::CStringRef filename, Runnable *cb)¶ 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
: Path to the file (Relative to the current working directory or absolute)cb
: Callback to be executed when the file has been interpreted
-
void
readDataAsync
(fmt::CStringRef filename, Runnable *cb)¶ 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 filecb
: Callback to be executed when the file has been interpreted
-
void
evalAsync
(fmt::CStringRef amplstatement, Runnable *cb)¶ Interpret the given AMPL statement Throws runtime_error if the underlying ampl interpreter is not running
-
void
solveAsync
(Runnable *cb)¶ Solve the current model asynchronously.
- Parameters
cb
: Object encapsulating the function to be called when solver is done
-
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 and the solver are idle.
-
std::string
cd
() const¶ Get the current working directory from the underlying interpreter (see https://en.wikipedia.org/wiki/Working_directory ).
- Return
- Current working directory
-
std::string
cd
(fmt::CStringRef path)¶ Change or display the current working directory (see https://en.wikipedia.org/wiki/Working_directory ).
- Return
- Current working directory
- Parameters
path
: New working directory or null (to display the working directory)
-
void
setOption
(fmt::CStringRef name, fmt::CStringRef 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
- Exceptions
std::invalid_argument
: if the option name is not valid
-
Optional<std::string>
getOption
(fmt::CStringRef name) const¶ Get the current value of the specified option.
If the option does not exist, the returned Optional object will not have value. Usage: if (auto value = ampl.getOption(“solver”)) value.get();
- Return
- Value of the option as a string.
- Parameters
name
: Option name (alphanumeric)
- Exceptions
std::invalid_argument
: if the option name is not valid
-
Optional<int>
getIntOption
(fmt::CStringRef name) const¶ Get the current value of the specified integer option.
If the option does not exist, the returned Optional object will not have value.
- Return
- Value of the option (integer)
- Parameters
name
: Option name (alphanumeric)
- Exceptions
std::invalid_argument
: if the option name is not validstd::invalid_argument
: If the option did not have a value which could be casted to integer
-
void
setIntOption
(fmt::CStringRef name, int value)¶ Set an AMPL option to a specified integer value.
- Parameters
name
: Name of the option to be setvalue
: The integer value the option must be set to
- Exceptions
std::invalid_argument
: if the option name is not valid
-
Optional<double>
getDblOption
(fmt::CStringRef name) const¶ Get the current value of the specified double option If the option does not exist, the returned Optional object will not have value.
- Return
- Value of the option (double)
- Parameters
name
: Option name
- Exceptions
std::invalid_argument
: if the option name is not validstd::invalid_argument
: If the option did not have a value which could be casted to double
-
void
setDblOption
(fmt::CStringRef name, double value)¶ Set an AMPL option to a specified double value.
- Parameters
name
: Name of the option to be setvalue
: The double value the option must be set to
- Exceptions
std::invalid_argument
: if the option name is not valid
-
Optional<bool>
getBoolOption
(fmt::CStringRef name) const¶ Get the current value of the specified boolean option.
In AMPL, boolean options are represented as integer: 0 for false, 1 for true. If the option does not exist, the returned Optional object will not have value.
- Return
- Value of the option (boolean)
- Parameters
name
: Option name
- Exceptions
std::invalid_argument
: if the option name is not validstd::invalid_argument
: If the option did not have a value which could be casted to boolean
-
std::string
getCurrentObjectiveName
()¶ Get the name of the currently active objective (see the
objective
command)- Return
- Current objective or empty string if no objective has been declared
-
void
setBoolOption
(fmt::CStringRef name, bool 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 setvalue
: The boolean value the option must be set to
- Exceptions
std::invalid_argument
: if the option name is not valid
-
void
read
(fmt::CStringRef 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.
- Exceptions
runtime_error
: In case the file does not exist.
-
void
readData
(fmt::CStringRef 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.
- Parameters
fileName
: Full path to the file.
- Exceptions
std::runtime_error
: In case the file does not exist.
-
Variant
getValue
(fmt::CStringRef scalarExpression) const¶ Get a scalar value from the underlying AMPL interpreter, as a double or a string.
- Return
- A Variant which represent the value of the expression.
- Parameters
scalarExpression
: An AMPL expression which evaluates to a scalar value.
-
std::string
getOutput
(fmt::CStringRef amplstatement)¶ Equivalent to eval() but returns the output as a string.
- Return
- A std::string with the output.
-
void
setData
(const DataFrame &df, fmt::CStringRef 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.
- 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.
- Exceptions
AMPLException
: If the data assignment procedure was not successful.
-
std::string
toString
() const¶ Get a string describing the object.
Returns the version of the API and either 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
AMPL::close)- Return
- A std::string that represents this object.
-
void
readTable
(fmt::CStringRef 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.
-
void
writeTable
(fmt::CStringRef 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.
-
void
display
(StringArgs 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.- Parameters
amplExpressions
: Expressions to be evaluated.
-
void
display
(EntityArgs entities)¶ Writes on the current OutputHandler the outcome of the AMPL statement.
display e1, e2, .., en;
where
e1...en
are the objects passed to the procedure.- Parameters
entities
: The entities to display
-
void
show
(EntityArgs 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
: The entities to show
-
void
expand
(EntityArgs entities)¶ Writes on the current OutputHandler the outcome of the AMPL statement.
expand e1, e2, .., en;
where
e1...en
are the objects passed to the procedure.- Parameters
entities
: The entities to expand
-
void
setOutputHandler
(OutputHandler *outputhandler)¶ Sets a new output handler.
- Parameters
outputhandler
: The function handling the AMPL output derived from interpreting user commands.
-
void
setErrorHandler
(ErrorHandler *errorhandler)¶ Sets a new error handler Note that the ownership of the error handling object remains of the caller.
- Parameters
errorhandler
: The object handling AMPL errors and warnings.
-
OutputHandler *
getOutputHandler
() const¶ Get the current output handler.
- Return
- A pointer to the current output handler.
-
ErrorHandler *
getErrorHandler
() const¶ Get the current error handler.
- Return
- A pointer to the current error handler.
-
EntityMap<Constraint>
getConstraints
() const¶ Get all the constraints declared.