Loading...
Searching...
No Matches
clad.py
Go to the documentation of this file.
16
17from io import StringIO
18import os
19import sys
20from threading import Thread
21from gams import GamsWorkspace, SolveLink
22
23if __name__ == "__main__":
24 sys_dir = sys.argv[1] if len(sys.argv) > 1 else None
25 ws = GamsWorkspace(system_directory=sys_dir)
26
27 # use model "clad" from the GAMS Model Library
28 ws.gamslib("clad")
29 job = ws.add_job_from_file("clad")
30
31 # define an option file for the solver to be used
32 with open(os.path.join(ws.working_directory, "cplex.opt"), "w") as f:
33 f.write("epgap 0\n") # set relative stopping tolerance to 0 initially
34 f.write("interactive 1\n") # activate interactive option setting on interrupt
35 f.write("iafile cplex.op2\n") # define new option file to read on interrupt
36
37 opt = ws.add_options()
38 opt.mip = "cplex"
39 opt.optfile = 1
40 opt.solvelink = SolveLink.LoadLibrary
41
42 # run GamsJob in separate thread
43 sw = StringIO()
44 thread = Thread(target=job.run, args=(opt,), kwargs={"output": sw})
45 thread.start()
46
47 # define list of increasing stopping tolerances
48 steps = [(5.0, "epgap 0.1"), (10.0, "epgap 0.2"), (20.0, "epagap 1e9")]
49
50 total_time = 0.0
51 for s in steps:
52 # wait a while and check if job is still running
53 thread.join(s[0] - total_time)
54 if not thread.is_alive():
55 break
56 total_time = s[0]
57 # write new Cplex option file
58 with open(os.path.join(ws.working_directory, "cplex.op2"), "w") as f:
59 f.write(s[1])
60 # interrupt job to read new Cplex option file
61 job.interrupt()
62 print("Interrupted Cplex to continue with new option: " + s[1])
63
64 # if job is still running, wait until it is finished
65 if thread.is_alive():
66 thread.join()
67 # check if we did interrupt the solver at least once
68 log = sw.getvalue()
69 if not "Interrupted..." in log:
70 raise Exception("Expected the solver to be interrupted at least once.")