source: pyomo/trunk/pyomo/bilevel/tests/test_linear_dual.py @ 9463

Last change on this file since 9463 was 9463, checked in by wehart, 4 years ago

Refactoring code to make it easier to enable debugging

File size: 5.6 KB
Line 
1#  _________________________________________________________________________
2#
3#  Pyomo: Python Optimization Modeling Objects
4#  Copyright (c) 2008 Sandia Corporation.
5#  This software is distributed under the BSD License.
6#  Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
7#  the U.S. Government retains certain rights in this software.
8#  For more information, see the FAST README.txt file.
9#  _________________________________________________________________________
10
11#
12# Test transformations for linear duality
13#
14
15#try:
16#    import new
17#except:
18#    import types as new
19import os
20import sys
21import unittest
22from os.path import abspath, dirname, normpath, join
23
24currdir = dirname(abspath(__file__))
25exdir = normpath(join(currdir,'..','..','..','examples','bilevel'))
26
27from six import iteritems
28import re
29import pyutilib.services
30import pyutilib.subprocess
31import pyutilib.common
32import pyutilib.th as unittest
33from pyutilib.misc import setup_redirect, reset_redirect
34try:
35    import yaml
36    yaml_available=True
37except ImportError:
38    yaml_available=False
39
40from pyomo.environ import *
41import pyomo.opt
42import pyomo.scripting.pyomo_command as pyomo_main
43from pyomo.bilevel.plugins.driver import bilevel_exec
44from pyomo.scripting.util import cleanup
45from pyomo.util.plugin import ExtensionPoint
46
47solver = pyomo.opt.load_solvers('cplex', 'glpk')
48
49
50class CommonTests:
51
52    def run_bilevel(self, *_args, **kwds):
53        args = []
54        args.append('-c')
55        pproc = None
56        if 'solver' in kwds:
57            _solver = kwds.get('solver','glpk')
58            args.append('--solver=bilevel_ld')
59            args.append('--solver-options="solver=%s"' % _solver)
60        elif 'preprocess' in kwds:
61            pp = kwds['preprocess']
62            if pp == 'linear_dual':
63                import pyomo.bilevel.linear_dual
64                pproc = pyomo.bilevel.linear_dual.transform
65        args.append('--symbolic-solver-labels')
66        args.append('--save-results=result.yml')
67        args.append('--file-determinism=2')
68
69        if False:
70            args.append('--stream-solver')
71            args.append('--tempdir='+currdir)
72            args.append('--keepfiles')
73            args.append('--debug')
74            args.append('--verbose')
75
76        args = args + list(_args)
77        os.chdir(currdir)
78
79        print('***')
80        if pproc:
81            pproc.activate()
82            print("Activating " + kwds['preprocess'])
83        #print(' '.join(args))
84        try:
85            if pproc:
86                output = pyomo_main.run(args)
87            else:
88                output = bilevel_exec(args)
89        except:
90            output = None
91        cleanup()
92        if pproc:
93            pproc.deactivate()
94        print('***')
95        return output
96
97    def check(self, problem, solver):
98        pass
99
100    def referenceFile(self, problem, solver):
101        return join(currdir, problem+'.txt')
102
103    def getObjective(self, fname):
104        FILE = open(fname)
105        data = yaml.load(FILE)
106        FILE.close()
107        solutions = data.get('Solution', [])
108        ans = []
109        for x in solutions:
110            ans.append(x.get('Objective', {}))
111        return ans
112
113    def updateDocStrings(self):
114        for key in dir(self):
115            if key.startswith('test'):
116                getattr(self,key).__doc__ = " (%s)" % getattr(self,key).__name__
117
118    def test_t5(self):
119        self.problem='test_t5'
120        self.run_bilevel( join(exdir,'t5.py'))
121        self.check( 't5', 'linear_dual' )
122
123    def test_t1(self):
124        self.problem='test_t1'
125        self.run_bilevel( join(exdir,'t1.py'))
126        self.check( 't1', 'linear_dual' )
127
128    def Xtest_t2(self):
129        self.problem='test_t2'
130        self.run_bilevel( join(exdir,'t2.py'))
131        self.check( 't2', 'linear_dual' )
132
133
134class Reformulate(unittest.TestCase, CommonTests):
135
136    def run_bilevel(self,  *args, **kwds):
137        args = list(args)
138        args.append('--save-model='+self.problem+'_result.lp')
139        args.append('--instance-only')
140        kwds['preprocess'] = 'linear_dual'
141        CommonTests.run_bilevel(self, *args, **kwds)
142
143    def referenceFile(self, problem, solver):
144        return join(currdir, problem+"_"+solver+'.lp')
145
146    def check(self, problem, solver):
147        self.assertFileEqualsBaseline( join(currdir,self.problem+'_result.lp'),
148                                           self.referenceFile(problem,solver), tolerance=1e-5 )
149
150
151class Solver(unittest.TestCase):
152
153    def check(self, problem, solver):
154        refObj = self.getObjective(self.referenceFile(problem,solver))
155        ansObj = self.getObjective(join(currdir,'result.yml'))
156        self.assertEqual(len(refObj), len(ansObj))
157        for i in range(len(refObj)):
158            self.assertEqual(len(refObj[i]), len(ansObj[i]))
159            for key,val in iteritems(refObj[i]):
160                self.assertEqual(val['Id'], ansObj[i].get(key,None)['Id'])
161                self.assertAlmostEqual(val['Value'], ansObj[i].get(key,None)['Value'], places=3)
162
163
164@unittest.skipIf(not yaml_available, "YAML is not available")
165@unittest.skipIf(solver['glpk'] is None, "The 'glpk' executable is not available")
166class Solve_GLPK(Solver, CommonTests):
167
168    def run_bilevel(self,  *args, **kwds):
169        kwds['solver'] = 'glpk'
170        CommonTests.run_bilevel(self, *args, **kwds)
171
172
173@unittest.skipIf(not yaml_available, "YAML is not available")
174@unittest.skipIf(solver['cplex'] is None, "The 'cplex' executable is not available")
175class Solve_CPLEX(Solver, CommonTests):
176
177    def run_bilevel(self,  *args, **kwds):
178        kwds['solver'] = 'cplex'
179        CommonTests.run_bilevel(self, *args, **kwds)
180
181
182if __name__ == "__main__":
183    unittest.main()
Note: See TracBrowser for help on using the repository browser.