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