Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def get_capacity_constraint(backend_model, parameter, loc_tech,
_equals=None, _max=None, _min=None, scale=None):
decision_variable = getattr(backend_model, parameter)
if not _equals:
_equals = get_param(backend_model, parameter + '_equals', loc_tech)
if not _max:
_max = get_param(backend_model, parameter + '_max', loc_tech)
if not _min:
_min = get_param(backend_model, parameter + '_min', loc_tech)
if po.value(_equals) is not False and po.value(_equals) is not None:
if np.isinf(po.value(_equals)):
e = exceptions.ModelError
raise e('Cannot use inf for {}_equals for loc:tech `{}`'.format(parameter, loc_tech))
if scale:
_equals *= scale
return decision_variable[loc_tech] == _equals
else:
if po.value(_min) == 0 and np.isinf(po.value(_max)):
return po.Constraint.NoConstraint
else:
if scale:
_max *= scale
_min *= scale
return (_min, decision_variable[loc_tech], _max)
"""
for var in m.component_data_objects(
ctype=Var, descend_into=True):
if var.fixed:
continue
var_value = var.value
if var_value is None:
logger.debug("Skipping VAR {} with no assigned value.")
continue
if (var.has_lb() and var.has_ub() and
fabs(value(var.ub - var.lb)) <= 2 * tol):
continue # if the bounds are too close, skip.
if var.has_lb() and fabs(value(var.lb - var)) <= tol:
logger.info('{} near LB of {}'.format(var.name, value(var.lb)))
elif var.has_ub() and fabs(value(var.ub - var)) <= tol:
logger.info('{} near UB of {}'.format(var.name, value(var.ub)))
for constr in m.component_data_objects(
ctype=Constraint, descend_into=True, active=True):
if not constr.equality:
# skip equality constraints, because they should always be close to
# bounds if enforced.
body_value = value(constr.body, exception=False)
if body_value is None:
logger.info("Skipping CONSTR {}: missing variable value.".format(constr.name))
continue
if (constr.has_ub() and
fabs(value(body_value - constr.upper)) <= tol):
logger.info('{} near UB'.format(constr.name))
if (constr.has_lb() and
fabs(value(body_value - constr.lower)) <= tol):
logger.info('{} near LB'.format(constr.name))
logger.debug("Skipping VAR {} with no assigned value.")
continue
if (var.has_lb() and var.has_ub() and
fabs(value(var.ub - var.lb)) <= 2 * tol):
continue # if the bounds are too close, skip.
if var.has_lb() and fabs(value(var.lb - var)) <= tol:
logger.info('{} near LB of {}'.format(var.name, value(var.lb)))
elif var.has_ub() and fabs(value(var.ub - var)) <= tol:
logger.info('{} near UB of {}'.format(var.name, value(var.ub)))
for constr in m.component_data_objects(
ctype=Constraint, descend_into=True, active=True):
if not constr.equality:
# skip equality constraints, because they should always be close to
# bounds if enforced.
body_value = value(constr.body, exception=False)
if body_value is None:
logger.info("Skipping CONSTR {}: missing variable value.".format(constr.name))
continue
if (constr.has_ub() and
fabs(value(body_value - constr.upper)) <= tol):
logger.info('{} near UB'.format(constr.name))
if (constr.has_lb() and
fabs(value(body_value - constr.lower)) <= tol):
logger.info('{} near LB'.format(constr.name))
def solve_bounding_problem(model, solver):
results = SolverFactory(solver).solve(model)
if results.solver.termination_condition is tc.optimal:
return value(model._var_bounding_obj.expr)
elif results.solver.termination_condition is tc.infeasible:
return None
elif results.solver.termination_condition is tc.unbounded:
return -inf
else:
raise NotImplementedError(
"Unhandled termination condition: %s"
% results.solver.termination_condition)
results = ph._solver.solve(m, warmstart=True)
ss = results.solver.status
tc = results.solver.termination_condition
#self.timeInSolver += results['Solver'][0]['Time']
if ss == SolverStatus.ok and tc in _acceptable_termination_conditions:
if PYOMO_4_0:
m.load(results)
else:
m.solutions.load_from(results)
_src = _block.local_stage1_varmap
return (
# Note: _src is {id: weakref} and original_obj is a
# weakref; so dereference weakref before computing value
dict((_id, value(_var())) for _id, _var in iteritems(_src)),
value(_block.original_obj()) )
else:
return None
fixed_inputs[dest_unit].add(evar)
evar.fix(value(mem[idx] if mem.is_indexed() else mem))
for con in eblock.component_data_objects(Constraint, active=True):
# we expect to find equality constraints with one linear variable
if not con.equality:
# We assume every constraint here is an equality.
# This will only be False if the transformation changes
# or if the user puts something unexpected on the eblock.
raise RuntimeError(
"Found inequality constraint '%s'. Please do not modify "
"the expanded block." % con.name)
repn = generate_standard_repn(con.body)
if repn.is_fixed():
# the port member's peer was already fixed
if abs(value(con.lower) - repn.constant) > eq_tol:
raise RuntimeError(
"Found connected ports '%s' and '%s' both with fixed "
"but different values (by > %s) for constraint '%s'" %
(src, dest, eq_tol, con.name))
continue
if not (repn.is_linear() and len(repn.linear_vars) == 1):
raise RuntimeError(
"Constraint '%s' had more than one free variable when "
"trying to pass a value to its destination. Please fix "
"more variables before passing across this arc." % con.name)
# fix the value of the single variable to satisfy the constraint
# con.lower is usually a NumericConstant but call value on it
# just in case it is something else
val = (value(con.lower) - repn.constant) / repn.linear_coefs[0]
var = repn.linear_vars[0]
fixed_inputs[dest_unit].add(var)
c_1 = []
c_2 = []
for loc_tech_carrier in loc_tech_carriers_1:
carrier_ratio_1 = get_param(
backend_model, 'carrier_ratios', (primary_tier, loc_tech_carrier, timestep)
)
if po.value(carrier_ratio_1) != 0:
c_1.append(
decision_variable[loc_tech_carrier, timestep] / carrier_ratio_1
)
for loc_tech_carrier in loc_tech_carriers_2:
carrier_ratio_2 = get_param(
backend_model, 'carrier_ratios', (tier, loc_tech_carrier, timestep)
)
if po.value(carrier_ratio_2) != 0:
c_2.append(
decision_variable[loc_tech_carrier, timestep] / carrier_ratio_2
)
if len(c_2) == 0:
return po.Constraint.Skip
else:
return sum(c_1) == sum(c_2)
# TODO check that status is actually ok and everything is feasible
config.logger.info(
'Unable to optimize MILP master problem '
'within time limit. '
'Using current solver feasible solution.')
copy_var_list_values(
m.MindtPy_utils.variable_list,
solve_data.working_model.MindtPy_utils.variable_list,
config)
if MindtPy.obj.sense == minimize:
solve_data.LB = max(
value(MindtPy.obj.expr), solve_data.LB)
solve_data.LB_progress.append(solve_data.LB)
else:
solve_data.UB = min(
value(MindtPy.obj.expr), solve_data.UB)
solve_data.UB_progress.append(solve_data.UB)
config.logger.info(
'MIP %s: OBJ: %s LB: %s UB: %s'
% (solve_data.mip_iter, value(MindtPy.obj.expr),
solve_data.LB, solve_data.UB))
elif (master_terminate_cond is tc.other and
results.solution.status is SolutionStatus.feasible):
# load the solution and suppress the warning message by setting
# solver status to ok.
config.logger.info(
'MILP solver reported feasible solution, '
'but not guaranteed to be optimal.')
copy_var_list_values(
m.MindtPy_utils.variable_list,
solve_data.working_model.MindtPy_utils.variable_list,
config)
# Now that we know who we need to disaggregate, we will do it
# while we also transform the disjuncts.
or_expr = 0
for disjunct in obj.disjuncts:
or_expr += disjunct.indicator_var
self._transform_disjunct(disjunct, transBlock, varSet,
localVars[disjunct])
orConstraint.add(index, (or_expr, 1))
for i, var in enumerate(varSet):
disaggregatedExpr = 0
for disjunct in obj.disjuncts:
if 'chull' not in disjunct._gdp_transformation_info:
if not disjunct.indicator_var.is_fixed() \
or value(disjunct.indicator_var) != 0:
raise RuntimeError(
"GDP chull: disjunct was not relaxed, but "
"does not appear to be correctly deactivated.")
continue
disaggregatedVar = disjunct._gdp_transformation_info['chull'][
'disaggregatedVars'][var]
disaggregatedExpr += disaggregatedVar
if type(index) is tuple:
consIdx = index + (i,)
elif parent_component.is_indexed():
consIdx = (index,) + (i,)
else:
consIdx = i
disaggregationConstraint.add(
consIdx,