source: coopr.pyomo/stable/coopr/pyomo/tests/unit/test_model.py @ 3285

Last change on this file since 3285 was 3285, checked in by wehart, 10 years ago

Merged revisions 3184-3284 via svnmerge from
https://software.sandia.gov/svn/public/coopr/coopr.pyomo/trunk

........

r3188 | jwatson | 2010-10-29 08:09:35 -0600 (Fri, 29 Oct 2010) | 3 lines


Eliminating initial domain check when constructing numeric constants and the default domain (Reals) is specified.

........

r3203 | jwatson | 2010-10-29 14:46:18 -0600 (Fri, 29 Oct 2010) | 3 lines


Fixing bugs in has_discrete_variables() method of PyomoModel?.

........

r3211 | jdsiiro | 2010-11-01 14:49:11 -0600 (Mon, 01 Nov 2010) | 4 lines


bugfixes for Blocks:

  • avoid infinite loop when adding a block to a model
  • support pretty printing of user-defined components

........

r3212 | jdsiiro | 2010-11-02 15:17:13 -0600 (Tue, 02 Nov 2010) | 5 lines


  • cleaning up the management of Block._parent_block and Component.model attributes. Adding & removing blocks now updates the model attribute on all children
  • renaming Block._setattr_exec -> Block._add_component

........

r3213 | jdsiiro | 2010-11-03 10:47:06 -0600 (Wed, 03 Nov 2010) | 2 lines


Bugfix to the PyomoLogHandler? for python 2.4 compatibility

........

r3214 | jdsiiro | 2010-11-03 15:20:47 -0600 (Wed, 03 Nov 2010) | 3 lines


There is no point logging a warning when the problem is encountered
generating a logging.info message: log the warning at the info level.

........

r3215 | wehart | 2010-11-04 23:05:17 -0600 (Thu, 04 Nov 2010) | 3 lines


Adding a simple knapsack example to illustrate the difference between
a concrete and abstract model.

........

r3216 | jwatson | 2010-11-05 09:39:19 -0600 (Fri, 05 Nov 2010) | 3 lines


Fixing error diagnostic when indexing a variable with a bad index.

........

r3219 | jwatson | 2010-11-05 16:01:23 -0600 (Fri, 05 Nov 2010) | 3 lines


Supressing a validation test with NumericConstant?. If the user specifies a value, we are (now) assuming it is actually a numeric value - otherwise, the domain check significantly inflates the run-time associated with expression tree creation. This needs to be revisited in the Coopr 2.5 re-write.

........

r3226 | wehart | 2010-11-06 21:32:59 -0600 (Sat, 06 Nov 2010) | 2 lines


Setting up example, which was never converted.

........

r3233 | wehart | 2010-11-12 15:56:28 -0700 (Fri, 12 Nov 2010) | 4 lines


Migrating OS-specific functionality into coopr.os


Adding coopr.os to the dev.ini config file.

........

r3242 | wehart | 2010-11-13 01:28:57 -0700 (Sat, 13 Nov 2010) | 4 lines


Type fix.


Updating error message.

........

r3244 | wehart | 2010-11-13 10:44:26 -0700 (Sat, 13 Nov 2010) | 2 lines


Skipping OSiL writer when not defined.

........

r3246 | wehart | 2010-11-13 10:54:15 -0700 (Sat, 13 Nov 2010) | 2 lines


bug fix.

........

r3247 | wehart | 2010-11-13 11:14:01 -0700 (Sat, 13 Nov 2010) | 2 lines


Bug fix.

........

r3248 | jwatson | 2010-11-17 13:51:47 -0700 (Wed, 17 Nov 2010) | 3 lines


Interim fixes to output of quadratic terms in LP writer - more to do, but at least the basic examples now work.

........

r3254 | jwatson | 2010-11-19 13:19:19 -0700 (Fri, 19 Nov 2010) | 3 lines


Fixed bug in LP writer involving quadratic terms involving two distinct variables. Added two new quadratic examples.

........

r3257 | jwatson | 2010-11-19 13:59:35 -0700 (Fri, 19 Nov 2010) | 3 lines


Fixing diagnostic error message when attempting to solve quadratic programs with GLPK - code for generating message was not syntatically legal.

........

r3268 | jwatson | 2010-12-01 15:08:28 -0700 (Wed, 01 Dec 2010) | 3 lines


Fixing issues with the Piecewise construct when breakpoints and slopes are generated via rules. Works now (on a sample of size 1 - the newly added example5.py) for non-indexed rules, likely broken for indexed breakpoint/slope rules.

........

r3272 | jwatson | 2010-12-02 13:53:51 -0700 (Thu, 02 Dec 2010) | 3 lines


Adding omitted pprint() method for SOS constraints - identified while debugging a piecewise issue.

........

r3274 | jwatson | 2010-12-02 16:32:29 -0700 (Thu, 02 Dec 2010) | 3 lines


Adding example of Piecewise construct using breakpoint and slope rules, as opposed to explicit/direct lists.

........

r3276 | jwatson | 2010-12-03 14:06:40 -0700 (Fri, 03 Dec 2010) | 3 lines


Some progress toward functional indexed Piecewise components.

........

File size: 9.5 KB
Line 
1#
2# Unit Tests for Elements of a Model
3#
4# Test             Class to test the Model class
5#
6
7import os
8import sys
9from os.path import abspath, dirname
10sys.path.insert(0, dirname(dirname(abspath(__file__)))+os.sep+".."+os.sep+"..")
11currdir = dirname(abspath(__file__))+os.sep
12
13from coopr.pyomo.base import IntegerSet
14from coopr.pyomo import *
15from coopr.opt import *
16from coopr.pyomo.base.var import _VarElement
17import pyutilib.th as unittest
18import pyutilib.services
19
20class PyomoModel(unittest.TestCase):
21
22    def setUp(self):
23        self.model = Model()
24
25    def construct(self,filename):
26        self.instance = self.model.create(filename)
27
28
29class Test(PyomoModel):
30
31    def setUp(self):
32        #
33        # Create Model
34        #
35        PyomoModel.setUp(self)
36
37    def tearDown(self):
38        if os.path.exists("unknown.lp"):
39           os.unlink("unknown.lp")
40        pyutilib.services.TempfileManager.clear_tempfiles()
41
42    def test_clear_attribute(self):
43        """ Coverage of the _clear_attribute method """
44        self.model.A = Set()
45        self.failUnlessEqual(self.model.A.name,"A")
46        self.model.A = Var()
47        self.failUnlessEqual(self.model.A.name,"A")
48        self.model.A = Param()
49        self.failUnlessEqual(self.model.A.name,"A")
50        self.model.A = Objective()
51        self.failUnlessEqual(self.model.A.name,"A")
52        self.model.A = Constraint()
53        self.failUnlessEqual(self.model.A.name,"A")
54        self.model.A = Set()
55        self.failUnlessEqual(self.model.A.name,"A")
56
57    def test_set_attr(self):
58        self.model.x = Param()
59        self.model.x = None
60
61    def test_write(self):
62        self.model.A = RangeSet(1,4)
63        self.model.x = Var(self.model.A, bounds=(-1,1))
64        def obj_rule(model):
65            return summation(model.x)
66        self.model.obj = Objective(rule=obj_rule)
67        self.instance = self.model.create()
68        self.instance.write()
69
70    def test_write2(self):
71        self.model.A = RangeSet(1,4)
72        self.model.x = Var(self.model.A, bounds=(-1,1))
73        def obj_rule(model):
74            return summation(model.x)
75        self.model.obj = Objective(rule=obj_rule)
76        def c_rule(model):
77            return (1, model.x[1]+model.x[2], 2)
78        self.model.c = Constraint(rule=c_rule)
79        self.instance = self.model.create()
80        self.instance.write()
81
82    def test_write3(self):
83        """Test that the summation works correctly, even though param 'w' has a default value"""
84        self.model.J = RangeSet(1,4)
85        self.model.w=Param(self.model.J, default=4)
86        self.model.x=Var(self.model.J)
87        def obj_rule(instance):
88            return summation(instance.x, instance.w)
89        self.model.obj = Objective(rule=obj_rule)
90        self.instance = self.model.create()
91        self.failUnlessEqual(self.instance.obj[None].expr._nargs, 4)
92
93    def test_write_osil1 ( self ):
94        if not 'osil' in coopr.opt.WriterFactory().services():
95            self.skipTest('No OSiL writer is available.')
96        base = '%s/test_write_osil1' % currdir
97        fout, fbase = (base + '.out', base + '.txt')
98
99        self.model.A = RangeSet(1, 4)
100        self.model.x = Var( self.model.A, bounds=(-1,1) )
101        def obj_rule ( model ):
102            return summation( model.x )
103        self.model.obj = Objective( rule=obj_rule )
104        self.instance = self.model.create()
105        self.instance.write(
106            format=ProblemFormat.osil,
107            filename=fout
108        )
109        self.failUnlessFileEqualsBaseline( fout, fbase )
110
111    def test_solve1(self):
112        if not pyutilib.services.registered_executable("glpsol"):
113            return
114        self.model.A = RangeSet(1,4)
115        self.model.x = Var(self.model.A, bounds=(-1,1))
116        def obj_rule(model):
117            return summation(model.x)
118        self.model.obj = Objective(rule=obj_rule)
119        def c_rule(model):
120            expr = 0
121            for i in model.A:
122                expr += i*model.x[i]
123            return expr == 0
124        self.model.c = Constraint(rule=c_rule)
125        self.instance = self.model.create()
126        #self.instance.pprint()
127        opt = SolverFactory('glpk')
128        solutions = opt.solve(self.instance, keepFiles=True)
129        self.instance.load(solutions)
130        self.instance.display(currdir+"solve1.out")
131        self.failUnlessFileEqualsBaseline(currdir+"solve1.out",currdir+"solve1.txt")
132        #
133        def d_rule(model):
134            return model.x[1] > 0
135        self.model.d = Constraint(rule=d_rule)
136        self.model.d.deactivate()
137        self.instance = self.model.create()
138        solutions = opt.solve(self.instance, keepFiles=True)
139        self.instance.load(solutions)
140        self.instance.display(currdir+"solve1.out")
141        self.failUnlessFileEqualsBaseline(currdir+"solve1.out",currdir+"solve1.txt")
142        #
143        self.model.d.activate()
144        self.instance = self.model.create()
145        solutions = opt.solve(self.instance, keepFiles=True)
146        self.instance.load(solutions)
147        self.instance.display(currdir+"solve1.out")
148        self.failUnlessFileEqualsBaseline(currdir+"solve1.out",currdir+"solve1a.txt")
149        #
150        self.model.d.deactivate()
151        def e_rule(i, model):
152            return model.x[i] > 0
153        self.model.e = Constraint(self.model.A, rule=e_rule)
154        self.instance = self.model.create()
155        for i in self.instance.A:
156            self.instance.e[i].deactivate()
157        solutions = opt.solve(self.instance, keepFiles=True)
158        self.instance.load(solutions)
159        self.instance.display(currdir+"solve1.out")
160        self.failUnlessFileEqualsBaseline(currdir+"solve1.out",currdir+"solve1b.txt")
161
162    def test_load1(self):
163        """Testing loading of vector solutions"""
164        self.model.A = RangeSet(1,4)
165        self.model.x = Var(self.model.A, bounds=(-1,1))
166        def obj_rule(model):
167            return summation(model.x)
168        self.model.obj = Objective(rule=obj_rule)
169        def c_rule(model):
170            expr = 0
171            for i in model.A:
172                expr += i*model.x[i]
173            return expr == 0
174        self.model.c = Constraint(rule=c_rule)
175        self.instance = self.model.create()
176        ans = [0.75]*4
177        self.instance.load(ans)
178        self.instance.display(currdir+"solve1.out")
179        self.failUnlessFileEqualsBaseline(currdir+"solve1.out",currdir+"solve1c.txt")
180
181    def Xtest_solve2(self):
182        """
183        WEH - this is disabled because glpk appears to work fine
184        on this example.  I'm not quite sure what has changed that has
185        impacted this test...
186        """
187        if not pyutilib.services.registered_executable("glpsol"):
188            return
189        self.model.A = RangeSet(1,4)
190        self.model.x = Var(self.model.A, bounds=(-1,1))
191        def obj_rule(model):
192          expr = 0
193          for i in model.A:
194            expr += model.x[i]
195          return expr
196        self.model.obj = Objective(rule=obj_rule)
197        self.instance = self.model.create()
198        #self.instance.pprint()
199        opt = solvers.GLPK(keepFiles=True)
200        solutions = opt.solve(self.instance)
201        solutions.write()
202        sys.exit(1)
203        try:
204            self.instance.load(solutions)
205            self.fail("Cannot load a solution with a bad solver status")
206        except ValueError:
207            pass
208
209    def test_solve3(self):
210        self.model.A = RangeSet(1,4)
211        self.model.x = Var(self.model.A, bounds=(-1,1))
212        def obj_rule(model):
213          expr = 0
214          for i in model.A:
215            expr += model.x[i]
216          return expr
217        self.model.obj = Objective(rule=obj_rule)
218        self.instance = self.model.create()
219        self.instance.display(currdir+"solve3.out")
220        self.failUnlessFileEqualsBaseline(currdir+"solve3.out",currdir+"solve3.txt")
221
222    def test_solve4(self):
223        if not pyutilib.services.registered_executable("glpsol"):
224            return
225        self.model.A = RangeSet(1,4)
226        self.model.x = Var(self.model.A, bounds=(-1,1))
227        def obj_rule(model):
228            return summation(model.x)
229        self.model.obj = Objective(rule=obj_rule)
230        def c_rule(model):
231          expr = 0
232          for i in model.A:
233            expr += i*model.x[i]
234          return expr == 0
235        self.model.c = Constraint(rule=c_rule)
236        self.instance = self.model.create()
237        #self.instance.pprint()
238        opt = SolverFactory('glpk', keepFiles=True)
239        solutions = opt.solve(self.instance)
240        self.instance.load(solutions.solution(0))
241        self.instance.display(currdir+"solve1.out")
242        self.failUnlessFileEqualsBaseline(currdir+"solve1.out",currdir+"solve1.txt")
243
244    def Xtest_solve5(self):
245        """ A draft test for the option to select an objective """
246        if not pyutilib.services.registered_executable("glpsol"):
247            return
248        self.model.A = RangeSet(1,4)
249        self.model.x = Var(self.model.A, bounds=(-1,1))
250        def obj1_rule(model):
251          expr = 0
252          for i in model.A:
253            expr += model.x[i]
254          return expr
255        self.model.obj1 = Objective(rule=obj1_rule)
256        def obj2_rule(model):
257          expr = 0
258          tmp=-1
259          for i in model.A:
260            expr += tmp*i*model.x[i]
261            tmp *= -1
262          return expr
263        self.model.obj2 = Objective(rule=obj2_rule)
264        self.instance = self.model.create()
265        opt = SolverFactory('glpk', keepfiles=True)
266        solutions = opt.solve(self.instance, objective='obj2')
267        self.instance.load(solutions.solution())
268        self.instance.display(currdir+"solve5.out")
269        self.failUnlessFileEqualsBaseline(currdir+"solve5.out",currdir+"solve5a.txt")
270
271if __name__ == "__main__":
272   unittest.main()
273
Note: See TracBrowser for help on using the repository browser.