clad.py
Go to the documentation of this file.
17
18from __future__ import print_function
19from gams import *
20import sys
21import os
22from threading import Thread
23try:
24 from StringIO import StringIO
25except ImportError:
26 from io import StringIO
27
28if __name__ == "__main__":
29 if len(sys.argv) > 1:
30 ws = GamsWorkspace(system_directory = sys.argv[1])
31 else:
32 ws = GamsWorkspace()
33
34 # Use the GAMS Model Library model "clad" as an example
35
36 ws.gamslib("clad")
37 j1 = ws.add_job_from_file("clad")
38
39 # Define an option file for the solver to be used
40 f = open(os.path.join(ws.working_directory, "cplex.opt"), "w")
41 # Set relative stopping tolerance to 0 initially
42 f.write("epgap 0")
43 # Activate interactive option setting on interrupt
44 f.write("interactive 1\n")
45 # Define new option file to read on interrupt
46 f.write("iafile cplex.op2")
47 f.close()
48
49 opt = ws.add_options()
50 opt.mip = "cplex"
51 opt.optfile = 1
52 opt.solvelink = SolveLink.LoadLibrary
53
54 sw = StringIO()
55
56 # Run GamsJob j1 in separate thread
57 opt_thread = Thread(target=j1.run, args=(opt,), kwargs={"output":sw})
58 opt_thread.start()
59
60 # Define list of increasing stopping tolerances
61 steps = [(5.0, "epgap 0.1"),
62 (10.0, "epgap 0.2"),
63 (20.0, "epagap 1e9")]
64
65 prev_step = 0.0
66 for s in steps:
67 # Wait a while and check if j1 is still running
68 opt_thread.join(s[0] - prev_step)
69 if not opt_thread.is_alive():
70 break
71 prev_step = s[0]
72 # Write new Cplex option file
73 f = open(os.path.join(ws.working_directory, "cplex.op2"), "w")
74 f.write(s[1])
75 f.close()
76 # Interrupt j1 to read new Cplex option file
77 j1.interrupt()
78 print("Interrupted Cplex to continue with new option: " + s[1])
79 # If j1 is still running, wait until it is finished
80 if opt_thread.is_alive:
81 opt_thread.join()
82 # Check if everything worked as expected
83 log = sw.getvalue()
84 if not "MIP status(113): aborted" in log:
85 raise Exception("Expected the solver to be interrupted at least once.")