本文整理汇总了Python中pyutilib.misc.Options类的典型用法代码示例。如果您正苦于以下问题:Python Options类的具体用法?Python Options怎么用?Python Options使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Options类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_solvers
def test_solvers(options=None, argv=None):
"""
The is the function executed by the command
pyomo test-solvers [solver ...]
"""
global rootdir
rootdir = os.getcwd()
if argv is None:
if options.debug:
if len(options.solver) == 0:
print("Testing all solvers")
else:
print("Testing solver", options.solver[0])
# Over-ride the value of sys.argv, which is used by unittest.main()
sys.argv=['test_solver']
else:
sys.argv=argv
# Create the tests defined in the YAML configuration file
autotest_options = Options()
autotest_options.testname_format = "%s_TEST_%s"
pyutilib.autotest.create_test_suites(filename=currdir+'test_solvers.yml', _globals=globals(), options=autotest_options)
# Execute the tests, using a custom test runner
runner = SolverTestRunner()
runner.options = options
unittest.main(module=globals()['__name__'], testRunner=runner)
示例2: help_environment
def help_environment():
cmddir = os.path.dirname(os.path.abspath(sys.executable))+os.sep
info = Options()
#
info.python = Options()
info.python.version = '%d.%d.%d' % sys.version_info[:3]
info.python.executable = sys.executable
info.python.platform = sys.platform
try:
packages = []
import pip
for package in pip.get_installed_distributions():
packages.append( Options(name=package.project_name, version=package.version) )
info.python.packages = packages
except:
pass
#
info.environment = Options()
path = os.environ.get('PATH', None)
if not path is None:
info.environment['shell path'] = path.split(os.pathsep)
info.environment['python path'] = sys.path
#
print('#')
print('# Information About the Python and Shell Environment')
print('#')
print(str(info))
示例3: create_test_suites
def create_test_suites(filename=None, config=None, _globals=None, options=None):
if options is None: #pragma:nocover
options = Options()
#
# Add categories specified by the PYUTILIB_AUTOTEST_CATEGORIES
# or PYUTILIB_UNITTEST_CATEGORIES environments
#
if options is None or options.categories is None or len(
options.categories) == 0:
options.categories = set()
if 'PYUTILIB_AUTOTEST_CATEGORIES' in os.environ:
for cat in re.split(',',
os.environ['PYUTILIB_AUTOTEST_CATEGORIES']):
if cat != '':
options.categories.add(cat.strip())
elif 'PYUTILIB_UNITTEST_CATEGORIES' in os.environ:
for cat in re.split(',',
os.environ['PYUTILIB_UNITTEST_CATEGORIES']):
if cat != '':
options.categories.add(cat.strip())
#
if not filename is None:
if options.currdir is None:
options.currdir = dirname(abspath(filename)) + os.sep
#
ep = ExtensionPoint(plugins.ITestParser)
ftype = os.path.splitext(filename)[1]
if not ftype == '':
ftype = ftype[1:]
service = ep.service(ftype)
if service is None:
raise IOError(
"Unknown file type. Cannot load test configuration from file '%s'"
% filename)
config = service.load_test_config(filename)
#service.print_test_config(config)
validate_test_config(config)
#
# Evaluate Python expressions
#
for item in config.get('python', []):
try:
exec(item, _globals)
except Exception:
err = sys.exc_info()[1]
print("ERROR executing '%s'" % item)
print(" Exception: %s" % str(err))
#
# Create test driver, which is put in the global namespace
#
driver = plugins.TestDriverFactory(config['driver'])
if driver is None:
raise IOError("Unexpected test driver '%s'" % config['driver'])
_globals["test_driver"] = driver
#
# Generate suite
#
for suite in config.get('suites', {}):
create_test_suite(suite, config, _globals, options)
示例4: PyomoDataCommands
class PyomoDataCommands(Plugin):
alias("dat", "Pyomo data command file interface")
implements(IDataManager, service=False)
def __init__(self):
self._info = []
self.options = Options()
def available(self):
return True
def initialize(self, **kwds):
self.filename = kwds.pop("filename")
self.add_options(**kwds)
def add_options(self, **kwds):
self.options.update(kwds)
def open(self):
if self.filename is None: # pragma:nocover
raise IOError("No filename specified")
if not os.path.exists(self.filename): # pragma:nocover
raise IOError("Cannot find file '%s'" % self.filename)
def close(self):
pass
def read(self):
"""
This function does nothing, since executing Pyomo data commands
both reads and processes the data all at once.
"""
pass
def write(self, data): # pragma:nocover
"""
This function does nothing, because we cannot write to a *.dat file.
"""
pass
def process(self, model, data, default):
"""
Read Pyomo data commands and process the data.
"""
_process_include(["include", self.filename], model, data, default, self.options)
def clear(self):
self._info = []
示例5: __init__
def __init__(self):
"""
Constructor
"""
self._info=None
self._data=None
self.options = Options()
self.options.ncolumns = 1
示例6: configure_loggers
def configure_loggers(options=None, reset=False):
if reset:
options = Options()
options.runtime = Options()
options.runtime.logging = 'quiet'
logging.getLogger('pyomo.core').handlers = []
logging.getLogger('pyomo').handlers = []
logging.getLogger('pyutilib').handlers = []
#
# Configure the logger
#
if options.runtime is None:
options.runtime = Options()
if options.runtime.logging == 'quiet':
logging.getLogger('pyomo.opt').setLevel(logging.ERROR)
logging.getLogger('pyomo.core').setLevel(logging.ERROR)
logging.getLogger('pyomo').setLevel(logging.ERROR)
logging.getLogger('pyutilib').setLevel(logging.ERROR)
elif options.runtime.logging == 'warning':
logging.getLogger('pyomo.opt').setLevel(logging.WARNING)
logging.getLogger('pyomo.core').setLevel(logging.WARNING)
logging.getLogger('pyomo').setLevel(logging.WARNING)
logging.getLogger('pyutilib').setLevel(logging.WARNING)
elif options.runtime.logging == 'info':
logging.getLogger('pyomo.opt').setLevel(logging.INFO)
logging.getLogger('pyomo.core').setLevel(logging.INFO)
logging.getLogger('pyomo').setLevel(logging.INFO)
logging.getLogger('pyutilib').setLevel(logging.INFO)
elif options.runtime.logging == 'verbose':
logger.setLevel(logging.DEBUG)
logging.getLogger('pyomo').setLevel(logging.DEBUG)
logging.getLogger('pyutilib').setLevel(logging.DEBUG)
elif options.runtime.logging == 'debug':
logging.getLogger('pyomo.opt').setLevel(logging.DEBUG)
logging.getLogger('pyomo.core').setLevel(logging.DEBUG)
logging.getLogger('pyomo').setLevel(logging.DEBUG)
logging.getLogger('pyutilib').setLevel(logging.DEBUG)
if options.runtime.logfile:
logging.getLogger('pyomo.opt').handlers = []
logging.getLogger('pyomo.core').handlers = []
logging.getLogger('pyomo').handlers = []
logging.getLogger('pyutilib').handlers = []
logging.getLogger('pyomo.core').addHandler( logging.FileHandler(options.runtime.logfile, 'w'))
logging.getLogger('pyomo').addHandler( logging.FileHandler(options.runtime.logfile, 'w'))
logging.getLogger('pyutilib').addHandler( logging.FileHandler(options.runtime.logfile, 'w'))
示例7: setUp
def setUp(self, testcase, options):
global tmpdir
tmpdir = os.getcwd()
os.chdir(options.currdir)
pyutilib.services.TempfileManager.push()
pyutilib.services.TempfileManager.sequential_files(0)
pyutilib.services.TempfileManager.tempdir = options.currdir
#
if ':' in options.solver:
solver, sub_solver = options.solver.split(':')
if options.solver_options is None:
_options = Options()
else:
_options = options.solver_options
_options.solver = sub_solver
testcase.opt = pyomo.opt.SolverFactory(solver, options=_options)
else:
testcase.opt = pyomo.opt.SolverFactory(options.solver, options=options.solver_options)
if testcase.opt is None or not testcase.opt.available(False):
testcase.skipTest('Solver %s is not available' % options.solver)
示例8: initialize
def initialize(**kwds):
obj = Options(**kwds)
#
# Set obj.available
#
opt = None
try:
opt = SolverFactory(obj.name, solver_io=obj.io)
except:
pass
if opt is None or isinstance(opt, UnknownSolver):
obj.available = False
elif (obj.name == "gurobi") and (not GUROBISHELL.license_is_valid()):
obj.available = False
elif (obj.name == "baron") and (not BARONSHELL.license_is_valid()):
obj.available = False
else:
obj.available = (opt.available(exception_flag=False)) and (
(not hasattr(opt, "executable")) or (opt.executable() is not None)
)
#
# Check capabilities
#
if obj.available:
for _c in obj.capabilities:
if not _c in opt._capabilities:
raise ValueError("Solver %s does not support capability %s!" % (obj.name, _c))
#
# Get version
#
obj.version = opt.version()
return obj
示例9: test_t1
def test_t1(self):
# Run a simple model
model = ConcreteModel()
model.A = RangeSet(1,4)
model.x = Var(model.A, bounds=(-1,1))
def obj_rule(model):
return sum_product(model.x)
model.obj = Objective(rule=obj_rule)
def c_rule(model):
expr = 0
for i in model.A:
expr += i*model.x[i]
return expr == 0
model.c = Constraint(rule=c_rule)
#
data = Options()
data.suffixes = {}
data.solver_options = {}
data.warmstart_filename = None
data.filename = currdir+'t1.lp'
model.write(data['filename'])
INPUT = open(data['filename'],'r')
data['file'] = INPUT.read()
INPUT.close()
data['opt'] = 'glpk'
data.kwds = {}
#
results = self.worker.process(data)
# Decode, evaluate and unpickle results
if using_pyro4:
# These two conversions are in place to unwrap
# the hacks placed in the pyro_mip_server
# before transmitting the results
# object. These hacks are put in place to
# avoid errors when transmitting the pickled
# form of the results object with the default Pyro4
# serializer (Serpent)
if six.PY3:
results = base64.decodebytes(
ast.literal_eval(results))
else:
results = base64.decodestring(results)
results = pickle.loads(results)
#
results.write(filename=currdir+"t1.out", format='json')
self.assertMatchesJsonBaseline(currdir+"t1.out",currdir+"t1.txt", tolerance=1e-4)
self.assertEqual(results._smap_id, None)
os.remove(data['filename'])
示例10: JSONDictionary
class JSONDictionary(Plugin):
alias("json", "JSON file interface")
implements(IDataManager, service=False)
def __init__(self):
self._info = {}
self.options = Options()
def available(self):
return True
def initialize(self, **kwds):
self.filename = kwds.pop('filename')
self.add_options(**kwds)
def add_options(self, **kwds):
self.options.update(kwds)
def open(self):
if self.filename is None:
raise IOError("No filename specified")
def close(self):
pass
def read(self):
"""
This function loads data from a JSON file and tuplizes the nested
dictionaries and lists of lists.
"""
if not os.path.exists(self.filename):
raise IOError("Cannot find file '%s'" % self.filename)
INPUT = open(self.filename, 'r')
jdata = json.load(INPUT)
INPUT.close()
if jdata is None or len(jdata) == 0:
raise IOError("Empty JSON data file")
self._info = {}
for k,v in jdata.items():
self._info[k] = tuplize(v)
def write(self, data):
"""
This function creates a JSON file for the specified data.
"""
with open(self.filename, 'w') as OUTPUT:
jdata = {}
if self.options.data is None:
for k,v in data.items():
jdata[k] = detuplize(v)
elif type(self.options.data) in (list, tuple):
for k in self.options.data:
jdata[k] = detuplize(data[k])
else:
k = self.options.data
jdata[k] = detuplize(data[k])
json.dump(jdata, OUTPUT)
def process(self, model, data, default):
"""
Set the data for the selected components
"""
if not self.options.namespace in data:
data[self.options.namespace] = {}
#
try:
if self.options.data is None:
for key in self._info:
self._set_data(data, self.options.namespace, key, self._info[key])
elif type(self.options.data) in (list, tuple):
for key in self.options.data:
self._set_data(data, self.options.namespace, key, self._info[key])
else:
key = self.options.data
self._set_data(data, self.options.namespace, key, self._info[key])
except KeyError:
raise IOError("Data value for '%s' is not available in JSON file '%s'" % (key, self.filename))
def _set_data(self, data, namespace, name, value):
if type(value) is dict:
data[namespace][name] = value
else:
data[namespace][name] = {None: value}
def clear(self):
self._info = {}
示例11: Objective
# Objective
#model.obj = Objective(expr = math.sqrt(((model.p - model.x)**2) + ((model.q - model.y)**2)))
model.obj = Objective(expr = (((model.p - model.x)**2) + ((model.q - model.y)**2))**0.5)
# Constraints
model.KeineAhnung = Constraint(expr = ((model.x / model.length)**2) + ((model.y / model.width)**2) - 1 >= 0)
model.pprint()
model.skip_canonical_repn = True # for nonlinear models
instance=model.create()
SolverName = "asl"
so = Options()
so.solver = "ipopt"
opt=SolverFactory(SolverName, options=so)
if opt is None:
print("Could not construct solver %s : %s" % (SolverName, so.solver))
sys.exit(1)
results=opt.solve(instance)
results.write()
instance.load(results) # put results in model
# because we know there is a variable named x
x_var = getattr(instance, "x")
x_val = x_var()
示例12: pyomo_create_model
def pyomo_create_model(options=None, model_options=None):
if model_options is None:
model_options = Options()
if model_options.type is None:
model_options.type = 'fixed_set_size'
#
# m - number of elements
#
m = 100 if model_options.m is None else model_options.m
#
# n - number of sets
#
n = 200 if model_options.n is None else model_options.n
seed = 9090 if model_options.seed is None else model_options.seed
random.seed(9090)
#
if model_options.type == 'fixed_set_size':
#
# p - fixed number elements per set
# rho - fixed fraction of elements per set
#
p = model_options.p
if p is None:
if model_options.rho is None:
p = int(math.ceil(m * 0.7))
else:
p = int(math.ceil(m * model_options.rho))
#
def S_rule(model):
ans = set()
for j in xrange(1,n+1):
tmp = list(range(1,m+1))
random.shuffle( tmp )
for i in range(0,p):
ans.add( (tmp[i], j) )
return ans
elif model_options.type == 'fixed_element_coverage':
#
# p - fixed number of sets that cover each element
# rho - fixed fraction of sets that cover each element
#
p = model_options.p
if p is None:
if model_options.rho is None:
p = int(math.ceil(n * 0.4))
else:
p = int(math.ceil(n * model_options.rho))
#
def S_rule(model):
ans = set()
for i in xrange(1,m+1):
tmp = list(range(1,n+1))
random.shuffle( tmp )
for j in range(0,p):
ans.add( (i, tmp[j]) )
return ans
elif model_options.type == 'fixed_probability':
#
# rho - probability of selecting element for a set
#
rho = 0.3 if model_options.rho is None else model_options.rho
#
def S_rule(model):
ans = set()
for j in xrange(1,n+1):
for i in xrange(1,m+1):
if random.uniform(0,1) < rho:
ans.add( (i, j) )
return ans
elif model_options.type == 'fixed_fill':
#
# rho - |S|/(I*J)
#
rho = 0.3 if model_options.rho is None else model_options.rho
#
def S_rule(model):
ans = set()
for j in xrange(1,n+1):
for i in xrange(1,m+1):
if random.uniform(0,1) < rho:
ans.add( (i, j) )
return ans
#
# CREATE MODEL
#
model = ConcreteModel()
#
# (i,j) in S if element i in set j
#
model.S = Set(dimen=2, initialize=S_rule)
#
# Dynamically create the I and J index sets, since
# some rows or columns of S may not be populated.
#
def I_rule(model):
return set((i for (i,j) in model.S))
model.I = Set(initialize=I_rule)
def J_rule(model):
return set((j for (i,j) in model.S))
model.J = Set(initialize=J_rule)
#.........这里部分代码省略.........
示例13: Constraint
#return Constraint.Skip
return expr >= 1
model.cover = Constraint(model.I, rule=cover_rule)
#
print_model_stats(model_options, model)
return model
def test_model(options=None):
model = pyomo_create_model(model_options=options)
#print_model_stats(options, model)
if __name__ == '__main__':
test_model()
#
options = Options()
options.type = 'fixed_set_size'
options.m = 11
options.n = 21
options.rho = 0.3
test_model(options)
#
options = Options()
options.type = 'fixed_element_coverage'
test_model(options)
#
options = Options()
options.m = 100
options.n = 200
options.type = 'fixed_probability'
test_model(options)
示例14: Var
self.model.x = Var()
def compare(self):
S = Pyomo2FuncDesigner(self.model)
self.assertAlmostEqual(self.model.f(), S.f(S.initial_point))
def tearDown(self):
self.model = None
@unittest.nottest
def expr_test(self, name):
options = self.get_options(name)
self.model.x.value = options.x
if name == 'pow':
self.model.f = Objective(expr=options.fn(self.model.x, 2))
else:
self.model.f = Objective(expr=options.fn(self.model.x))
self.compare()
for i in range(len(fns)):
options = Options()
options.fn = fns[i]
options.x = xs[i]
Tests.add_fn_test(fn=expr_test, name=fns[i].__name__, options=options)
if __name__ == "__main__":
unittest.main()
示例15: create_test_suite
def create_test_suite(suite, config, _globals, options):
#
# Skip suite creation if the options categores do not intersect with the list of test suite categories
#
if len(options.categories) > 0:
flag = False
for cat in options.categories:
if cat in config['suites'][suite].get('categories',[]):
flag = True
break
if not flag:
return
#
# Create test driver
#
if suite in _globals:
raise IOError("Cannot create suite '%s' since there is another symbol with that name in the global namespace!" % suite)
def setUpClassFn(cls):
options = cls._options[None]
cls._test_driver.setUpClass(cls,options)
_globals[suite] = type(str(suite),(unittest.TestCase,),{'setUpClass': classmethod(setUpClassFn)})
_globals[suite]._options[None] = options
setattr(_globals[suite],'_test_driver', _globals['test_driver'])
setattr(_globals[suite],'suite_categories', config['suites'][suite].get('categories',[]))
#
# Create test functions
#
tests = []
if 'tests' in config['suites'][suite]:
for item in config['suites'][suite]['tests']:
tests.append( (item['solver'], item['problem'], item) )
else:
for solver in config['suites'][suite]['solvers']:
for problem in config['suites'][suite]['problems']:
tests.append( (solver, problem, {}) )
#
for solver, problem, item in tests:
##sname = solver
if options.testname_format is None:
test_name = solver+"_"+problem
else:
test_name = options.testname_format % (solver, problem)
#
def fn(testcase, name, suite):
options = testcase._options[suite,name]
fn.test_driver.setUp(testcase, options)
ans = fn.test_driver.run_test(testcase, name, options)
fn.test_driver.tearDown(testcase, options)
return ans
fn.test_driver = _globals['test_driver']
#
_options = Options()
#
problem_options = config['suites'][suite]['problems'][problem]
if not problem_options is None and 'problem' in problem_options:
_problem = problem_options['problem']
else:
_problem = problem
for attr,value in config['problems'].get(_problem,{}).items():
_options[attr] = _str(value)
if not problem_options is None:
for attr,value in problem_options.items():
_options[attr] = _str(value)
#
solver_options = config['suites'][suite]['solvers'][solver]
if not solver_options is None and 'solver' in solver_options:
_solver = solver_options['solver']
else:
_solver = solver
_name = _solver
for attr,value in config['solvers'].get(_solver,{}).items():
_options[attr] = _str(value)
if attr == 'name':
_name = value
if not solver_options is None:
for attr,value in solver_options.items():
_options[attr] = _str(value)
#
for key in item:
if key not in ['problem','solver']:
_options[key] = _str(item[key])
#
_options.solver = _str(_name)
_options.problem = _str(_problem)
_options.suite = _str(suite)
_options.currdir = _str(options.currdir)
#
_globals[suite].add_fn_test(name=test_name, fn=fn, suite=suite, options=_options)