AMPL#
- class ampl.AMPL : IDisposable#
An AMPL translator.
An object of this class can be used to do the following tasks:
Run AMPL code. See
ampl.AMPL.Eval
.Read models and data from files. See
ampl.AMPL.read
andampl.AMPL.ReadData
.Solve optimization problems constructed from model and data (see
ampl.AMPL.Solve
).Access single elements of an optimization problem. See the generic
ampl.AMPL.GetEntity
and the genericampl.AMPL.GetVariable
,ampl.AMPL.GetObjective
,ampl.AMPL.GetConstraint
,ampl.AMPL.GetSet
andampl.AMPL.GetParameter
.Access lists of available elements of an optimization problem. See
ampl.AMPL.GetVariables
,ampl.AMPL.GetObjectives
,ampl.AMPL.GetConstraints
,ampl.AMPL.GetSets
andampl.AMPL.GetParameters
.AMPL stores one or more problems which may consume substantial amount of memory. An AMPL object without any references to it will eventually be freed by the Java garbage collector and all the memory and other resources associated with it will be released. This includes any resources which are out of scope of the garbage collector such as open files or memory managed by the native code. Call
ampl.AMPL.Close
to release these resources explicitly.The initialization of the Java representation of the AMPL entities (any class derived from
ampl.Entities.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 Java representation of one entity is obtained (through a call toampl.AMPL.GetEntity
or 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
ampl.AMPL.Eval
and similar functions invalidates all entities, and any further access to any entity will require communication between the native translator and the Java code. Conversely, any operation called through the Java 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
ampl.AMPL.Eval
method) are handled by the eventampl.AMPL.Error
. Note that by default the event is disabled. To enable it, callampl.AMPL.EnableErrorAndWarningRouting
.Generic errors coming from misusing the API, which are detected in .NET, 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 by the event
ampl.AMPL.Output
, which is called at each block of output from the translator after the functionampl.AMPL.EnableOutputRouting
is called.Public Functions
- void EnableOutputRouting ()#
Enable routing of AMPL console outputs through the C# wrapper.
Must be called to enable handling of the output through a personalised handler registered with
ampl.AMPL.Output
.See also
- void EnableErrorAndWarningRouting ()#
Enable routing of AMPL error and warning handling via the C# wrapper.
Must be called to enable handling of errors and warning through handlers registered with
ampl.AMPL.Error
andampl.AMPL.Warning
.See also
- AMPL ()#
Default constructor: creates a new AMPL instance with the default environment.
- Throws ApplicationException:
If no valid AMPL license has been found or if the translator cannot be started for any other reason.
- AMPL (Environment e)
Creates a new AMPL instance with the specified environment.
- Throws ApplicationException:
If no valid AMPL license has been found or if the translator cannot be started for any other reason.
- void Eval (string 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.
- string GetOutput (string AMPLStatements)#
Equivalent to
ampl.AMPL.eval
but returns the output as a string.
- 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 its resources.
Any further attempt to execute optimisation commands without restarting it will throw an exception.
- void Solve (string problem = "", string solver = "")#
Solve the model.
- Param problem:
Problem to solve.
- Param solver:
Solver to use.
- void Read (string 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)
- Param filename:
Path to the file (Relative to the current working directory or absolute)
- void ReadData (string filename)#
Interprets the specified 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)
- Param filename:
Path to the file (Relative to the current working directory or absolute)
- string Cd (string directoryName = null)#
Change or display the current working directory (see https://en.wikipedia.org/wiki/Working_directory ).
<return>The current working directory</return>
- Param directoryName:
New working directory or null (to display the working directory)
- void ReadTable (string tableName)#
Read the table corresponding to the specified name, equivalent to the AMPL statement:
read table tableName;
- Param tableName:
Name of the table to be read
- 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.
- void EvalAsync (string AMPLStatements, Action cb)#
Interpret asynchronously the given AMPL statements.
- Param AMPLStatements:
Statements to be interpreted
- Param cb:
Call back to be executed when completed
- void SolveAsync (Action cb)#
Solve the current model asynchronously.
- Param cb:
Call back to be executed when completed
- void ReadAsync (string filename, Action 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)
- Param filename:
Path to the file (Relative to the current working directory or absolute)
- Param cb:
Callback to be executed when the file has been interpreted
- void ReadDataAsync (string filename, Action cb)#
Interprets the specified data file asynchronously, interpreting it as a model or a script file.
The file is interpreted as data. As a side effect, it invalidates all entities (as the file can contain arbitrary commands); the lists of entities will be re-populated lazily (at first access)
- Param filename:
Path to the file (Relative to the current working directory or absolute)
- Param cb:
Callback to be executed when the file has been interpreted
- string Snapshot (string fileName = "", bool model = true, bool data = true, bool options = true)#
Returns all the declarations and data in the current AMPL session.
- Param fileName:
The file where to write the snapshot to.
- Param model:
Include model if set to true.
- Param data:
Include data if set to true.
- Param options:
Include options if set to true.
- void ExportModel (string fileName)
Writes the declarations in the current AMPL instance to file.
- Param fileName:
The file to write
- string ExportData ()#
Get all the data currently loaded in dat format.
- void ExportData (string fileName)
Writes all the data currently loaded to file in dat format.
- Param fileName:
The file to write
- Entities.VariableMap GetVariables ()#
Get the defined variables.
- Entities.ConstraintMap GetConstraints ()#
Get the defined constraints.
- Entities.ObjectiveMap GetObjectives ()#
Get the defined objectives.
- Entities.SetMap GetSets ()#
Get the defined sets.
- Entities.ParameterMap GetParameters ()#
Get the defined parameters.
- Entities.EntityBase GetEntity (string name)#
Get entity corresponding to the specified name (looks for it in all types of entities)
- Param name:
Name of the entity
- Throws ArgumentOutOfRangeException:
If the specified entity is not found
- Return:
The AMPL entity with the specified name
- Entities.Variable GetVariable (string name)#
Get the variable with the corresponding name.
- Param name:
Name of the variable to be found
- Throws ArgumentOutOfRangeException:
If the specified variable does not exist
- Entities.Constraint GetConstraint (string name)#
Get the constraint with the corresponding name.
- Param name:
Name of the constraint to be found
- Throws ArgumentOutOfRangeException:
If the specified constraint does not exist
- Entities.Objective GetObjective (string name)#
Get the objective with the corresponding name.
- Param name:
Name of the objective to be found
- Throws ArgumentOutOfRangeException:
If the specified objective does not exist
- Entities.Parameter GetParameter (string name)#
Get the parameter with the corresponding name.
- Param name:
Name of the parameter to be found
- Throws ArgumentOutOfRangeException:
If the specified parameter does not exist
- Entities.Set GetSet (string name)#
Get the set with the corresponding name.
- Param name:
Name of the set to be found
- Throws ArgumentOutOfRangeException:
If the specified set does not exist
- Variant GetValue (string scalarExpression)#
Get a scalar value from the underlying AMPL interpreter, as a double or a string.
- Param scalarExpression:
An AMPL expression which evaluates to a scalar value.
- Return:
- DataFrame GetData (params string[] 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<c> ds1, …, dsn are the statements 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.
- Param statements:
The display statements to be fetched
- Return:
DataFrame capturing the output of the display command in tabular form
- void SetData (DataFrame df, string setName = null)#
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.
- Param df:
The dataframe containing the data to be assigned
- Param setName:
The name of the set to which the indices values of the DataFrame are to be assigned.
- void SetOption (string name, string value)#
Set an AMPL option to a specified value.
- Param name:
Name of the option to be set (alphanumeric without spaces)
- Param value:
String representing the value the option must be set to
- Throws ArgumentException:
if the option name is not valid
- void SetOption (string name, double value)
Set an AMPL option to a specified double value.
- Param name:
Name of the option to be set (alphanumeric without spaces)
- Param value:
Value the option must be set to
- Throws ArgumentException:
if the option name is not valid
- void SetOption (string name, int value)
Set an AMPL option to a specified integer value.
- Param name:
Name of the option to be set (alphanumeric without spaces)
- Param value:
Value the option must be set to
- Throws ArgumentException:
if the option name is not valid
- void SetOption (string name, bool value)
Set an AMPL option to a specified boolean value.
In AMPL, boolean options are represented as integer: 0 for false, 1 for true.
- Param name:
Name of the option to be set (alphanumeric without spaces)
- Param value:
Value the option must be set to
- Throws ArgumentException:
if the option name is not valid
- string GetOption (string name)#
Get the current value of the specified option.
- Param name:
Option name
- Return:
The option value, null if the specified option does not exist
- int? GetIntOption (string name)#
Get the current value of the specified option.
- Param name:
Option name
- Throws ArgumentException:
If the option is not in the correct format
- Return:
The option value, null if the specified option does not exist
- double? GetDblOption (string name)#
Get the current value of the specified option.
- Param name:
Option name
- Throws ArgumentException:
If the option is not in the correct format
- Return:
The option value, null if the specified option does not exist
- bool? GetBoolOption (string name)#
Get the current value of the specified boolean option.
- Param name:
Option name
- Throws ArgumentException:
If the option is not in the correct format
- Return:
The option value, null if the specified option does not exist
- override string ToString ()#
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())
Properties
- string CurrentObjectiveName { get; set; }#
Get the name of the currently active objective (see the
objective
command), or null if no objective has been declared or selected.
- Entities.VariableMap Var { get; set; }#
Get the defined variables.
- Entities.ConstraintMap Con { get; set; }#
Get the defined constraints.
- Entities.ObjectiveMap Obj { get; set; }#
Get the defined objectives.
- Entities.SetMap Set { get; set; }#
Get the defined sets.
- Entities.ParameterMap Param { get; set; }#
Get the defined parameters.
Events
- event Action<Kind, string> Output#
Raised for each AMPL output, if
ampl.AMPL.EnableOutputRouting
has been called on the current object instance.
- event Action<AMPLException> Error#
Raised for each AMPL error, if
ampl.AMPL.EnableErrorAndWarningRouting
has been called on the current object instance.
- event Action<AMPLException> Warning#
Raised for each AMPL warning, if
ampl.AMPL.EnableErrorAndWarningRouting
has been called on the current object instance.
Public Static Functions
- void LoadModules ()#
Enable the use of the binaries distributed with the NuGet packages in the namespace AMPL.Module.
- Throws FileNotFoundException:
If the NuGet package(s) are not correctly deployed
Kind#
Represents the type of the output coming from the interpreter.
Output related to command execution:
WAITING
– Outputprompt2
, returned when incomplete statements are interpreted.
BREAK
– Outputbreak
, displayed when an operation is interrupted with SIGINT.
CD
– Outputcd
, returned by thecd
function.
DISPLAY
– Outputdisplay
, returned by thedisplay
function.
EXIT
– Outputexit
, returned as the last message from AMPL before exiting the interpreter.
EXPAND
– Outputexpand
, returned by theexpand
function.
LOAD
– Outputload
, returned by theload
function when loading a library.
OPTION
– Outputoption
, returned by theoption
function when getting the value of an option.
PROMPT
– Outputprompt1
, normal AMPL prompt.Solver and solution-related output:
SOLUTION
– Outputsolution
, returned when loading a solution with thesolution
command; contains the solver message.
SOLVE
– Outputsolve
, returned by thesolve
function; contains the solver message.Miscellaneous command output:
SHOW
– Outputshow
, returned by theshow
function.
XREF
– Outputxref
, returned by thexref
function.
SHELL_OUTPUT
– Output from the AMPL commandshell
.
SHELL_MESSAGE
– Messages from the commandshell
.
MISC
– General miscellaneous output.
WRITE_TABLE
– Messages from thewrite table
command.
READ_TABLE
– Messages from theread table
command.
_READTABLE
– Internal messages from theread table
command.
_WRITETABLE
– Internal messages from thewrite table
command.Debugging and scripting:
BREAKPOINT
– Breakpoint hit.
CALL
– Output of a scriptcall
.
CHECK
– Output of acheck
operation.
CLOSE
– Output of aclose
command for output redirection.
COMMANDS
– Output of acommands
call into another file.
CONTINUE
– Issued whencontinue
is encountered.
DATA
– Output of adata
command.
DELETECMD
– Output of adelete
command.
DROP
– Output of adrop
command.
DROP_OR_RESTORE_ALL
– Internal.
ELSE
– Else block.
ELSE_CHECK
– Internal.
ENDIF
– End of if block.
ENVIRON
– Output of anenviron
command.
FIX
– Output of afix
command.
FOR
– Output of afor
command.
IF
– Output of anif
command.
LET
– Output of alet
command.
LOOPEND
– End of loop.
OBJECTIVE
– Output of anobjective
command.
OPTION_RESET
– Occurs when resetting option values.
PRINTF
– Output of aprintf
command.
PROBLEM
– Output of aproblem
command.
PURGE
– Output of apurge
command.
RBRACE
– Occurs when a right brace is encountered.
READ
– Output of aread
command.
RELOAD
– Output of areload
command.
REMOVE
– Output of aremove
command.
REPEAT
– Beginning of arepeat
block.