Clad.cs
1using System;
2using System.Collections.Generic;
3using System.Linq;
4using System.Text;
5using GAMS;
6using System.Threading;
7using System.IO;
8using System.Diagnostics;
9using System.Text.RegularExpressions;
10
11namespace Clad
12{
27 class Clad
28 {
29 static int Main(string[] args)
30 {
32 if (Environment.GetCommandLineArgs().Length > 1)
33 ws = new GAMSWorkspace(systemDirectory: Environment.GetCommandLineArgs()[1]);
34 else
35 ws = new GAMSWorkspace();
36
37 // Use the GAMS Model Library model "clad" as an example
38 GAMSJob j1 = ws.AddJobFromGamsLib("clad");
39
40 // Define an option file for the solver to be used
41 using (StreamWriter outfile = new StreamWriter(Path.Combine(ws.WorkingDirectory, "cplex.opt")))
42 {
43 // Set relative stopping tolerance to 0 initially
44 outfile.WriteLine("epgap 0");
45 // Activate interactive option setting on interrupt
46 outfile.WriteLine("interactive 1");
47 // Define new option file to read on interrupt
48 outfile.WriteLine("iafile cplex.op2");
49 }
50
51 GAMSOptions opt = ws.AddOptions();
52 opt.MIP = "cplex";
53 opt.OptFile = 1;
54 opt.SolveLink = GAMSOptions.ESolveLink.LoadLibrary;
55
56 StringWriter sw = new StringWriter();
57
58 // Run GAMSJob j1 in separate thread
59 Thread optThread = new Thread(new ThreadStart(delegate() { j1.Run(output: sw, gamsOptions: opt); }));
60 optThread.Start();
61
62 // Define list of increasing stopping tolerances
63 List<Tuple<int, String>> steps = new List<Tuple<int, String>>();
64 steps.Add(new Tuple<int, String>(5, "epgap 0.1"));
65 steps.Add(new Tuple<int, String>(10, "epgap 0.2"));
66 steps.Add(new Tuple<int, String>(20, "epagap 1e9"));
67
68 int prevStep = 0;
69 foreach (var s in steps)
70 {
71 // Wait a while and check if j1 is still running
72 if (optThread.Join(TimeSpan.FromSeconds(s.Item1 - prevStep)))
73 break;
74 prevStep = s.Item1;
75 // Write new Cplex option file
76 using (StreamWriter outfile = new StreamWriter(Path.Combine(ws.WorkingDirectory, "cplex.op2")))
77 outfile.WriteLine(s.Item2);
78 // Interrupt j1 to read new Cplex option file
79 j1.Interrupt();
80 Console.WriteLine("Interrupted Cplex to continue with new option: " + s.Item2);
81 }
82
83 // If j1 is still running, wait until it is finished
84 if (optThread.IsAlive)
85 optThread.Join();
86
87 // Check if everything worked as expected
88 String log = sw.ToString();
89 if (!log.Contains("MIP status(113): aborted"))
90 {
91 Console.WriteLine("Expected the solver to be interrupted at least once.");
92 return 1;
93 }
94 return 0;
95 }
96 }
97}
void Run(GAMSOptions gamsOptions=null, GAMSCheckpoint checkpoint=null, TextWriter output=null, Boolean createOutDB=true)
Definition: Clad.cs:11
GAMSOptions AddOptions(GAMSOptions optFrom=null)
GAMSJob AddJobFromGamsLib(string model, GAMSCheckpoint checkpoint=null, string jobName=null)
ESolveLink SolveLink