Skip to content

Commit

Permalink
Merge pull request #1838 from mrmundt/pyutilib-misc
Browse files Browse the repository at this point in the history
Move Container/Options/Bunch into just Bunch
  • Loading branch information
mrmundt authored Feb 26, 2021
2 parents 3d99136 + e4bcb33 commit 9c48afa
Show file tree
Hide file tree
Showing 53 changed files with 339 additions and 145 deletions.
4 changes: 2 additions & 2 deletions examples/doc/pyomobook/attic/scripts/alltogether.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import pyomo.environ
from pyomo.opt import SolverFactory
from pyomo.common.collections import Options
from pyomo.common.collections import Bunch

import sys
import math
Expand Down Expand Up @@ -39,7 +39,7 @@
instance=model.create()

SolverName = "asl"
so = Options()
so = Bunch()
so.solver = "ipopt"
opt=SolverFactory(SolverName, options=so)

Expand Down
4 changes: 2 additions & 2 deletions examples/doc/pyomobook/attic/scripts/indexnonlinscript.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import sys
import pyomo.environ
from pyomo.opt import SolverFactory
from pyomo.common.collections import Options
from pyomo.common.collections import Bunch

from indexnonlin import model

Expand All @@ -12,7 +12,7 @@
instance=model.create()

SolverName = "asl"
so = Options()
so = Bunch()
so.solver = "ipopt"
opt=SolverFactory(SolverName, options=so)

Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
# Mimic the pyomo script
from pyomo.core import *
from pyomo.common.collections import Options
from pyomo.common.collections import Bunch

# set high level options that mimic pyomo comand line
options = Options()
options = Bunch()
options.model_file = 'DiseaseEstimation.py'
options.data_files = ['DiseaseEstimation.dat']
options.solver = 'ipopt'
Expand Down
4 changes: 2 additions & 2 deletions examples/doc/pyomobook/attic/scripts/nonlinscript.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import sys
import pyomo.environ
from pyomo.opt import SolverFactory
from pyomo.common.collections import Options
from pyomo.common.collections import Bunch

from nonlin import model

Expand All @@ -12,7 +12,7 @@
instance=model.create()

SolverName = "asl"
so = Options()
so = Bunch()
so.solver = "ipopt"
opt=SolverFactory(SolverName, options=so)

Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# nonlinear_ReactorDesignTable.py
from pyomo.environ import *
from pyomo.common.collections import Options
from pyomo.common.collections import Bunch

# create the concrete model
model = ConcreteModel()
Expand Down Expand Up @@ -36,7 +36,7 @@
+ k3 * model.ca ** 2.0))

# setup the solver options
options = Options()
options = Bunch()
options.solver = 'ipopt'
options.quiet = True

Expand Down
4 changes: 2 additions & 2 deletions examples/doc/samples/pyomo_book/scripts_mimicPyomo.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
# Mimic the pyomo script
from pyomo.environ import *
from pyomo.common.collections import Options
from pyomo.common.collections import Bunch

# set high level options that mimic pyomo comand line
options = Options()
options = Bunch()
options.model_file = 'DiseaseEstimation.py'
options.data_files = ['DiseaseEstimation.dat']
options.solver = 'ipopt'
Expand Down
12 changes: 6 additions & 6 deletions examples/pyomo/callbacks/sc.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
# This software is distributed under the 3-clause BSD License.
# ___________________________________________________________________________

from pyomo.common.collections import Options
from pyomo.common.collections import Bunch
from pyomo.core import *
import math
import random
Expand Down Expand Up @@ -45,7 +45,7 @@ def print_model_stats(options,model):

def pyomo_create_model(options=None, model_options=None):
if model_options is None:
model_options = Options()
model_options = Bunch()
if model_options.type is None:
model_options.type = 'fixed_set_size'
#
Expand Down Expand Up @@ -185,24 +185,24 @@ def test_model(options=None):
if __name__ == '__main__':
test_model()
#
options = Options()
options = Bunch()
options.type = 'fixed_set_size'
options.m = 11
options.n = 21
options.rho = 0.3
test_model(options)
#
options = Options()
options = Bunch()
options.type = 'fixed_element_coverage'
test_model(options)
#
options = Options()
options = Bunch()
options.m = 100
options.n = 200
options.type = 'fixed_probability'
test_model(options)
#
options = Options()
options = Bunch()
options.type = 'fixed_element_coverage'
options.m = 10
options.n = 100
Expand Down
3 changes: 1 addition & 2 deletions pyomo/bilevel/plugins/lcp.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
# This software is distributed under the 3-clause BSD License.
# ___________________________________________________________________________

import six
import logging

from pyomo.core.base import Block, VarList, ConstraintList, Objective, Var, Constraint, maximize, ComponentUID, Set, TransformationFactory
Expand Down Expand Up @@ -287,7 +286,7 @@ def _add_optimality_conditions(self, instance, submodel):
exp -= B2_[uid] * lb_dual
if not ub_dual is None:
exp += B2_[uid] * ub_dual
if type(exp) in six.integer_types or type(exp) is float:
if type(exp) in [int, float]:
# TODO: Annotate the model as unbounded
raise IOError("Unbounded variable without side constraints")
else:
Expand Down
5 changes: 2 additions & 3 deletions pyomo/bilevel/tests/test_blp.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,10 +26,9 @@
from pyomo.scripting.util import cleanup
from pyomo.environ import TransformationFactory

from six import iteritems

solvers = pyomo.opt.check_available_solvers('cplex', 'glpk', 'ipopt')


class CommonTests:

solve = True
Expand Down Expand Up @@ -148,7 +147,7 @@ def check(self, problem, solver):
self.assertEqual(len(refObj), len(ansObj))
for i in range(len(refObj)):
self.assertEqual(len(refObj[i]), len(ansObj[i]))
for key,val in iteritems(refObj[i]):
for key,val in refObj[i].items():
#self.assertEqual(val['Id'], ansObj[i].get(key,None)['Id'])
self.assertAlmostEqual(val['Value'], ansObj[i].get(key,None)['Value'], places=3)

Expand Down
4 changes: 1 addition & 3 deletions pyomo/bilevel/tests/test_linear_dual.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,6 @@
from pyomo.scripting.util import cleanup
import pyomo.environ

from six import iteritems

solvers = pyomo.opt.check_available_solvers('cplex', 'glpk')


Expand Down Expand Up @@ -154,7 +152,7 @@ def check(self, problem, solver):
self.assertEqual(len(refObj), len(ansObj))
for i in range(len(refObj)):
self.assertEqual(len(refObj[i]), len(ansObj[i]))
for key,val in iteritems(refObj[i]):
for key,val in refObj[i].items():
#self.assertEqual(val['Id'], ansObj[i].get(key,None)['Id'])
self.assertAlmostEqual(val['Value'], ansObj[i].get(key,None)['Value'], places=3)

Expand Down
3 changes: 1 addition & 2 deletions pyomo/common/collections/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,5 +23,4 @@
from .orderedset import OrderedDict, OrderedSet
from .component_map import ComponentMap
from .component_set import ComponentSet

from pyutilib.misc import Bunch, Container, Options
from .bunch import Bunch
121 changes: 121 additions & 0 deletions pyomo/common/collections/bunch.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
# ___________________________________________________________________________
#
# Pyomo: Python Optimization Modeling Objects
# Copyright 2017 National Technology and Engineering Solutions of Sandia, LLC
# Under the terms of Contract DE-NA0003525 with National Technology and
# Engineering Solutions of Sandia, LLC, the U.S. Government retains certain
# rights in this software.
# This software is distributed under the 3-clause BSD License.
# ___________________________________________________________________________
#
# This module was originally developed as part of the PyUtilib project
# Copyright (c) 2008 Sandia Corporation.
# This software is distributed under the BSD License.
# Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
# the U.S. Government retains certain rights in this software.
# ___________________________________________________________________________

import shlex


class Bunch(dict):
"""
A class that can be used to store a bunch of data dynamically.
This class allows all other attributes to have a default value of None.
This borrows the output formatting ideas from the
ActiveState Code Container (recipe 496697).
"""

def __init__(self, *args, **kw):
for arg in args:
for item in shlex.split(arg):
r = item.find('=')
if r != -1:
try:
val = eval(item[r + 1:])
except:
val = item[r + 1:]
kw[item[:r]] = val
dict.__init__(self, kw)
self.__dict__.update(kw)
if not '_name_' in kw:
self._name_ = self.__class__.__name__

def update(self, d):
"""
The update is specialized for JSON-like data. This
recursively replaces dictionaries with Container objects.
"""
for k in d:
if type(d[k]) is dict:
tmp = Bunch()
tmp.update(d[k])
self.__setattr__(k, tmp)
elif type(d[k]) is list:
val = []
for i in d[k]:
if type(i) is dict:
tmp = Bunch()
tmp.update(i)
val.append(tmp)
else:
val.append(i)
self.__setattr__(k, val)
else:
self.__setattr__(k, d[k])

def set_name(self, name):
self._name_ = name

def __setitem__(self, name, val):
self.__setattr__(name, val)

def __getitem__(self, name):
return self.__getattr__(name)

def __setattr__(self, name, val):
if name[0] != '_':
dict.__setitem__(self, name, val)
self.__dict__[name] = val

def __getattr__(self, name):
try:
return dict.__getitem__(self, name)
except:
if name[0] == '_':
raise AttributeError("Unknown attribute %s" % name)
return None

def __repr__(self):
attrs = sorted("%s = %r" % (k, v) for k, v in self.__dict__.items()
if not k.startswith("_"))
return "%s(%s)" % (self.__class__.__name__, ", ".join(attrs))

def __str__(self):
return self.as_string()

def __str__(self, nesting=0, indent=''):
attrs = []
indentation = indent + " " * nesting
for k, v in self.__dict__.items():
if not k.startswith("_"):
text = [indentation, k, ":"]
if isinstance(v, Bunch):
if len(v) > 0:
text.append('\n')
text.append(v.__str__(nesting + 1))
elif isinstance(v, list):
if len(v) == 0:
text.append(' []')
else:
for v_ in v:
text.append('\n' + indentation + "-")
if isinstance(v_, Bunch):
text.append('\n' + v_.__str__(nesting + 1))
else:
text.append(" " + repr(v_))
else:
text.append(' ' + repr(v))
attrs.append("".join(text))
attrs.sort()
return "\n".join(attrs)
Loading

0 comments on commit 9c48afa

Please sign in to comment.