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 opt.threads = 1
42
43 # run GamsJob in separate thread
44 sw = StringIO()
45 thread = Thread(target=job.run, args=(opt,), kwargs={"output": sw})
46 thread.start()
47
48 # define list of increasing stopping tolerances
49 steps = [(5.0, "epgap 0.1"), (10.0, "epgap 0.2"), (20.0, "epagap 1e9")]
50
51 total_time = 0.0
52 for s in steps:
53 # wait a while and check if job is still running
54 thread.join(s[0] - total_time)
55 if not thread.is_alive():
56 break
57 total_time = s[0]
58 # write new Cplex option file
59 with open(os.path.join(ws.working_directory, "cplex.op2"), "w") as f:
60 f.write(s[1])
61 # interrupt job to read new Cplex option file
62 job.interrupt()
63 print("Interrupted Cplex to continue with new option: " + s[1])
64
65 # if job is still running, wait until it is finished
66 if thread.is_alive():
67 thread.join()
68 # check if we did interrupt the solver at least once
69 log = sw.getvalue()
70 if not "Interrupted..." in log:
71 raise Exception("Expected the solver to be interrupted at least once.")