Loading...
Searching...
No Matches
TestGAMSModelInstance.cs
1using GAMS;
2using NLog;
3using NUnit.Framework;
4using System;
5using System.IO;
6
7
8namespace GamsApiTests
9{
10 [TestFixture]
12 {
13 static readonly String PROPERTIES_FILE = "test.properties";
14 static GAMSWorkspaceInfo wsInfo;
15 static Logger logger = LogManager.GetCurrentClassLogger();
16 static GAMSWorkspace ws;
17 static GAMSCheckpoint cp;
18 static GAMSJob job;
19 static GAMSOptions opt;
20 static GAMSModelInstance mi;
21 static GAMSModelInstance copy;
22
23 static readonly String MODEL =
24 "Sets \n" +
25 " i canning plants / seattle, san-diego / \n" +
26 " j markets / new-york, chicago, topeka / ; \n" +
27 " \n" +
28 "Parameters \n" +
29 " a(i) capacity of plant i in cases \n" +
30 " / seattle 350 \n" +
31 " san-diego 600 / \n" +
32 " \n" +
33 " b(j) demand at market j in cases \n" +
34 " / new-york 325 \n" +
35 " chicago 300 \n" +
36 " topeka 275 / ; \n" +
37 " \n" +
38 "Table d(i,j) distance in thousands of miles \n" +
39 " new-york chicago topeka \n" +
40 "seattle 2.5 1.7 1.8 \n" +
41 "san-diego 2.5 1.8 1.4 ; \n" +
42 " \n" +
43 "Scalar f freight in dollars per case per thousand miles /90/ ; \n" +
44 "Scalar bmult demand multiplier /1/; \n" +
45 " \n" +
46 "Parameter c(i,j) transport cost in thousands of dollars per case ; \n" +
47 " c(i,j) = f * d(i,j) / 1000 ; \n" +
48 " \n" +
49 "Variables \n" +
50 " x(i,j) shipment quantities in cases \n" +
51 " z total transportation costs in thousands of dollars ; \n" +
52 " \n" +
53 "Positive Variable x ; \n" +
54 " \n" +
55 "Equations \n" +
56 " cost define objective function \n" +
57 " supply(i) observe supply limit at plant i \n" +
58 " demand(j) satisfy demand at market j ; \n" +
59 " \n" +
60 " cost .. z =e= sum((i,j), c(i,j)*x(i,j)) ; \n" +
61 " \n" +
62 " supply(i) .. sum(j, x(i,j)) =l= a(i) ; \n" +
63 " \n" +
64 " demand(j) .. sum(i, x(i,j)) =g= bmult*b(j) ; \n" +
65 " \n" +
66 "Model transport /all/ ; \n" +
67 " \n";
68
69 [OneTimeSetUp]
70 public static void OneTimeSetUp()
71 {
72 logger.Debug("entering TestGAMSModelInstance | SetUpBeforeClass");
73 HouseKeeper.initializeTestFrom(PROPERTIES_FILE, "TestGAMSModelInstance");
74 logger.Info("Housekeeper task initialized");
75 wsInfo = new GAMSWorkspaceInfo();
76 wsInfo.WorkingDirectory = HouseKeeper.gamsWorkingDir;
77 wsInfo.SystemDirectory = HouseKeeper.gamsSystemDir;
78 wsInfo.Debug = DebugLevel.Off;
79 logger.Debug("exiting TestGAMSModelInstance | SetUpBeforeClass");
80 }
81
82 [TearDown]
83 public static void TearDown()
84 {
85 cp = null;
86 job = null;
87 if (mi != null)
88 {
89 if (mi.SyncDB != null)
90 {
91 mi.SyncDB.Clear();
92 mi.SyncDB.Dispose();
93 }
94 mi.Dispose();
95 mi = null;
96 }
97
98 if (copy != null)
99 {
100 if (copy.SyncDB != null)
101 {
102 copy.SyncDB.Clear();
103 copy.SyncDB.Dispose();
104 }
105 copy.Dispose();
106 copy = null;
107 }
108 ws = null;
109 opt = null;
110 }
111
112 [Test]
113 public void testAddModelInstanceInstantiateAndSolve()
114 {
115 logger.Debug("entering TestGAMSModelInstance | testAddModelInstanceInstantiateAndSolve");
116
117 ws = new GAMSWorkspace(wsInfo);
118 cp = ws.AddCheckpoint();
119 Assert.That(cp != null, "do not expect cp as null");
120 StringAssert.AreEqualIgnoringCase(new FileInfo(ws.WorkingDirectory).FullName,
121 new FileInfo(cp.WorkSpace.WorkingDirectory).FullName,
122 "expect [" + ws.WorkingDirectory + "] as a checkpoint's working directory.");
123 job = ws.AddJobFromString(MODEL);
124 Assert.NotNull(job, "do not expect a null job");
125
126 job.Run(cp);
127 Assert.That(job.OutDB.NrSymbols > 0, "expect non-empty OutDB");
128 Assert.AreEqual("bmult", job.OutDB.GetParameter("bmult").Name, "expect bmult in OutDB");
129 Assert.AreEqual(0, job.OutDB.GetParameter("bmult").Dim, "expect bmult as scalar");
130
131 mi = cp.AddModelInstance();
132
133 Assert.NotNull(mi, "do not expect a null mi");
134 Assert.NotNull(mi.SyncDB, "do not expect a null syncDB");
135 Assert.AreEqual(0, mi.SyncDB.NrSymbols, "expect an empty syncDB");
136
137 GAMSParameter bmult = mi.SyncDB.AddParameter("bmult", "demand multiplier");
138 opt = ws.AddOptions();
139 opt.AllModelTypes = "cplex";
140
141 Assert.NotNull(bmult, "do not expect a null bmult");
142
143 Assert.Throws<GAMSException>(() => bmult.AddRecord().Value = 1.0);
144 Assert.AreEqual(0, bmult.NumberRecords, "expect empty records");
145
146 mi.Instantiate("transport use lp min z", opt, new GAMSModifier(bmult));
147 bmult.AddRecord().Value = 1.0;
148 Assert.AreEqual(1, bmult.NumberRecords, "expect one record in bmult");
149
150 mi.Solve();
151 Assert.AreEqual(ModelStat.OptimalGlobal, mi.ModelStatus, "expect ModelStatus:OPTIMAL_GLOBAL");
152 Assert.AreEqual(SolveStat.Normal, mi.SolveStatus, "expect SolveStatus: NORMAL");
153
154 bmult.FirstRecord().Value = 1.2;
155 mi.Solve();
156
157 Assert.AreEqual(ModelStat.InfeasibleGlobal, mi.ModelStatus, "expect ModelStatus:INFEASIBLE_GLOBAL");
158 Assert.AreEqual(SolveStat.Normal, mi.SolveStatus, "expect SolveStatus: NORMAL");
159
160 bmult.FirstRecord().Value = 0.8;
161 mi.Solve();
162
163 Assert.AreEqual(ModelStat.OptimalGlobal, mi.ModelStatus, "expect ModelStatus :OPTIMAL_GLOBAL");
164 Assert.AreEqual(SolveStat.Normal, mi.SolveStatus, "expect SolveStatus: NORMAL");
165
166
167 logger.Debug("exiting TestGAMSModelInstance | testAddModelInstanceInstantiateAndSolve");
168 }
169
170 [Test]
171 public void testCopyModelInstanceAndSolve()
172 {
173 logger.Debug("entering TestGAMSModelInstance | testAddModelInstanceInstantiateAndSolve");
174
175 ws = new GAMSWorkspace(wsInfo);
176 cp = ws.AddCheckpoint();
177 job = ws.AddJobFromString(MODEL);
178 job.Run(cp);
179
180 mi = cp.AddModelInstance();
181 GAMSParameter bmult = mi.SyncDB.AddParameter("bmult", "demand multiplier");
182 opt = ws.AddOptions();
183 opt.AllModelTypes = "cplex";
184 mi.Instantiate("transport use lp min z", opt, new GAMSModifier(bmult));
185
186 bmult.AddRecord().Value = 1.0;
187 mi.Solve();
188
189 copy = mi.CopyModelinstance();
190 copy.Solve();
191
192 Assert.NotNull(copy, "do not expect a null copy");
193 Assert.AreEqual(mi.ModelStatus, copy.ModelStatus, "expect copy MI with the same model status");
194 Assert.AreEqual(mi.SolveStatus, copy.SolveStatus, "expect copy MI with the same solve status");
195 Assert.AreEqual(mi.SyncDB.NrSymbols, copy.SyncDB.NrSymbols, "expect copy.SyncDB() with the same number of symbols");
196
197 logger.Debug("exiting TestGAMSModelInstance | testCopyModelInstanceAndSolve");
198 }
199
200 [Test]
201 public void testSolveWhenDebugIsTrue()
202 {
203 logger.Debug("entering TestGAMSModelInstance | testSolveWhenDebugIsTrue");
204
205 ws = new GAMSWorkspace(wsInfo);
206 cp = ws.AddCheckpoint();
207 job = ws.AddJobFromString(MODEL);
208 job.Run(cp);
209
210 mi = cp.AddModelInstance();
211 GAMSParameter bmult = mi.SyncDB.AddParameter("bmult", "demand multiplier");
212 opt = ws.AddOptions();
213 opt.AllModelTypes = "cplex";
214 mi.Instantiate("transport use lp min z", opt, new GAMSModifier(bmult));
215
216 GAMSModelInstanceOpt MIO = new GAMSModelInstanceOpt(debug: true);
217
218 bmult.AddRecord().Value = 1.0;
219 mi.Solve(miOpt: MIO);
220
221 Assert.AreEqual(ModelStat.OptimalGlobal, mi.ModelStatus, "expect ModelStatus:OPTIMAL_GLOBAL");
222 Assert.AreEqual(SolveStat.Normal, mi.SolveStatus, "expect SolveStatus: NORMAL");
223
224 logger.Debug("exiting TestGAMSModelInstance | testSolveWhenDebugIsTrue");
225 }
226
227 [Test]
228 public void testModelInstanceOptDir()
229 {
230 string tmpDir;
231 bool optFileNotFound;
232
233 logger.Debug("entering TestGAMSModelInstance | testModelInstanceOptDir");
234
235 ws = new GAMSWorkspace(wsInfo);
236 cp = ws.AddCheckpoint();
237 job = ws.AddJobFromGamsLib("trnsport");
238 job.Run(cp);
239
240 mi = cp.AddModelInstance();
241 opt = ws.AddOptions();
242 opt.AllModelTypes = "cbc";
243 tmpDir = Path.GetTempPath();
244 opt.OptDir = tmpDir;
245 mi.Instantiate("transport use lp min z", opt);
246 GAMSModelInstanceOpt MIO = new GAMSModelInstanceOpt(optfile: 1);
247 using (TextWriter logFile = new StreamWriter("transport_cbc.log"))
248 mi.Solve(output:logFile, miOpt: MIO);
249 using (StreamReader sr = new StreamReader("transport_cbc.log"))
250 {
251 string contents = sr.ReadToEnd();
252 optFileNotFound = contents.Contains("*** Error Cannot open parameter file");
253 }
254 Assert.True(optFileNotFound, "Expected optfile not to be found");
255 Assert.AreEqual(mi.ModelStatus, ModelStat.OptimalGlobal, "Expected ModelStat.OptimalGlobal");
256 Assert.AreEqual(mi.SolveStatus, SolveStat.Normal, "Expected SolveStat.Normal");
257
258 using (File.Create(Path.Combine(tmpDir, "cbc.opt"))) {}
259 using (TextWriter logFile = new StreamWriter("transport_cbc.log"))
260 mi.Solve(output:logFile, miOpt: MIO);
261 using (StreamReader sr = new StreamReader("transport_cbc.log"))
262 {
263 string contents = sr.ReadToEnd();
264 optFileNotFound = contents.Contains("*** Error Cannot open parameter file");
265 }
266 Assert.False(optFileNotFound, "Expected optfile to be found");
267 Assert.AreEqual(mi.ModelStatus, ModelStat.OptimalGlobal, "Expected ModelStat.OptimalGlobal");
268 Assert.AreEqual(mi.SolveStatus, SolveStat.Normal, "Expected SolveStat.Normal");
269
270 logger.Debug("exiting TestGAMSModelInstance | testModelInstanceOptDir");
271 }
272
273 [Test]
274 public void testCallingInstantiateForSecondTime()
275 {
276 logger.Debug("entering TestGAMSModelInstance | testCallingInstantiateForSecondTime");
277
278 ws = new GAMSWorkspace(wsInfo);
279 cp = ws.AddCheckpoint();
280 job = ws.AddJobFromString(MODEL);
281 job.Run(cp);
282
283 mi = cp.AddModelInstance();
284 GAMSParameter bmult = mi.SyncDB.AddParameter("bmult", "demand multiplier");
285 opt = ws.AddOptions();
286 opt.AllModelTypes = "cplex";
287 mi.Instantiate("transport use lp min z", opt, new GAMSModifier(bmult));
288
289 GAMSParameter bmult2;
290 Assert.Throws<GAMSException>(() => bmult2 = mi.SyncDB.AddParameter("bmult", "demand multiplier"));
291 //mi.Instantiate("transport use lp min z", new GAMSModifier(bmult2));
292
293 logger.Debug("exiting TestGAMSModelInstance | testCallingInstantiateForSecondTime");
294 }
295
296 [Test]
297 public void testInstantiateWithNullModelDefinition()
298 {
299 logger.Debug("entering TestGAMSModelInstnace | testInstantiateWithNullModelDefinition");
300
301 ws = new GAMSWorkspace(wsInfo);
302 cp = ws.AddCheckpoint();
303 job = ws.AddJobFromString(MODEL);
304 job.Run(cp);
305
306 mi = cp.AddModelInstance();
307 GAMSParameter bmult = mi.SyncDB.AddParameter("bmult", "demand multiplier");
308 GAMSOptions opt = ws.AddOptions();
309 opt.AllModelTypes = "cplex";
310
311 Assert.Throws<GAMSException>(()=> mi.Instantiate(null, opt, new GAMSModifier(bmult)));
312
313 logger.Debug("exiting TestGAMSModelInstnace | testInstantiateWithNullModelDefinition");
314 }
315
316 [Test]
317 public void testInstantiateWithNullModifier1()
318 {
319 logger.Debug("entering TestGAMSModelInstance | testInstantiateWithNullModifier1");
320
321 ws = new GAMSWorkspace(wsInfo);
322 cp = ws.AddCheckpoint();
323 job = ws.AddJobFromString(MODEL);
324 job.Run(cp);
325
326 mi = cp.AddModelInstance();
327 GAMSOptions opt = ws.AddOptions();
328 opt.AllModelTypes = "cplex";
329
330 Assert.Throws<GAMSException>(()=> mi.Instantiate(null, opt, new GAMSModifier(null)));
331
332 logger.Debug("exiting TestGAMSModelInstance | testInstantiateWithNullModifier1");
333 }
334
335 [Test]
336 public void testInstantiateWithNullModifier2()
337 {
338 logger.Debug("entering TestGAMSModelInstance | testInstantiateWithNullModifier2");
339
340 ws = new GAMSWorkspace(wsInfo);
341 cp = ws.AddCheckpoint();
342 job = ws.AddJobFromString(MODEL);
343 job.Run(cp);
344
345 mi = cp.AddModelInstance();
346 GAMSOptions opt = ws.AddOptions();
347 opt.AllModelTypes = "cplex";
348
349 Assert.Throws<GAMSException>(()=> mi.Instantiate(null, opt, (GAMSModifier)null));
350
351 logger.Debug("exiting TestGAMSModelInstance | testInstantiateWithNullModifier2");
352 }
353 [Test]
354 public void testCopyModelInstanceBeforeInstantiated()
355 {
356 logger.Debug("entering TestGAMSModelInstance | testCopyModelInstanceBeforeInstantiated");
357
358 ws = new GAMSWorkspace(wsInfo);
359 cp = ws.AddCheckpoint();
360 job = ws.AddJobFromString(MODEL);
361 job.Run(cp);
362
363 mi = cp.AddModelInstance();
364
365 Assert.Throws<GAMSException>(()=> mi.CopyModelinstance());
366
367 logger.Debug("exiting TestGAMSModelInstance | testCopyModelInstanceBeforeInstantiated");
368 }
369 }
370}
GAMSModelInstance AddModelInstance(string modelInstanceName=null)
GAMSWorkspace WorkSpace
GAMSParameter GetParameter(string parameterIdentifier)
GAMSParameter AddParameter(string identifier, int dimension, string explanatoryText="")
GAMSDatabase OutDB
void Run(GAMSOptions gamsOptions=null, GAMSCheckpoint checkpoint=null, TextWriter output=null, Boolean createOutDB=true)
GAMSModelInstance CopyModelinstance(string modelInstanceName=null)
void Solve(SymbolUpdateType updateType=SymbolUpdateType.BaseCase, TextWriter output=null, GAMSModelInstanceOpt miOpt=null)
void Instantiate(string modelDefinition, params GAMSModifier[] modifiers)
new GAMSParameterRecord FirstRecord()
new GAMSParameterRecord AddRecord(params string[] keys)
GAMSJob AddJobFromString(string gamsSource, GAMSCheckpoint checkpoint=null, string jobName=null)
GAMSJob AddJobFromGamsLib(string model, GAMSCheckpoint checkpoint=null, string jobName=null)
GAMSCheckpoint AddCheckpoint(string checkpointName=null)
GAMSOptions AddOptions(GAMSOptions optFrom=null)
static void initializeTestFrom(String filename, String subdir)
initialize class properties from fileName and prepare directory subdir
Definition: HouseKeeper.cs:114