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