using ampl;
using System;
using System.Collections.Generic;
namespace Examples
{
///
/// This example shows how to redirect AMPL output (normally directed to the console) and AMPL
/// errors (by default, an error throws an exception and a warning is simply directed to the console.
///
public class OutputAndErrorRedirectionExample
{
private static List> outputs = new List>();
public static int Main(string[] args)
{
try
{
using (var ampl = new AMPL())
{
ampl.Eval("var x{1..3};");
ampl.Eval("maximize z: sum{i in 1..3} x[i];");
// *** Output redirection *** Enable output redirection
ampl.EnableOutputRouting();
// Assign handler: Method 1: using method
ampl.Output += HandleOutput;
ampl.Eval("display x;");
ampl.Eval("let {i in 1..3} x[i] := i;");
ampl.Eval("display x;");
// Unassign output handler
ampl.Output -= HandleOutput;
// print all outputs
foreach (var t in outputs)
Console.Write("{0} - Kind: {1} - Msg:\n{2}", t.Item1,
t.Item2, t.Item3);
// Method 2: Using lambda expression
ampl.Output += (kind, message) => Console.Write("Got AMPL message:\n{0}\n", message);
// Test it
ampl.Eval("display x,x;");
// *** Error redirection *** Enable error and warnings redirection
ampl.EnableErrorAndWarningRouting();
// Register handlers
ampl.Error += HandleError;
ampl.Warning += HandleWarning;
// Normally throws exception, will just be printed on screen
ampl.Eval("var x;");
// Create an obvious infeasibility
ampl.Eval("c1: x[1]>=1; c2: x[1]<=0;");
// Solve the model, issuing a warning
ampl.Solve();
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return 1;
}
return 0;
}
private static void HandleError(AMPLException obj)
{
Console.Write("Got error: {0}\n", obj.Message);
}
private static void HandleOutput(Kind arg1, string arg2)
{
outputs.Add(System.Tuple.Create(DateTime.Now, arg1, arg2));
}
private static void HandleWarning(AMPLException obj)
{
Console.Write("Got warning: {0}\n", obj.Message);
}
}
}