本文整理汇总了Python中pyomo.core.base.value函数的典型用法代码示例。如果您正苦于以下问题:Python value函数的具体用法?Python value怎么用?Python value使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了value函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: update_bounds_lists
def update_bounds_lists(var_name):
var_lb = None
var_ub = None
if var_data.fixed and self._output_fixed_variable_bounds:
var_lb = var_ub = var_data.value
elif var_data.fixed:
# if we've been directed to not deal with fixed
# variables, then skip - they should have been
# compiled out of any description of the constraints
return
else:
if var_data.lb is None:
var_lb = -cplex.infinity
else:
var_lb = value(var_data.lb)
if var_data.ub is None:
var_ub = cplex.infinity
else:
var_ub= value(var_data.ub)
var_cplex_id = self._cplex_variable_ids[var_name]
new_lower_bounds.append((var_cplex_id, var_lb))
new_upper_bounds.append((var_cplex_id, var_ub))
示例2: _collect_linear_pow
def _collect_linear_pow(exp, idMap, multiplier, coef, varmap, compute_values):
if exp.is_fixed():
if compute_values:
coef[None] += multiplier * value(exp)
else:
coef[None] += multiplier * exp
elif value(exp._args[1]) == 1:
arg = exp._args[0]
_linear_collectors[arg.__class__](arg, idMap, multiplier, coef, varmap, compute_values)
else:
raise TypeError( "Unsupported power expression: "+str(exp._args) )
示例3: instance2dat
def instance2dat(instance, output_filename):
output_file = open(output_filename,"w")
for set_name, set_object in iteritems(instance.component_map(Set, active=True)):
if (set_object.initialize is not None) and (type(set_object.initialize) is types.FunctionType):
continue
if (set_name.find("_index") == -1) and (set_name.find("_domain") == -1):
if set_object.dim() == 0:
if len(set_object) == 0:
continue
print >>output_file, "set "+set_name+" := "
for element in set_object:
print >>output_file, element
print >>output_file, ";"
elif set_object.dim() == 1:
for index in set_object:
print >>output_file, "set "+set_name+"[\""+str(index)+"\"]"+" := ",
for element in set_object[index]:
print >>output_file, element,
print >>output_file, ";"
else:
print >>output_file, "***MULTIPLY INDEXED SETS NOT IMPLEMENTED!!!"
pass
print >>output_file, ""
for param_name, param_object in iteritems(instance.component_map(Param, active=True)):
if (param_object._initialize is not None) and (type(param_object._initialize) is types.FunctionType):
continue
elif len(param_object) == 0:
continue
if None in param_object:
print >>output_file, "param "+param_name+" := "+str(value(param_object[None]))+" ;"
print >>output_file, ""
else:
print >>output_file, "param "+param_name+" := "
if param_object.dim() == 1:
for index in param_object:
print >>output_file, index, str(value(param_object[index]))
else:
for index in param_object:
for i in index:
print >>output_file, i,
print >>output_file, str(value(param_object[index]))
print >>output_file, ";"
print >>output_file, ""
output_file.close()
示例4: __imul__
def __imul__(self, other):
_type = other.__class__
if _type in native_numeric_types:
pass
elif _type is CompiledLinearCanonicalRepn:
if other.variables:
self, other = other, self
assert(not other.variables)
CompiledLinearCanonicalRepn_Pool.append(other)
other = other.constant
elif other.is_fixed():
other = value(other)
else:
assert isinstance(other, _VarData)
assert not self.variables
self.variables.append(other)
self.linear[id(other)] = self.constant
self.constant = 0.
return self
if other:
for _id in self.linear:
self.linear[_id] *= other
else:
self.linear = {}
self.variables = []
self.constant *= other
return self
示例5: __iadd__
def __iadd__(self, other):
_type = other.__class__
if _type in native_numeric_types:
self.constant += other
elif _type is CompiledLinearCanonicalRepn:
self.constant += other.constant
for v in other.variables:
_id = id(v)
if _id in self.linear:
self.linear[_id] += other.linear[_id]
else:
self.variables.append(v)
self.linear[_id] = other.linear[_id]
CompiledLinearCanonicalRepn_Pool.append(other)
elif other.is_fixed():
self.constant += value(other)
else:
assert isinstance(other, _VarData)
_id = id(other)
if _id in self.linear:
self.linear[_id] += 1.
else:
self.variables.append(other)
self.linear[_id] = 1.
return self
示例6: _collect_linear_intrinsic
def _collect_linear_intrinsic(exp, idMap, multiplier, coef, varmap, compute_values):
if exp.is_fixed():
if compute_values:
coef[None] += multiplier * value(exp)
else:
coef[None] += multiplier * exp
else:
raise TypeError( "Unsupported intrinsic expression: %s: %s" % (exp, str(exp._args)) )
示例7: _collect_identity
def _collect_identity(exp, idMap, multiplier, coef, varmap, compute_values):
exp = exp.expr
if exp.is_fixed():
if compute_values:
coef[None] += multiplier * value(exp)
else:
coef[None] += multiplier * exp
else:
_linear_collectors[exp.__class__](exp, idMap, multiplier, coef, varmap, compute_values)
示例8: propagate_solution
def propagate_solution(self, scaled_model, original_model):
"""
This method takes the solution in scaled_model and maps it back to the original model.
It will also transform duals and reduced costs if the suffixes 'dual' and/or 'rc' are present.
The :code:`scaled_model` argument must be a model that was already scaled using this transformation
as it expects data from the transformation to perform the back mapping.
Parameters
----------
scaled_model : Pyomo Model
The model that was previously scaled with this transformation
original_model : Pyomo Model
The original unscaled source model
"""
if not hasattr(scaled_model, 'component_scaling_factor_map'):
raise AttributeError('ScaleModel:propagate_solution called with scaled_model that does not '
'have a component_scaling_factor_map. It is possible this method was called '
'using a model that was not scaled with the ScaleModel transformation')
if not hasattr(scaled_model, 'scaled_component_to_original_name_map'):
raise AttributeError('ScaleModel:propagate_solution called with scaled_model that does not '
'have a scaled_component_to_original_name_map. It is possible this method was called '
'using a model that was not scaled with the ScaleModel transformation')
component_scaling_factor_map = scaled_model.component_scaling_factor_map
scaled_component_to_original_name_map = scaled_model.scaled_component_to_original_name_map
# get the objective scaling factor
scaled_objectives = list(scaled_model.component_data_objects(ctype=Objective, active=True, descend_into=True))
if len(scaled_objectives) != 1:
raise NotImplementedError(
'ScaleModel.propagate_solution requires a single active objective function, but %d objectives found.' % (
len(objectives)))
objective_scaling_factor = component_scaling_factor_map[scaled_objectives[0]]
# transfer the variable values and reduced costs
check_reduced_costs = type(scaled_model.component('rc')) is Suffix
for scaled_v in scaled_model.component_objects(ctype=Var, descend_into=True):
# get the unscaled_v from the original model
original_v_path = scaled_component_to_original_name_map[scaled_v]
original_v = original_model.find_component(original_v_path)
for k in scaled_v:
original_v[k].value = value(scaled_v[k]) / component_scaling_factor_map[scaled_v[k]]
if check_reduced_costs and scaled_v[k] in scaled_model.rc:
original_model.rc[original_v[k]] = scaled_model.rc[scaled_v[k]] * component_scaling_factor_map[
scaled_v[k]] / objective_scaling_factor
# transfer the duals
if type(scaled_model.component('dual')) is Suffix and type(original_model.component('dual')) is Suffix:
for scaled_c in scaled_model.component_objects(ctype=Constraint, descend_into=True):
original_c = original_model.find_component(scaled_component_to_original_name_map[scaled_c])
for k in scaled_c:
original_model.dual[original_c[k]] = scaled_model.dual[scaled_c[k]] * component_scaling_factor_map[
scaled_c[k]] / objective_scaling_factor
示例9: visiting_potential_leaf
def visiting_potential_leaf(self, node):
"""
Visiting a potential leaf.
Return True if the node is not expanded.
"""
if node.__class__ in native_numeric_types:
return True, node
if node.__class__ is casadi.SX:
return True, node
if node.is_variable_type():
return True, value(node)
if not node.is_expression_type():
return True, value(node)
return False, None
示例10: _collect_linear_prod
def _collect_linear_prod(exp, idMap, multiplier, coef, varmap, compute_values):
multiplier *= exp._coef
_coef = { None : 0 }
_varmap = {}
for subexp in exp._denominator:
if compute_values:
x = value(subexp) # only have constants/fixed terms in the denominator.
if x == 0:
buf = StringIO()
subexp.pprint(buf)
logger.error("Divide-by-zero: offending sub-expression:\n " + buf)
raise ZeroDivisionError
multiplier /= x
else:
multiplier /= subexp
for subexp in exp._numerator:
if _varmap:
if compute_values:
multiplier *= value(subexp)
else:
multiplier *= subexp
else:
_linear_collectors[subexp.__class__](subexp, idMap, 1, _coef, _varmap, compute_values)
if not _varmap:
multiplier *= _coef[None]
_coef[None] = 0
if _varmap:
for key, val in iteritems(_coef):
if key in coef:
coef[key] += multiplier * val
else:
coef[key] = multiplier * val
varmap.update(_varmap)
else:
# constant expression; i.e. 1/x
coef[None] += multiplier
示例11: get_table
def get_table(self):
tmp = []
if not self.options.columns is None:
tmp.append(self.options.columns)
if not self.options.set is None:
# Create column names
if self.options.columns is None:
cols = []
for i in xrange(self.options.set.dimen):
cols.append(self.options.set.local_name+str(i))
tmp.append(cols)
# Get rows
if not self.options.sort is None:
for data in sorted(self.options.set):
if self.options.set.dimen > 1:
tmp.append(list(data))
else:
tmp.append([data])
else:
for data in self.options.set:
if self.options.set.dimen > 1:
tmp.append(list(data))
else:
tmp.append([data])
elif not self.options.param is None:
if type(self.options.param) in (list,tuple):
_param = self.options.param
else:
_param = [self.options.param]
tmp = []
# Collect data
for index in _param[0]:
if index is None:
row = []
elif type(index) in (list,tuple):
row = list(index)
else:
row = [index]
for param in _param:
row.append(value(param[index]))
tmp.append(row)
# Create column names
if self.options.columns is None:
cols = []
for i in xrange(len(tmp[0])-len(_param)):
cols.append('I'+str(i))
for param in _param:
cols.append(param)
tmp = [cols] + tmp
return tmp
示例12: subproblem_solve
def subproblem_solve(gdp, solver, config):
subproblem = gdp.clone()
TransformationFactory('gdp.fix_disjuncts').apply_to(subproblem)
result = solver.solve(subproblem, **config.solver_args)
main_obj = next(subproblem.component_data_objects(Objective, active=True))
obj_sign = 1 if main_obj.sense == minimize else -1
if (result.solver.status is SolverStatus.ok and
result.solver.termination_condition is tc.optimal):
return value(main_obj.expr), result, subproblem.GDPbb_utils.variable_list
elif result.solver.termination_condition is tc.unbounded:
return obj_sign * float('-inf'), result, subproblem.GDPbb_utils.variable_list
else:
return obj_sign * float('inf'), result, subproblem.GDPbb_utils.variable_list
示例13: coopr3_generate_canonical_repn
def coopr3_generate_canonical_repn(exp, idMap=None, compute_values=True):
if exp is None:
return CompiledLinearCanonicalRepn()
degree = exp.polynomial_degree()
if idMap is None:
idMap = {}
idMap.setdefault(None, {})
if degree == 0:
ans = CompiledLinearCanonicalRepn()
ans.constant = value(exp)
return ans
elif degree == 1:
# varmap is a map from the variable id() to a _VarData.
# coef is a map from the variable id() to its coefficient.
coef, varmap = collect_linear_canonical_repn(exp, idMap, compute_values)
ans = CompiledLinearCanonicalRepn()
if None in coef:
val = coef.pop(None)
if type(val) not in [int,float] or val != 0.0:
ans.constant = val
# the six module is inefficient in terms of wrapping iterkeys
# and itervalues, in the context of Python 2.7. use the native
# dictionary methods where possible.
if using_py3:
ans.linear = tuple( itervalues(coef) )
ans.variables = tuple(varmap[var_hash] for var_hash in iterkeys(coef) )
else:
ans.linear = tuple( coef.itervalues() )
ans.variables = tuple(varmap[var_hash] for var_hash in coef.iterkeys() )
return ans
# **Py3k: degree > 1 comparision will error if degree is None
elif degree and degree > 1:
ans = collect_general_canonical_repn(exp, idMap, compute_values)
if 1 in ans:
linear_terms = {}
for key, coef in iteritems(ans[1]):
linear_terms[list(key.keys())[0]] = coef
ans[1] = linear_terms
return GeneralCanonicalRepn(ans)
else:
return GeneralCanonicalRepn(
{ None: exp, -1 : collect_variables(exp, idMap) } )
示例14: _collect_linear_var
def _collect_linear_var(exp, idMap, multiplier, coef, varmap, compute_values):
if exp.is_fixed():
if compute_values:
coef[None] += multiplier * value(exp)
else:
coef[None] += multiplier * exp
else:
id_ = id(exp)
if id_ in idMap[None]:
key = idMap[None][id_]
else:
key = len(idMap) - 1
idMap[None][id_] = key
idMap[key] = exp
#
if key in coef:
coef[key] += multiplier
else:
coef[key] = multiplier
varmap[key] = exp
示例15: pyomo4_generate_canonical_repn
def pyomo4_generate_canonical_repn(exp, idMap=None, compute_values=True):
if exp is None:
return CompiledLinearCanonicalRepn()
if exp.__class__ in native_numeric_types:
ans = CompiledLinearCanonicalRepn()
ans.constant = value(exp)
return ans
if not exp.is_expression():
if exp.is_fixed():
ans = CompiledLinearCanonicalRepn()
ans.constant = value(exp)
return ans
elif isinstance(exp, _VarData):
ans = CompiledLinearCanonicalRepn()
ans.constant = 0
ans.linear = (1.,)
ans.variables = (exp,)
return ans
else:
raise RuntimeError(
"Unrecognized expression node: %s" % (type(exp),) )
degree = exp.polynomial_degree()
if degree == 1:
_stack = []
_args = exp._args
_idx = 0
_len = len(_args)
_result = None
while 1:
# Linear expressions just need to be filteres and copied
if exp.__class__ is expr_pyomo4._LinearExpression:
_result = expr_pyomo4._LinearExpression(None, 0)
_result._args = []
_result._coef.clear()
_result._const = value(exp._const)
for v in _args:
_id = id(v)
if v.is_fixed():
_result._const += v.value * value(exp._coef[_id])
else:
_result._args.append(v)
_result._coef[_id] = value(exp._coef[_id])
_idx = _len
# Other expressions get their arguments parsed one at a time
if _idx < _len:
_stack.append((exp, _args, _idx+1, _len, _result))
exp = _args[_idx]
if exp.__class__ in native_numeric_types:
_len = _idx = 0
_result = exp
elif exp.is_expression():
_args = exp._args
_idx = 0
_len = len(_args)
_result = None
continue
elif isinstance(exp, _VarData):
_len = _idx = 0
if exp.is_fixed():
_result = exp.value
else:
_result = expr_pyomo4._LinearExpression(exp, 1.)
else:
raise RuntimeError(
"Unrecognized expression node: %s" % (type(exp),) )
#
# End of _args... time to move up the stack
#
# Top of the stack. _result had better be a _LinearExpression
if not _stack:
ans = CompiledLinearCanonicalRepn()
# old format
ans.constant = _result._const
ans.linear = []
for v in _result._args:
# Note: this also filters out the bogus NONE we added above
_coef = _result._coef[id(v)]
if _coef:
ans.variables.append(v)
ans.linear.append(_coef)
if idMap:
if None not in idMap:
idMap[None] = {}
_test = idMap[None]
_key = len(idMap) - 1
for v in ans.variables:
if id(v) not in _test:
_test[id(v)] = _key
idMap[_key] = v
_key += 1
return ans
# Ok ... process the new argument to the node. Note that
# _idx is 1-based now...
#.........这里部分代码省略.........