AMPL¶
-
class ampl::AMPL¶
An AMPL translator.
An object of this class can be used to do the following tasks:
Run AMPL code. See eval().
Read models and data from files. See read() and readData().
Solve optimization problems constructed from model and data (see solve()).
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 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
-
inline AMPL()¶
Default constructor: creates a new AMPL instance with the default environment.
- Throws
std::runtime_error – If no valid AMPL license has been found or if the translator cannot be started for any other reason.
-
inline 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
- Throws
std::runtime_error – If no valid AMPL license has been found or if the translator cannot be started for any other reason.
-
inline ~AMPL()¶
Default destructor Releases all the resources related to the AMPL instance (most notably kills the underlying interpreter.
-
inline 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.
- Throws
AMPLException – if the AMPL visualization command does not succeed for one of the reasons listed above.
- Parameters
statements – The display statements to be fetched.
- Returns
DataFrame capturing the output of the display command in tabular form.
-
inline 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
-
inline 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 to
includeSets – Set to false to export only the parameter values, to true to include the sets too
-
inline std::string exportModel() const¶
Get the declarations that were made in the current AMPL instance.
-
inline 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
-
inline Entity getEntity(fmt::CStringRef name) const¶
Get entity corresponding to the specified name (looks for it in all types of entities)
- Parameters
name – Name of the entity
- Throws
std::out_of_range – exception if the specified entity does not exist
- Returns
The AMPL entity with the specified name
-
inline Variable getVariable(fmt::CStringRef name) const¶
Get the variable with the corresponding name.
- Parameters
name – Name of the variable to be found
- Throws
std::out_of_range – exception if the specified variable does not exist
-
inline Constraint getConstraint(fmt::CStringRef name) const¶
Get the constraint with the corresponding name.
- Parameters
name – Name of the constraint to be found
- Throws
std::out_of_range – exception if the specified constraint does not exist
-
inline Objective getObjective(fmt::CStringRef name) const¶
Get the objective with the corresponding name.
- Parameters
name – Name of the objective to be found
- Throws
An – std::out_of_range exception if the specified objective does not exist
-
inline Set getSet(fmt::CStringRef name) const¶
Get the set with the corresponding name.
- Parameters
name – Name of the set to be found
- Throws
std::out_of_range – exception if the specified set does not exist
-
inline Parameter getParameter(fmt::CStringRef name) const¶
Get the parameter with the corresponding name.
- Parameters
name – Name of the parameter to be found
- Throws
std::out_of_range – exception if the specified parameter does not exist
-
inline Table getTable(fmt::CStringRef name) const¶
Get the table with the corresponding name.
- Parameters
name – Name of the table to be found
- Throws
std::out_of_range – exception if the specified table does not exist
-
inline 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
- Throws
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
-
inline void reset()¶
Clears all entities in the underlying AMPL interpreter, clears all maps and invalidates all entities.
-
inline void close()¶
Stops the underlying engine, and release all any further attempt to execute optimisation commands without restarting it will throw an exception.
-
inline bool isRunning() const¶
Returns true if the underlying engine is running.
-
inline bool isBusy() const¶
Returns true if the underlying engine is doing an async operation.
-
inline void solve()¶
Solve the current model.
- Throws
std::runtime_error – If the underlying interpreter is not running
-
inline 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
-
inline 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 file
cb – Callback to be executed when the file has been interpreted
-
inline void evalAsync(fmt::CStringRef amplstatement, Runnable *cb)¶
Interpret the given AMPL statement Throws runtime_error if the underlying ampl interpreter is not running
-
inline void solveAsync(Runnable *cb)¶
Solve the current model asynchronously.
- Parameters
cb – Object encapsulating the function to be called when solver is done
-
inline 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.
-
inline std::string cd() const¶
Get the current working directory from the underlying interpreter (see https://en.wikipedia.org/wiki/Working_directory ).
- Returns
Current working directory
-
inline std::string cd(fmt::CStringRef path)¶
Change or display the current working directory (see https://en.wikipedia.org/wiki/Working_directory ).
- Parameters
path – New working directory or null (to display the working directory)
- Returns
Current working directory
-
inline 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
- Throws
std::invalid_argument – if the option name is not valid
-
inline 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();
- Parameters
name – Option name (alphanumeric)
- Throws
std::invalid_argument – if the option name is not valid
- Returns
Value of the option as a string.
-
inline 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.
- Parameters
name – Option name (alphanumeric)
- Throws
std::invalid_argument – if the option name is not valid
std::invalid_argument – If the option did not have a value which could be casted to integer
- Returns
Value of the option (integer)
-
inline void setIntOption(fmt::CStringRef name, int value)¶
Set an AMPL option to a specified integer value.
- Parameters
name – Name of the option to be set
value – The integer value the option must be set to
- Throws
std::invalid_argument – if the option name is not valid
-
inline 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.
- Parameters
name – Option name
- Throws
std::invalid_argument – if the option name is not valid
std::invalid_argument – If the option did not have a value which could be casted to double
- Returns
Value of the option (double)
-
inline void setDblOption(fmt::CStringRef name, double value)¶
Set an AMPL option to a specified double value.
- Parameters
name – Name of the option to be set
value – The double value the option must be set to
- Throws
std::invalid_argument – if the option name is not valid
-
inline 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.
- Parameters
name – Option name
- Throws
std::invalid_argument – if the option name is not valid
std::invalid_argument – If the option did not have a value which could be casted to boolean
- Returns
Value of the option (boolean)
-
inline std::string getCurrentObjectiveName()¶
Get the name of the currently active objective (see the
objective
command)- Returns
Current objective or empty string if no objective has been declared
-
inline 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 set
value – The boolean value the option must be set to
- Throws
std::invalid_argument – if the option name is not valid
-
inline 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.
- Throws
runtime_error – In case the file does not exist.
-
inline 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.
- Throws
std::runtime_error – In case the file does not exist.
-
inline Variant getValue(fmt::CStringRef scalarExpression) const¶
Get a scalar value from the underlying AMPL interpreter, as a double or a string.
- Parameters
scalarExpression – An AMPL expression which evaluates to a scalar value.
- Returns
A Variant which represent the value of the expression.
-
inline std::string getOutput(fmt::CStringRef amplstatement)¶
Equivalent to eval() but returns the output as a string.
- Returns
A std::string with the output.
-
inline 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.
- Throws
AMPLException – If the data assignment procedure was not successful.
-
inline 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)- Returns
A std::string that represents this object.
-
inline 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.
-
inline 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.
-
inline void write(fmt::CStringRef filename, fmt::CStringRef auxfiles = nullptr)¶
Write model instances.
equivalent to
option auxfiles auxfiles; write filename;
- Parameters
filename – The name of the file to write; the first letter indicates which filetype to write (see the output of
ampl -o?
)auxfiles – The auxiliary files to write. Most notably, ‘cr’ instructs AMPL to write out column and row names respectively
- Throws
PresolveException – if the model is not exported because of the presolver (most notably if the model is trivial)
InfeasibilityException – if the model is not exported because detected infeasible by the presolver
-
inline 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.
-
inline 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
-
inline 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
-
inline 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
-
inline void setOutputHandler(OutputHandler *outputhandler)¶
Sets a new output handler.
- Parameters
outputhandler – [in] The function handling the AMPL output derived from interpreting user commands.
-
inline void setErrorHandler(ErrorHandler *errorhandler)¶
Sets a new error handler Note that the ownership of the error handling object remains of the caller.
- Parameters
errorhandler – [in] The object handling AMPL errors and warnings.
-
inline OutputHandler *getOutputHandler() const¶
Get the current output handler.
- Returns
A pointer to the current output handler.
-
inline ErrorHandler *getErrorHandler() const¶
Get the current error handler.
- Returns
A pointer to the current error handler.
-
inline EntityMap<Constraint> getConstraints() const¶
Get all the constraints declared.