diff --git a/pyomo/contrib/pyros/master_problem_methods.py b/pyomo/contrib/pyros/master_problem_methods.py index aea5138f6ed..378b9c3f585 100644 --- a/pyomo/contrib/pyros/master_problem_methods.py +++ b/pyomo/contrib/pyros/master_problem_methods.py @@ -11,6 +11,7 @@ Functions for construction and solution of the PyROS master problem. """ +from pyomo.common.dependencies import numpy as np from pyomo.common.collections import ComponentMap, ComponentSet from pyomo.common.modeling import unique_component_name from pyomo.core import TransformationFactory @@ -579,24 +580,16 @@ def minimize_dr_vars(master_data): def get_master_dr_degree(master_data): """ - Determine DR polynomial degree to enforce based on - the iteration number and/or the presence of first-stage - equality constraints that depend on the decision rule variables. + Determine degree of the decision rule polynomials that should + be enforced given the current state of the master model's + uncertain parameter realizations. - If there are first-stage equality constraints that depend + Also, if there are first-stage equality constraints that depend on the decision rule variables, such as equalities derived from coefficient matching or discretization of state-variable - independent equalities, then the degree is set to + independent equalities, then the degree is always set to ``config.decision_rule_order``. - Otherwise, the degree is set to: - - - 0 if iteration number is 0 - - min(1, config.decision_rule_order) if iteration number - otherwise does not exceed number of effective - uncertain parameters - - min(2, config.decision_rule_order) otherwise. - Parameters ---------- master_data : MasterProblemData @@ -611,31 +604,65 @@ def get_master_dr_degree(master_data): if nom_scenario_blk.first_stage.dr_dependent_equality_cons: return master_data.config.decision_rule_order - if master_data.iteration == 0: + if not len(nom_scenario_blk.first_stage.decision_rule_vars): return 0 - elif master_data.iteration <= len(nom_scenario_blk.effective_uncertain_params): - return min(1, master_data.config.decision_rule_order) + + scenario_blks = master_data.master_model.scenarios + if len(scenario_blks) == 1 or master_data.config.decision_rule_order == 0: + return 0 + elif master_data.config.decision_rule_order == 1: + return 1 + elif master_data.config.decision_rule_order == 2: + # restricting quadratic decision rules to affine rules + # is nonconservative if (and only if) + # the unique sampled problem scenarios are affinely independent. + # to avoid conservatism, it is safer to err on the side of + # allowing quadratic decision rules + + # note: we are erring on the side of caution by + # using a zero deduplication tolerance. + # allowing scenarios that are nearly equal increases the + # scenario count and leads rank-based checks + # to err on side of affirming affine dependence + unique_scenarios = np.unique( + [ + [param.value for param in blk.effective_uncertain_params] + for blk in scenario_blks.values() + ], + axis=0, + ) + + return 1 + ( + # singleton set is always affinely independent + len(unique_scenarios) > 1 + and ( + # too many "unique" scenarios for affine independence + len(unique_scenarios) + >= 2 + len(nom_scenario_blk.effective_uncertain_dimensions) + or + # rank check reveals affine dependence + np.linalg.matrix_rank(unique_scenarios[1:] - unique_scenarios[0]) + != len(unique_scenarios) - 1 + ) + ) else: - return min(2, master_data.config.decision_rule_order) + raise ValueError( + f"Decision rule order {master_data.config.decision_rule_order} not supported." + ) def higher_order_decision_rule_efficiency(master_data): """ - Enforce DR coefficient variable efficiencies for - master problem-like formulation. + "Fix" a subset of the higher-order decision rule coefficients, + based on the current state of the master problem's added + scenarios and whether there are decision-rule-variable-dependent + equality constraints that were derived by the preprocessor's + equality constraint reformulations. Parameters ---------- master_data : MasterProblemData Master problem data. - - Note - ---- - The DR coefficient variable efficiencies consist of - setting the degree of the DR polynomial expressions - by fixing the appropriate variables to 0. The degree - to be set depends on the iteration number; - see ``get_master_dr_degree``. """ order_to_enforce = get_master_dr_degree(master_data) enforce_dr_degree( @@ -775,8 +802,6 @@ def solver_call_master(master_data): solve_mode = "global" if config.solve_master_globally else "local" config.progress_logger.debug("Solving master problem") - higher_order_decision_rule_efficiency(master_data) - for idx, opt in enumerate(solvers): if idx > 0: config.progress_logger.debug( @@ -874,6 +899,13 @@ def solve_master(master_data): master_soln : MasterResults Master problem solve results. """ + # apply decision rule variable fixing here. + # note: the master feasibility and DR polishing models + # are later cloned from the master model, + # so the decision rule variable fixing + # is implicitly applied to those, as well. + higher_order_decision_rule_efficiency(master_data) + feasibility_problem_results = None time_out_after_feasibility = False if master_data.iteration > 0: @@ -937,6 +969,28 @@ def solve_master(self): def solve_dr_polishing(self): """ - Solve the DR polishing problem. + "Polish" the decision rules, as needed. + + Returns + ------- + polishing_solver_res : SolverResults or None + If the polishing problem was set up and solved, + the SolverResults object produced by the subsolver + is returned. Otherwise, None is returned. + polishing_successful : bool + True if polishing was deemed successful, False otherwise. """ - return minimize_dr_vars(self) + nom_scenario_blk = self.master_model.scenarios[0, 0] + if ( + # there are DR variables in the model + nom_scenario_blk.first_stage.decision_rule_vars + and ( + # there are unfixed non-static DR variables + len(self.master_model.scenarios) > 1 + or nom_scenario_blk.first_stage.dr_dependent_equality_cons + ) + ): + return minimize_dr_vars(self) + else: + # static DRs are considered always already "polished" + return None, True diff --git a/pyomo/contrib/pyros/pyros_algorithm_methods.py b/pyomo/contrib/pyros/pyros_algorithm_methods.py index fcb4c854fee..049758fa7a2 100644 --- a/pyomo/contrib/pyros/pyros_algorithm_methods.py +++ b/pyomo/contrib/pyros/pyros_algorithm_methods.py @@ -191,14 +191,7 @@ def ROSolver_iterative_solve(model_data): iterations=k + 1, ) - polishing_successful = True - polish_master_solution = ( - config.decision_rule_order != 0 - and nominal_master_blk.first_stage.decision_rule_vars - and k != 0 - ) - if polish_master_solution: - _, polishing_successful = master_data.solve_dr_polishing() + _, polishing_successful = master_data.solve_dr_polishing() # track variable values current_iter_var_data = get_variable_value_data( diff --git a/pyomo/contrib/pyros/tests/test_grcs.py b/pyomo/contrib/pyros/tests/test_grcs.py index 708360c1d3e..8b67fa0f7a6 100644 --- a/pyomo/contrib/pyros/tests/test_grcs.py +++ b/pyomo/contrib/pyros/tests/test_grcs.py @@ -1626,6 +1626,46 @@ def test_higher_order_decision_rules(self): msg="Returned termination condition is not return robust_optimal.", ) + @unittest.skipUnless(baron_license_is_valid, "BARON is not available and licensed.") + def test_quadratic_dr_fixing_rule_correct(self): + m = ConcreteModel() + m.q = Param(range(2), initialize=0, mutable=True) + # test consideration for effective uncertain parameters + m.qfix = Param(initialize=0, mutable=True) + m.z = Var() + m.obj = Objective(expr=m.z) + m.con1 = Constraint(expr=m.z <= sum(q**2 for q in m.q.values())) + m.con2 = Constraint(expr=m.z >= -sum((q + 2) ** 2 for q in m.q.values()) + 1) + m.con3 = Constraint(expr=m.z >= -sum((q - 2) ** 2 for q in m.q.values()) + 1) + res = SolverFactory("pyros").solve( + model=m, + first_stage_variables=[], + second_stage_variables=m.z, + uncertain_params=[m.q, m.qfix], + # define set to make only q effectively uncertain + uncertainty_set=BoxSet([[-2, 2]] * len(m.q) + [[0, 0]]), + local_solver="ipopt", + global_solver="baron", + decision_rule_order=2, + objective_focus="worst_case", + solve_master_globally=True, + bypass_local_separation=True, + robust_feasibility_tolerance=1e-4, + # to confirm the DR fixing rule is correct, + # just need to confirm robust infeasible termination + # does not occur before this many iterations. + # test is otherwise expensive + max_iter=5, + ) + self.assertIn( + res.pyros_termination_condition, + { + pyrosTerminationCondition.max_iter, + pyrosTerminationCondition.robust_optimal, + }, + ) + self.assertLessEqual(res.iterations, 5) + @unittest.skipUnless(scip_available, "Global NLP solver is not available.") def test_coefficient_matching_solve(self): # Write the deterministic Pyomo model @@ -2138,6 +2178,96 @@ def test_coefficient_matching_singleton_set(self): self.assertEqual(results2.iterations, 0) self.assertEqual(results2.final_objective_value, None) + @unittest.skipUnless(scip_available, "SCIP is not available.") + def test_coefficient_matching_measure_0_set(self): + ndim = 2 + m = ConcreteModel() + m.q = Param(range(ndim), initialize=0, mutable=True) + m.x = Var(range(ndim), initialize=0, bounds=(-2, 2)) + m.obj = Objective(expr=m.x[0]) + m.certain_eq = Constraint(expr=sum(m.x.values()) == 0) + m.p = Param(initialize=0, mutable=True) + m.uncertain_eq = Constraint( + # this constraint is subject to coefficient matching, + # since there are no state variables and there are + # uncertain parameters. + expr=sum(m.q[idx] * m.x[idx] for idx in range(ndim)) + == 0 + ) + + with LoggingIntercept(level=logging.DEBUG) as LOG: + res = SolverFactory("pyros").solve( + model=m, + first_stage_variables=m.x, + second_stage_variables=[], + uncertain_params=m.q, + # this set is a line segment (1D), so it + # has no interior points. + # therefore, coefficient matching + # of the above equality constraint + # should not take place + uncertainty_set=PolyhedralSet( + lhs_coefficients_mat=np.vstack( + [ + np.hstack( + [np.ones(ndim - 1)[:, np.newaxis], -np.eye(ndim - 1)] + ), + -np.hstack( + [np.ones(ndim - 1)[:, np.newaxis], -np.eye(ndim - 1)] + ), + np.eye(ndim), + -np.eye(ndim), + ] + ), + rhs_vec=np.hstack( + [ + np.zeros(ndim - 1), + np.zeros(ndim - 1), + np.ones(ndim), + np.zeros(ndim), + ] + ), + ), + local_solver="scip", + global_solver="scip", + ) + debug_msgs = LOG.getvalue() + self.assertRegex( + debug_msgs, + ( + r".*Equality constraint.*eq_con.*state.*independent.*as a polynomial.*" + r".*but the specified uncertainty set does not meet conditions" + ), + ) + self.assertEqual( + res.pyros_termination_condition, pyrosTerminationCondition.robust_feasible + ) + # if coefficient matching occurred, the objective would have + # been equal to 0 + self.assertEqual(res.final_objective_value, -2) + self.assertEqual(res.iterations, 1) + self.assertEqual(m.x[0].value, -2) + self.assertEqual(m.x[1].value, 2) + + # run again, now with box set, + # to confirm coefficient matching causes x = 0 + res = SolverFactory("pyros").solve( + model=m, + first_stage_variables=m.x, + second_stage_variables=[], + uncertain_params=m.q, + uncertainty_set=BoxSet([[0, 1]] * len(m.q)), + local_solver="scip", + global_solver="scip", + ) + self.assertEqual( + res.pyros_termination_condition, pyrosTerminationCondition.robust_feasible + ) + self.assertEqual(res.iterations, 1) + self.assertEqual(res.final_objective_value, 0) + self.assertEqual(m.x[0].value, 0) + self.assertEqual(m.x[1].value, 0) + @unittest.skipUnless(ipopt_available, "IPOPT not available") def test_pyros_certain_params_ipopt_degrees_of_freedom(self): """ diff --git a/pyomo/contrib/pyros/tests/test_master.py b/pyomo/contrib/pyros/tests/test_master.py index adc5737af96..451e50a73ba 100644 --- a/pyomo/contrib/pyros/tests/test_master.py +++ b/pyomo/contrib/pyros/tests/test_master.py @@ -55,7 +55,9 @@ logger = logging.getLogger(__name__) -def build_simple_model_data(objective_focus="worst_case", decision_rule_order=1): +def build_simple_model_data( + objective_focus="worst_case", decision_rule_order=1, uncertain_eq_con=False +): """ Test construction of master problem. """ @@ -65,7 +67,13 @@ def build_simple_model_data(objective_focus="worst_case", decision_rule_order=1) m.x2 = Var(bounds=[-1000, 1000], initialize=1) m.x3 = Var(bounds=[-1000, 1000], initialize=-3) m.con = Constraint(expr=exp(m.u - 1) - m.x1 - m.x2 * m.u - m.x3 * m.u**2 <= 0) - m.eq_con = Constraint(expr=m.x2 - 1 == 0) + if uncertain_eq_con: + # this will be coefficient matched if x2 + # is not a state variable + m.eq_con = Constraint(expr=m.x2 - m.u == 0) + else: + # this makes x2 effectively first-stage + m.eq_con = Constraint(expr=m.x2 - 1 == 0) m.obj = Objective(expr=m.x1 + m.x2 / 2 + m.x3 / 3) @@ -479,74 +487,129 @@ class TestHigherOrderDecisionRuleEfficiency(unittest.TestCase): Test efficiency for decision rules. """ - def test_higher_order_decision_rule_efficiency(self): + def test_higher_order_decision_rule_efficiency_affine_dr(self): + """ + Test higher-order decision rule efficiency. + """ + model_data = build_simple_model_data(decision_rule_order=1) + master_model = construct_initial_master_problem(model_data) + master_data = Bunch(master_model=master_model, config=model_data.config) + decision_rule_vars = master_data.master_model.scenarios[ + 0, 0 + ].first_stage.decision_rule_vars[0] + + # only one scenario block, so enforce static DR + higher_order_decision_rule_efficiency(master_data) + self.assertFalse(decision_rule_vars[0].fixed) + self.assertTrue(decision_rule_vars[1].fixed) + + add_scenario_block_to_master_problem( + master_data.master_model, + scenario_idx=[1, 0], + param_realization=[-0.4], + from_block=master_data.master_model.scenarios[0, 0], + clone_first_stage_components=False, + ) + # more than one block, so allow affine DR + higher_order_decision_rule_efficiency(master_data) + self.assertFalse(decision_rule_vars[0].fixed) + self.assertFalse(decision_rule_vars[1].fixed) + + def test_higher_order_decision_rule_efficiency_quad_dr(self): """ Test higher-order decision rule efficiency. """ model_data = build_simple_model_data(decision_rule_order=2) master_model = construct_initial_master_problem(model_data) - master_data = Bunch( - master_model=master_model, iteration=0, config=model_data.config + master_data = Bunch(master_model=master_model, config=model_data.config) + decision_rule_vars = master_data.master_model.scenarios[ + 0, 0 + ].first_stage.decision_rule_vars[0] + + # only one scenario block, so enforce static DR + higher_order_decision_rule_efficiency(master_data) + self.assertFalse(decision_rule_vars[0].fixed) + self.assertTrue(decision_rule_vars[1].fixed) + self.assertTrue(decision_rule_vars[2].fixed) + + add_scenario_block_to_master_problem( + master_data.master_model, + scenario_idx=[1, 0], + param_realization=[-0.4], + from_block=master_data.master_model.scenarios[0, 0], + clone_first_stage_components=False, + ) + # two scenario blocks: no rank loss if affine DR used + higher_order_decision_rule_efficiency(master_data) + self.assertFalse(decision_rule_vars[0].fixed) + self.assertFalse(decision_rule_vars[1].fixed) + self.assertTrue(decision_rule_vars[2].fixed) + + master_data.master_model.scenarios[1, 0].uncertain_params[0].set_value(0.4) + # only one unique scenario: no rank loss if affine DR used + higher_order_decision_rule_efficiency(master_data) + self.assertFalse(decision_rule_vars[0].fixed) + self.assertFalse(decision_rule_vars[1].fixed) + self.assertTrue(decision_rule_vars[2].fixed) + + master_data.master_model.scenarios[1, 0].uncertain_params[0].set_value(-0.4) + + add_scenario_block_to_master_problem( + master_data.master_model, + scenario_idx=[2, 0], + param_realization=[0.0], + from_block=master_data.master_model.scenarios[0, 0], + clone_first_stage_components=False, + ) + # with this combo of parameter realizations, + # there is rank reduction if affine DR used, + # so use quadratic DR + higher_order_decision_rule_efficiency(master_data) + self.assertFalse(decision_rule_vars[0].fixed) + self.assertFalse(decision_rule_vars[1].fixed) + self.assertFalse(decision_rule_vars[2].fixed) + + master_data.master_model.scenarios[2, 0].uncertain_params[0].set_value(0.4) + # with this new combo of parameter realizations, + # there is no rank reduction if affine DR used, + # so use affine DR + higher_order_decision_rule_efficiency(master_data) + self.assertFalse(decision_rule_vars[0].fixed) + self.assertFalse(decision_rule_vars[1].fixed) + self.assertTrue(decision_rule_vars[2].fixed) + + def test_higher_order_decision_rule_efficiency_d_eq_cons(self): + """ + Test higher-order decision rule efficiency + when there are d-dependent equality constraints + """ + model_data = build_simple_model_data( + decision_rule_order=2, uncertain_eq_con=True ) + master_model = construct_initial_master_problem(model_data) + master_data = Bunch(master_model=master_model, config=model_data.config) decision_rule_vars = master_data.master_model.scenarios[ 0, 0 ].first_stage.decision_rule_vars[0] + # since there are d-dependent constraints + # due to coefficient matching, + # all DR variables are unfixed + higher_order_decision_rule_efficiency(master_data) + self.assertFalse(decision_rule_vars[0].fixed) + self.assertFalse(decision_rule_vars[1].fixed) + self.assertFalse(decision_rule_vars[2].fixed) - for iter_num in range(4): - master_data.iteration = iter_num - higher_order_decision_rule_efficiency(master_data) - self.assertFalse( - decision_rule_vars[0].fixed, - msg=( - f"DR Var {decision_rule_vars[1].name!r} should not " - f"be fixed by efficiency in iteration {iter_num}" - ), - ) - if iter_num == 0: - self.assertTrue( - decision_rule_vars[1].fixed, - msg=( - f"DR Var {decision_rule_vars[1].name!r} should " - f"be fixed by efficiency in iteration {iter_num}" - ), - ) - self.assertTrue( - decision_rule_vars[2].fixed, - msg=( - f"DR Var {decision_rule_vars[2].name!r} should " - f"be fixed by efficiency in iteration {iter_num}" - ), - ) - elif iter_num <= len(master_data.config.uncertain_params): - self.assertFalse( - decision_rule_vars[1].fixed, - msg=( - f"DR Var {decision_rule_vars[1].name!r} should not " - f"be fixed by efficiency in iteration {iter_num}" - ), - ) - self.assertTrue( - decision_rule_vars[2].fixed, - msg=( - f"DR Var {decision_rule_vars[2].name!r} should " - f"be fixed by efficiency in iteration {iter_num}" - ), - ) - else: - self.assertFalse( - decision_rule_vars[1].fixed, - msg=( - f"DR Var {decision_rule_vars[1].name!r} should not " - f"be fixed by efficiency in iteration {iter_num}" - ), - ) - self.assertFalse( - decision_rule_vars[2].fixed, - msg=( - f"DR Var {decision_rule_vars[2].name!r} should not " - f"be fixed by efficiency in iteration {iter_num}" - ), - ) + add_scenario_block_to_master_problem( + master_data.master_model, + scenario_idx=[1, 0], + param_realization=[-0.4], + from_block=master_data.master_model.scenarios[0, 0], + clone_first_stage_components=False, + ) + higher_order_decision_rule_efficiency(master_data) + self.assertFalse(decision_rule_vars[0].fixed) + self.assertFalse(decision_rule_vars[1].fixed) + self.assertFalse(decision_rule_vars[2].fixed) class TestSolveMaster(unittest.TestCase): diff --git a/pyomo/contrib/pyros/tests/test_preprocessor.py b/pyomo/contrib/pyros/tests/test_preprocessor.py index e5f833cb649..2a6c39e9f35 100644 --- a/pyomo/contrib/pyros/tests/test_preprocessor.py +++ b/pyomo/contrib/pyros/tests/test_preprocessor.py @@ -2193,6 +2193,7 @@ def test_coefficient_matching_correct_constraints_added(self): model_data.working_model.all_nonadjustable_variables = list( ep.first_stage_variables ) + model_data.working_model.effective_uncertain_dimensions = [0] robust_infeasible = reformulate_state_var_independent_eq_cons(model_data) @@ -2262,6 +2263,7 @@ def test_reformulate_nonlinear_state_var_independent_eq_con(self): # we want only one of the constraints to be 'nonlinear' # change eq_con_2 to give a valid matching constraint wm.second_stage.equality_cons["eq_con_2"].set_value(m.u * (m.x1 - 1) == 0) + wm.effective_uncertain_dimensions = [0] with LoggingIntercept(level=logging.DEBUG) as LOG: robust_infeasible = reformulate_state_var_independent_eq_cons(model_data) @@ -2438,6 +2440,7 @@ def test_coefficient_matching_robust_infeasible_proof(self): model_data.working_model.all_nonadjustable_variables = list( ep.first_stage_variables ) + model_data.working_model.effective_uncertain_dimensions = [0] with LoggingIntercept(level=logging.INFO) as LOG: robust_infeasible = reformulate_state_var_independent_eq_cons(model_data) diff --git a/pyomo/contrib/pyros/tests/test_uncertainty_sets.py b/pyomo/contrib/pyros/tests/test_uncertainty_sets.py index 0011ecddc54..4eb3e7853ce 100644 --- a/pyomo/contrib/pyros/tests/test_uncertainty_sets.py +++ b/pyomo/contrib/pyros/tests/test_uncertainty_sets.py @@ -96,6 +96,17 @@ def bounded_and_nonempty_check(test, unc_set): test.assertTrue(unc_set.is_nonempty(config=CONFIG), "Set is empty.") +class UnknownSolver: + def available(self, exception_flag=None): + return True + + def solve(self, model, *args, **kwargs): + res = SolverResults() + res.solver.termination_condition = TerminationCondition.unknown + res.solver.status = SolverStatus.warning + return res + + class TestBoxSet(unittest.TestCase): """ Tests for the BoxSet. @@ -487,6 +498,46 @@ def test_is_coordinate_fixed(self): box_set._is_coordinate_fixed(config=Bunch()), [False, False, False] ) + def test_has_positive_measure(self): + """ + Tests for BoxSet positive measure checks. + """ + # compare bounds + self.assertTrue(BoxSet([[0.0, 2], [1, 2]])._has_positive_measure(Bunch())) + self.assertTrue(BoxSet([[0.0, 1.1e-8], [1, 2]])._has_positive_measure(Bunch())) + self.assertFalse(BoxSet([[0.0, 9e-9], [1, 2]])._has_positive_measure(Bunch())) + self.assertFalse(BoxSet([[0.0, 2], [2, 1]])._has_positive_measure(Bunch())) + + # check fixed values vs bounds + self.assertTrue( + BoxSet([[0.0, 2], [1, 2]])._has_positive_measure(Bunch(), {0: 1}) + ) + self.assertTrue( + BoxSet([[0.0, 2], [1, 2]])._has_positive_measure(Bunch(), {0: -1e-8}) + ) + self.assertFalse( + BoxSet([[0.0, 2], [1, 2]])._has_positive_measure(Bunch(), {0: -1e-7}) + ) + self.assertTrue( + BoxSet([[0.0, 2], [1, 2]])._has_positive_measure(Bunch(), {1: 2 + 1e-8}) + ) + self.assertFalse( + BoxSet([[0.0, 2], [1, 2]])._has_positive_measure(Bunch(), {1: 2 + 1e-7}) + ) + self.assertTrue( + BoxSet([[0.0, 2], [1, 2]])._has_positive_measure(Bunch(), {1: 2, 0: -1e-8}) + ) + self.assertFalse( + BoxSet([[0.0, 2], [1, 2]])._has_positive_measure(Bunch(), {1: 2, 0: -1e-7}) + ) + # compare only unfixed coordinate bounds + self.assertTrue( + BoxSet([[0.0, 1.1e-8], [1, 1]])._has_positive_measure(Bunch(), {1: 1}) + ) + self.assertFalse( + BoxSet([[0.0, 9.9e-9], [1, 1]])._has_positive_measure(Bunch(), {1: 1}) + ) + class TestBudgetSet(unittest.TestCase): """ @@ -839,6 +890,94 @@ def test_is_coordinate_fixed(self): buset._is_coordinate_fixed(config=Bunch()), [False, True, False] ) + def test_has_positive_measure(self): + """ + Tests for BudgetSet positive measure checks. + """ + # budgets allow nonzero deviations + self.assertTrue( + BudgetSet([[1, 0, 1], [1, 1, 0]], [2, 2], [1] * 3)._has_positive_measure( + Bunch() + ) + ) + # budgets large enough to allow nonzer odeviations + self.assertTrue( + BudgetSet([[1, 0, 1], [1, 1, 0]], [1, 1e-8], [1] * 3)._has_positive_measure( + Bunch() + ) + ) + # zero budgets disallow nonzero deviations + self.assertFalse( + BudgetSet([[1, 0, 1], [1, 1, 0]], [0, 0], [1] * 3)._has_positive_measure( + Bunch() + ) + ) + # budgets not considered large enough to allow nonzero deviations + self.assertFalse( + BudgetSet([[1, 0, 1], [1, 1, 0]], [1, 9e-9], [0] * 3)._has_positive_measure( + Bunch() + ) + ) + + # fixed coordinates agree with set data + self.assertTrue( + BudgetSet([[1, 0, 1], [1, 1, 0]], [2, 2], [0] * 3)._has_positive_measure( + Bunch(), {1: 0} + ) + ) + # fixed coordinates agree well enough with set data + self.assertTrue( + BudgetSet([[1, 0, 1], [1, 1, 0]], [2, 2], [0] * 3)._has_positive_measure( + Bunch(), {1: -1e-8} + ) + ) + # fixed coordinates are too far below origin + self.assertFalse( + BudgetSet([[1, 0, 1], [1, 1, 0]], [2, 2], [0] * 3)._has_positive_measure( + Bunch(), {1: -1e-7} + ) + ) + # fixed coordinates effectively limit budgets + # to disallow nonzero deviations + self.assertFalse( + BudgetSet([[1, 0, 1], [1, 1, 0]], [2, 2], [0] * 3)._has_positive_measure( + Bunch(), {1: 2} + ) + ) + # fixed coordinates are fine enough so that effective budget + # allows nonzero deviations + self.assertTrue( + BudgetSet([[1, 0, 1], [1, 1, 0]], [2, 2], [0] * 3)._has_positive_measure( + Bunch(), {1: 2 - 1e-6} + ) + ) + # fixed coordinates are not fine enough so that effective budget + # allows nonzero deviations + self.assertFalse( + BudgetSet([[1, 0, 1], [1, 1, 0]], [2, 2], [0] * 3)._has_positive_measure( + Bunch(), {1: 2} + ) + ) + # zero budgets don't restrict unrelated unfixed coordinates + # to origin + self.assertTrue( + BudgetSet([[1, 0, 1], [1, 1, 0]], [2, 0], [0.1] * 3)._has_positive_measure( + Bunch(), {0: 0.1, 1: 0.1} + ) + ) + # all coordinates are fixed to feasible values + self.assertTrue( + BudgetSet([[1, 0, 1], [1, 1, 0]], [2, 0], [0.1] * 3)._has_positive_measure( + Bunch(), {0: 0.1, 2: 0.1 + 2, 1: 0.1} + ) + ) + # some coordinates are fixed to infeasible values + self.assertFalse( + BudgetSet([[1, 0, 1], [1, 1, 0]], [2, 0], [0.1] * 3)._has_positive_measure( + Bunch(), {0: 0.1, 2: 0.1 + 2 + 1e-6, 1: 0.1} + ) + ) + class TestFactorModelSet(unittest.TestCase): """ @@ -1323,6 +1462,85 @@ def test_is_coordinate_fixed(self): fset._is_coordinate_fixed(config=Bunch()), [False, False, True] ) + @unittest.skipUnless(baron_available, "BARON is not available.") + def test_has_positive_measure(self): + """ + Tests for FactorModelSet positive measure checks. + """ + self.assertTrue( + FactorModelSet([1, 1.5], 2, [[1, 2], [2, 1]], 0.1)._has_positive_measure( + Bunch() + ) + ) + # beta*F considered large enough for nonzero deviations + self.assertTrue( + FactorModelSet([1, 1.5], 2, [[1, 2], [2, 1]], 5e-9)._has_positive_measure( + Bunch() + ) + ) + # beta*F considered too small for nonzero deviations + self.assertFalse( + FactorModelSet([1, 1.5], 2, [[1, 2], [2, 1]], 4.9e-9)._has_positive_measure( + Bunch() + ) + ) + # some, but not all, coordinates fixed, + # rank check passes, and restricted latent domain has strictly + # feasible points + self.assertTrue( + FactorModelSet([1, 1.5], 2, [[1, 2], [2, 1]], 1)._has_positive_measure( + Bunch(global_solver=SolverFactory("baron")), {0: 1} + ) + ) + # some, but not all, coordinates fixed, + # rank check passes, but fixing restricts latent factor domain + # to boundary points + self.assertFalse( + FactorModelSet([1, 1.5], 2, [[1, 0], [2, 1]], 1)._has_positive_measure( + Bunch(global_solver=SolverFactory("baron")), {0: 3} + ) + ) + # some, but not all, coordinates fixed, + # rank check passes, but fixing restricts latent factor domain + # to empty set (so slack model infeasible) + self.assertFalse( + FactorModelSet([1, 1.5], 2, [[1, 0], [2, 1]], 1)._has_positive_measure( + Bunch(global_solver=SolverFactory("baron")), {0: 4} + ) + ) + # some, but not all, coordinates fixed, + # rank check passes, but beta*F too small + # to allow latent space to have tolerated interior points + self.assertFalse( + FactorModelSet([1, 1.5], 2, [[1, 2], [2, 1]], 4.9e-9)._has_positive_measure( + Bunch(global_solver=SolverFactory("baron")), {0: 1} + ) + ) + # some, but not all, coordinates fixed, but rank check fails + self.assertFalse( + FactorModelSet([1, 1.5], 2, [[1, 2], [1, 2]], 1)._has_positive_measure( + Bunch(), {0: 1} + ) + ) + # some, but not all, coordinates fixed, but rank check fails + self.assertFalse( + FactorModelSet( + [1, 1.5, 0], 2, [[1, 0], [1, 2], [2, 4]], 1 + )._has_positive_measure(Bunch(), {0: 1}) + ) + # all coordinates are fixed to feasible point + self.assertTrue( + FactorModelSet([1, 1.5], 2, [[1, 2], [2, 1]], 1)._has_positive_measure( + Bunch(), {1: 1.5 + 1, 0: 1} + ) + ) + # all coordinates are fixed to point outside set + self.assertFalse( + FactorModelSet([1, 1.5], 2, [[1, 0], [0, 1]], 1)._has_positive_measure( + Bunch(), {1: 1.5 + 1 + 1e-6, 0: 1} + ) + ) + class TestIntersectionSet(unittest.TestCase): """ @@ -1950,6 +2168,35 @@ def test_intersection_discrete_set(self): self.assertFalse(uq.auxiliary_vars) self.assertFalse(uq.uncertainty_cons) + def test_has_positive_measure(self): + """ + Tests for IntersectionSet positive measure checks. + """ + # all coordinates fixed to point in set + self.assertTrue( + IntersectionSet( + BoxSet([[1, 2], [0, 2]]), AxisAlignedEllipsoidalSet([1, 2], [2, 3]) + )._has_positive_measure(Bunch(), {1: 2, 0: 1.0}) + ) + # all coordinates fixed to point out of set + self.assertFalse( + IntersectionSet( + BoxSet([[1, 2], [0, 2]]), AxisAlignedEllipsoidalSet([1, 2], [2, 3]) + )._has_positive_measure(Bunch(), {1: 2, 0: 5}) + ) + # no coordinates fixed + self.assertFalse( + IntersectionSet( + BoxSet([[1, 2], [0, 2]]), AxisAlignedEllipsoidalSet([0, 0], [2, 2]) + )._has_positive_measure(Bunch()) + ) + # some but not all coordinates fixed + self.assertFalse( + IntersectionSet( + BoxSet([[1, 2], [0, 2]]), AxisAlignedEllipsoidalSet([0, 0], [2, 2]) + )._has_positive_measure(Bunch(), {0: 2}) + ) + class TestCardinalitySet(unittest.TestCase): """ @@ -2324,6 +2571,113 @@ def test_is_coordinate_fixed(self): cset._is_coordinate_fixed(config=Bunch()), [False, False, True] ) + def test_has_positive_measure(self): + """ + Tests for CardinalitySet positive measure checks. + """ + # octahedron + self.assertTrue( + CardinalitySet([0, 0], 1, [1, 1], [1, 1])._has_positive_measure(Bunch()) + ) + # gamma large enough to allow deviations + self.assertTrue( + CardinalitySet([0, 0], 1e-8, [1, 1], [1, 1])._has_positive_measure(Bunch()) + ) + # gamma too small to allow deviations + self.assertFalse( + CardinalitySet([0, 0], 9e-9, [1, 1], [1, 1])._has_positive_measure(Bunch()) + ) + # nonzero deviations allowed + self.assertTrue( + CardinalitySet([0, 0], 1, [1e-8, 0], [0, 1])._has_positive_measure(Bunch()) + ) + self.assertTrue( + CardinalitySet([0, 0], 1, [0, 1], [1e-8, 0])._has_positive_measure(Bunch()) + ) + # nonzero deviations not allowed + self.assertFalse( + CardinalitySet([0, 0], 1, [1e-9, 0], [0, 1])._has_positive_measure(Bunch()) + ) + self.assertFalse( + CardinalitySet([0, 0], 1, [0, 1], [1e-9, 0])._has_positive_measure(Bunch()) + ) + + # some coordinates fixed to valid point. + # may or may not allow unfixed coordinates to deviate + self.assertTrue( + CardinalitySet([0, 0], 1, [1, 1], [0, 0])._has_positive_measure( + Bunch(), {1: 0} + ) + ) + self.assertTrue( + CardinalitySet([0, 0], 1, [1, 1], [0, 0])._has_positive_measure( + Bunch(), {1: 0.5} + ) + ) + self.assertFalse( + CardinalitySet([0, 0], 1, [1, 1], [0, 0])._has_positive_measure( + Bunch(), {1: 1} + ) + ) + self.assertTrue( + CardinalitySet([0, 0], 1, [1e-8, 0], [0, 0])._has_positive_measure( + Bunch(), {1: 0} + ) + ) + self.assertTrue( + CardinalitySet([0, 0], 1, [0, 0], [1e-8, 0])._has_positive_measure( + Bunch(), {1: 0} + ) + ) + self.assertFalse( + CardinalitySet([0, 0], 1, [0, 0], [1e-9, 0])._has_positive_measure( + Bunch(), {1: 0} + ) + ) + # coordinates fixed to valid point, but no deviations allowed + self.assertFalse( + CardinalitySet([0, 0], 1, [1, 1], [0, 0])._has_positive_measure( + Bunch(), {1: 1} + ) + ) + # coordinate fixed to value outside set + self.assertTrue( + CardinalitySet([0, 0], 1, [1, 1], [0, 0])._has_positive_measure( + Bunch(), {1: 1e-6} + ) + ) + + # coordinates fixed to point in set + self.assertTrue( + CardinalitySet([0, 0], 1, [0, 0], [0, 0])._has_positive_measure( + Bunch(), {1: 1e-8, 0: 0} + ) + ) + # coordinates fixed to point out of set + self.assertFalse( + CardinalitySet([0, 0], 1, [0, 0], [0, 0])._has_positive_measure( + Bunch(), {1: 1e-7, 0: 0} + ) + ) + # point outside set + self.assertFalse( + CardinalitySet([0, 0], 1, [1, 0], [0, 1])._has_positive_measure( + Bunch(), {1: 2, 0: 0.1} + ) + ) + # point outside set + self.assertFalse( + CardinalitySet([0, 0], 1, [1, 0], [0, 1])._has_positive_measure( + Bunch(), {1: 1 + 1e-4, 0: 0} + ) + ) + # point outside set + self.assertFalse( + CardinalitySet([0, 0], 1, [1, 0], [0, 1])._has_positive_measure( + Bunch(), {1: 0, 0: -1 - 1e-4} + ) + ) + class TestDiscreteScenarioSet(unittest.TestCase): """ @@ -2518,6 +2872,31 @@ def test_is_coordinate_fixed(self): dset._is_coordinate_fixed(config=Bunch()), [True, False, False] ) + def test_has_positive_measure(self): + """ + Tests for DiscreteScenarioSet positive measure checks. + """ + # all coordinates fixed to point inside set + self.assertTrue( + DiscreteScenarioSet([[0, 2], [3, 4]])._has_positive_measure( + Bunch(), {1: 2, 0: -1e-9} + ) + ) + # all coordinates fixed to point outside set + self.assertFalse( + DiscreteScenarioSet([[1, 2], [3, 4]])._has_positive_measure( + Bunch(), {1: 2, 0: -1e-8} + ) + ) + # no coordinates fixed + self.assertFalse( + DiscreteScenarioSet([[1, 2], [3, 4]])._has_positive_measure(Bunch()) + ) + # some but not all coordinates fixed + self.assertFalse( + DiscreteScenarioSet([[1, 2], [3, 4]])._has_positive_measure(Bunch(), {0: 0}) + ) + class TestAxisAlignedEllipsoidalSet(unittest.TestCase): """ @@ -2756,6 +3135,55 @@ def test_is_coordinate_fixed(self): aeset._is_coordinate_fixed(config=Bunch()), [False, False, True] ) + def test_has_positive_measure(self): + """ + Tests for AxisAlignedEllipsoidalSet positive measure checks. + """ + # unfixed half-lengths allow deviations + self.assertTrue( + AxisAlignedEllipsoidalSet([1, 1], [2, 3])._has_positive_measure(Bunch()) + ) + self.assertTrue( + AxisAlignedEllipsoidalSet([1, 1], [1e-8, 1e-8])._has_positive_measure( + Bunch() + ) + ) + self.assertTrue( + AxisAlignedEllipsoidalSet([1, 1], [1e-8, 0])._has_positive_measure( + Bunch(), {1: 1} + ) + ) + # fixed coordinates have maximal deviation + self.assertFalse( + AxisAlignedEllipsoidalSet([1, 1], [1, 2])._has_positive_measure( + Bunch(), {1: 3} + ) + ) + # fixed coordinates allow unfixed coordinates to deviate + self.assertTrue( + AxisAlignedEllipsoidalSet([1, 1], [1, 2])._has_positive_measure( + Bunch(), {1: 2.99} + ) + ) + # fixed coordinate values not feasible + self.assertFalse( + AxisAlignedEllipsoidalSet([1, 1], [1, 2])._has_positive_measure( + Bunch(), {1: 3.01} + ) + ) + # coordinates fixed to point in tset + self.assertFalse( + AxisAlignedEllipsoidalSet([1, 1], [1, 2])._has_positive_measure( + Bunch(), {1: 3.0, 0: 1.0} + ) + ) + # coordinates fixed to point not in set + self.assertFalse( + AxisAlignedEllipsoidalSet([1, 1], [1, 2])._has_positive_measure( + Bunch(), {1: 3.01, 0: 1.0} + ) + ) + class TestEllipsoidalSet(unittest.TestCase): """ @@ -3202,6 +3630,53 @@ def test_is_coordinate_fixed(self): eset.scale = 0 self.assertEqual(eset._is_coordinate_fixed(config=Bunch()), [True, True, True]) + def test_has_positive_measure(self): + """ + Tests for EllipsoidalSet positive measure checks. + """ + # nonzero scale + self.assertTrue( + EllipsoidalSet([0, 0, 0.0], np.diag([4, 1, 9]), 1)._has_positive_measure( + Bunch() + ) + ) + # scale large enough to allow deviations + self.assertTrue( + EllipsoidalSet([0, 0, 0.0], np.diag([4, 1, 9]), 1e-8)._has_positive_measure( + Bunch() + ) + ) + # scale too small to allow deviations + self.assertFalse( + EllipsoidalSet([0, 0, 0.0], np.diag([4, 1, 9]), 1e-9)._has_positive_measure( + Bunch() + ) + ) + + # coordinates fixed to allow unfixed nonzero deviations + self.assertTrue( + EllipsoidalSet([0, 0, 0.0], np.diag([4, 1, 9]))._has_positive_measure( + Bunch(), {1: 0, 2: 0} + ) + ) + self.assertTrue( + EllipsoidalSet([0, 0, 0.0], np.diag([4, 1, 9]))._has_positive_measure( + Bunch(), {1: 0.99, 2: 0} + ) + ) + # coordinate fixing does not allow nonzero deviations + self.assertFalse( + EllipsoidalSet([0, 0, 0.0], np.diag([4, 1, 9]))._has_positive_measure( + Bunch(), {1: 1, 2: 0} + ) + ) + # coordinates fixed to point inside set + self.assertTrue( + EllipsoidalSet([0, 0, 0.0], np.diag([4, 1, 9]))._has_positive_measure( + Bunch(), {1: 0, 2: 3, 0: 0} + ) + ) + class TestPolyhedralSet(unittest.TestCase): """ @@ -3480,16 +3955,6 @@ def test_is_nonempty(self): pset = PolyhedralSet(lhs_coefficients_mat=[[1], [-1]], rhs_vec=[2, -3]) self.assertFalse(pset.is_nonempty(config=CONFIG)) - class UnknownSolver: - def available(self, exception_flag=None): - return True - - def solve(self, model, *args, **kwargs): - res = SolverResults() - res.solver.termination_condition = TerminationCondition.unknown - res.solver.status = SolverStatus.warning - return res - # nonemptiness check fails as nomemptiness/emptiness could # not be deduced using this solver CONFIG.global_solver = UnknownSolver() @@ -3512,6 +3977,54 @@ def test_is_coordinate_fixed(self): pset._is_coordinate_fixed(config=Bunch(global_solver=baron)), [False, True] ) + @unittest.skipUnless(baron_available, "BARON is not available.") + def test_has_positive_measure(self): + """ + Tests for PolyhedralSet positive measure checks. + """ + # has interior point + self.assertTrue( + PolyhedralSet( + [[1, 0], [-1, 0], [0, 1], [0, -1]], [1.01, -1, 2.01, -2] + )._has_positive_measure(Bunch(global_solver=SolverFactory("baron"))) + ) + # has no interior point + self.assertFalse( + PolyhedralSet( + [[1, 0], [-1, 0], [0, 1], [0, -1]], [1, -1, 2, -2] + )._has_positive_measure(Bunch(global_solver=SolverFactory("baron"))) + ) + # slice has interior point + self.assertFalse( + PolyhedralSet( + [[1, 0], [-1, 0], [0, 1], [0, -1]], [1.01, -1, 2, -2] + )._has_positive_measure(Bunch(global_solver=SolverFactory("baron")), {1: 2}) + ) + # slice has no interior point + self.assertFalse( + PolyhedralSet( + [[1, 0], [-1, 0], [0, 1], [0, -1]], [1, -1, 2.01, -2] + )._has_positive_measure(Bunch(global_solver=SolverFactory("baron")), {1: 2}) + ) + # solver doesn't work + self.assertFalse( + PolyhedralSet( + [[1, 0], [-1, 0], [0, 1], [0, -1]], [1.01, -1, 2.01, -2] + )._has_positive_measure(Bunch(global_solver=UnknownSolver())) + ) + # coordinates fixed to point inside set + self.assertTrue( + PolyhedralSet( + [[1, 0], [-1, 0], [0, 1], [0, -1]], [1.01, -1, 2.01, -2] + )._has_positive_measure(Bunch(), {1: 2, 0: 1}) + ) + # 1D line segment: no interior points in ambient space + self.assertFalse( + PolyhedralSet( + [[1, -1], [-1, 1], [1, 0], [0, 1], [-1, 0], [0, -1]], [0, 0, 1, 1, 0, 0] + )._has_positive_measure(Bunch(global_solver=SolverFactory("baron"))) + ) + class TestCartesianProductSet(unittest.TestCase): """ @@ -4323,6 +4836,67 @@ def test_is_coordinate_fixed(self): [False, False, False], ) + def test_has_positive_measure(self): + """ + Tests for CartesianProductSet positive measure checks. + """ + # all factors have positive measure + self.assertTrue( + CartesianProductSet( + AxisAlignedEllipsoidalSet([0], [1]), + BoxSet([[0, 1], [2, 3], [1.5, 2]]), + CardinalitySet([0, 0], 1, [1.5, 2], [0, 0]), + )._has_positive_measure(Bunch()) + ) + # one factor with zero measure (singleton set) + self.assertFalse( + CartesianProductSet( + AxisAlignedEllipsoidalSet([0], [0]), + BoxSet([[0, 1], [2, 3], [1.5, 2]]), + CardinalitySet([0, 0], 1, [1.5, 2], [0, 0]), + )._has_positive_measure(Bunch()) + ) + # one factor has zero measure in one of its coordinates + self.assertFalse( + CartesianProductSet( + AxisAlignedEllipsoidalSet([0], [1]), + BoxSet([[0, 1], [3, 3], [1.5, 2]]), + CardinalitySet([0, 0], 1, [1.5, 2], [0, 0]), + )._has_positive_measure(Bunch(), {0: 0}) + ) + # positive measure with respect to unfixed coordinates + self.assertTrue( + CartesianProductSet( + AxisAlignedEllipsoidalSet([0], [0]), + BoxSet([[0, 1], [3, 3], [1.5, 2]]), + CardinalitySet([0, 0], 1, [1.5, 2], [0, 0]), + )._has_positive_measure(Bunch(), {2: 3, 0: 0}) + ) + # coordinates fixed to infeasible values + self.assertFalse( + CartesianProductSet( + AxisAlignedEllipsoidalSet([0], [0]), + BoxSet([[0, 1], [2, 3], [1.5, 2]]), + CardinalitySet([0, 0], 1, [1.5, 2], [0, 0]), + )._has_positive_measure(Bunch(), {1: 4}) + ) + # point in set + self.assertTrue( + CartesianProductSet( + AxisAlignedEllipsoidalSet([0], [0]), + BoxSet([[0, 1], [2, 3], [1.5, 2]]), + CardinalitySet([0, 0], 1, [1.5, 2], [0, 0]), + )._has_positive_measure(Bunch(), {1: 1, 3: 1.5, 4: 0, 5: 0, 0: 0, 2: 2.5}) + ) + # point not in set + self.assertFalse( + CartesianProductSet( + AxisAlignedEllipsoidalSet([0], [0]), + BoxSet([[0, 1], [2, 3], [1.5, 2]]), + CardinalitySet([0, 0], 1, [1.5, 2], [0, 0]), + )._has_positive_measure(Bunch(), {1: 1, 3: 1.5, 4: 0, 5: 3, 0: 0, 2: 2.5}) + ) + if __name__ == "__main__": unittest.main() diff --git a/pyomo/contrib/pyros/uncertainty_sets.py b/pyomo/contrib/pyros/uncertainty_sets.py index dda7dc45923..e0e152b8cbb 100644 --- a/pyomo/contrib/pyros/uncertainty_sets.py +++ b/pyomo/contrib/pyros/uncertainty_sets.py @@ -35,6 +35,7 @@ PARAM_IS_CERTAIN_ABS_TOL, PARAM_IS_CERTAIN_REL_TOL, POINT_IN_UNCERTAINTY_SET_TOL, + UNCERTAINTY_SET_MEASURE_TOL, copy_docstring, standardize_component_data, ) @@ -43,6 +44,7 @@ ConcreteModel, ConstraintList, NonNegativeReals, + Objective, Var, VarData, maximize, @@ -499,8 +501,9 @@ class UncertaintySet(metaclass=abc.ABCMeta): @abc.abstractmethod def dim(self): """ - int : Dimension of the uncertainty set (number of uncertain - parameters in a corresponding optimization model of interest). + int : Ambient dimension of the uncertainty set, i.e., + the number of coordinates used to specify a point in the + uncertainty set's ambient real space. """ ... @@ -1091,6 +1094,34 @@ def scenarios(self): """ raise NotImplementedError + def _has_positive_measure(self, config, fixed_coord_vals=None): + """ + Return True if a specified axis-aligned slice/section + of the uncertainty set is known to have a positive + Lebesgue measure (hypervolume) in the space of unfixed + coordinates, False otherwise. + + A sufficient condition is that the slice of the set + has an interior point in the unfixed coordinate space. + This is usually the condition that is checked, in practice. + + Parameters + ---------- + config : ConfigDict + PyROS solver options. + fixed_coord_vals : dict, optional + Maps the positional indices of fixed coordinates + to the values to which to fix the coordinates. + + Returns + ------- + bool + """ + if fixed_coord_vals and set(fixed_coord_vals.keys()) == set(range(self.dim)): + return self.point_in_set([fixed_coord_vals[idx] for idx in range(self.dim)]) + else: + return False + class UncertaintySetList(MutableSequence): """ @@ -1279,7 +1310,7 @@ def _validate(self, value, single_item=False): @property def dim(self): - """Dimension of all uncertainty sets contained in self.""" + """Ambient dimension of all uncertainty sets contained in self.""" return self._dim @@ -1385,7 +1416,7 @@ def bounds(self, val): @property def dim(self): """ - int : Dimension `N` of the box set. + int : Ambient dimension `N` of the box set. """ return len(self.bounds) @@ -1465,6 +1496,36 @@ def validate(self, config): if lb > ub: raise ValueError(f"Lower bound {lb} exceeds upper bound {ub}") + @copy_docstring(UncertaintySet._has_positive_measure) + def _has_positive_measure(self, config, fixed_coord_vals=None): + if fixed_coord_vals is None: + fixed_coord_vals = {} + fixed_coords = list(fixed_coord_vals.keys()) + unfixed_coords = list( + filter(lambda idx: idx not in set(fixed_coords), range(self.dim)) + ) + lower_bounds, upper_bounds = self.bounds[:, 0], self.bounds[:, 1] + return ( + # slice is nonempty: fixed coordinate lower bounds + # are satisfied + np.all( + lower_bounds[fixed_coords] - POINT_IN_UNCERTAINTY_SET_TOL + <= np.array(list(fixed_coord_vals.values())) + ) + # slice is nonempty: fixed coordinate upper bounds + # are satisfied + and np.all( + np.array(list(fixed_coord_vals.values())) + <= upper_bounds[fixed_coords] + POINT_IN_UNCERTAINTY_SET_TOL + ) + # all unfixed coordinates can deviate strictly from bounds. + # use tolerance conservatively + and np.all( + upper_bounds[unfixed_coords] - lower_bounds[unfixed_coords] + >= UNCERTAINTY_SET_MEASURE_TOL + ) + ) + class CardinalitySet(UncertaintySet): r""" @@ -1716,7 +1777,7 @@ def gamma(self, val): @property def dim(self): """ - int : Dimension `N` of the cardinality-constrained set. + int : Ambient dimension `N` of the cardinality-constrained set. """ return len(self.origin) @@ -1908,6 +1969,52 @@ def validate(self, config): f"(provided value {self.gamma})" ) + @copy_docstring(UncertaintySet._has_positive_measure) + def _has_positive_measure(self, config, fixed_coord_vals=None): + if fixed_coord_vals is None: + fixed_coord_vals = {} + fixed_coords = list(fixed_coord_vals.keys()) + unfixed_coords = list( + filter(lambda idx: idx not in set(fixed_coords), range(self.dim)) + ) + aux_vals = self.compute_auxiliary_uncertain_param_vals( + point=[ + ( + self.origin[idx] + if idx in set(unfixed_coords) + else fixed_coord_vals[idx] + ) + for idx in range(self.dim) + ] + ) + aux_pos_vals, aux_neg_vals = aux_vals[: self.dim], aux_vals[self.dim :] + max_unfixed_coord_devs = np.max( + [ + self.positive_deviation[unfixed_coords], + self.negative_deviation[unfixed_coords], + ], + axis=0, + ) + return ( + # auxiliary values for the fixed coordinates are feasible + # (otherwise, the slice is empty) + np.all(aux_pos_vals[fixed_coords] >= -POINT_IN_UNCERTAINTY_SET_TOL) + and np.all(aux_pos_vals[fixed_coords] <= 1 + POINT_IN_UNCERTAINTY_SET_TOL) + and np.all(aux_neg_vals[fixed_coords] >= -POINT_IN_UNCERTAINTY_SET_TOL) + and np.all(aux_neg_vals[fixed_coords] <= 1 + POINT_IN_UNCERTAINTY_SET_TOL) + # nonzero deviations allowed for individual unfixed coordinates. + # use tolerance conservatively + and np.all(max_unfixed_coord_devs >= UNCERTAINTY_SET_MEASURE_TOL) + # nonzero deviations of unfixed coordinates + # are not disallowed due to effective gamma. + # use tolerance conservatively + and ( + self.gamma + - (aux_pos_vals[fixed_coords] + aux_neg_vals[fixed_coords]).sum() + >= UNCERTAINTY_SET_MEASURE_TOL + ) + ) + class PolyhedralSet(UncertaintySet): r""" @@ -2055,7 +2162,7 @@ def rhs_vec(self, val): @property def dim(self): """ - int : Dimension `N` of the polyhedral set. + int : Ambient dimension `N` of the polyhedral set. """ return len(self.coefficients_mat[0]) @@ -2146,6 +2253,40 @@ def validate(self, config): # boundedness check super().validate(config) + @copy_docstring(UncertaintySet._has_positive_measure) + def _has_positive_measure(self, config, fixed_coord_vals=None): + # in case all coordinates are fixed + if fixed_coord_vals and set(fixed_coord_vals.keys()) == set(range(self.dim)): + return self.point_in_set([fixed_coord_vals[idx] for idx in range(self.dim)]) + + if fixed_coord_vals is None: + fixed_coord_vals = {} + + # set up and solve optimization problem to check for interior point + model = ConcreteModel() + model.param_vars = Var(range(self.dim)) + model.slack_var = Var(domain=NonNegativeReals) + model.slack_obj = Objective(expr=model.slack_var, sense=maximize) + uq = self.set_as_constraint(block=model, uncertain_params=model.param_vars) + for con in uq.uncertainty_cons: + if con.lower is not None: + raise ValueError( + f"{type(self)} constraint {con.name} has unexpected " + "lower bound expression." + ) + con.set_value((None, con.body + model.slack_var, con.upper)) + for fixed_idx, fixed_val in fixed_coord_vals.items(): + model.param_vars[fixed_idx].fix(fixed_val) + res = config.global_solver.solve(model, load_solutions=False) + if check_optimal_termination(res): + model.solutions.load_from(res) + # sufficient for presence of interior point. + # use tolerance conservatively + return model.slack_var.value >= UNCERTAINTY_SET_MEASURE_TOL + else: + # since solver does not let us know if there is interior point + return False + class BudgetSet(UncertaintySet): r""" @@ -2388,7 +2529,7 @@ def origin(self, val): @property def dim(self): """ - int : Dimension `N` of the budget set. + int : Ambient dimension `N` of the budget set. """ return self.budget_membership_mat.shape[1] @@ -2507,6 +2648,42 @@ def validate(self, config): "negative. Ensure all entries are nonnegative" ) + @copy_docstring(UncertaintySet._has_positive_measure) + def _has_positive_measure(self, config, fixed_coord_vals=None): + if fixed_coord_vals is None: + fixed_coord_vals = {} + fixed_coords = list(fixed_coord_vals.keys()) + fixed_coord_vals_arr = np.array(list(fixed_coord_vals.values())) + unfixed_coords = list( + filter(lambda idx: idx not in set(fixed_coords), range(self.dim)) + ) + is_unfixed_budget_mat_row_zeros = np.all( + self.budget_membership_mat[:, unfixed_coords] == 0, axis=1 + ) + effective_rhs_vec = self.budget_rhs_vec - self.budget_membership_mat[ + :, fixed_coords + ] @ (fixed_coord_vals_arr - self.origin[fixed_coords]) + return ( + # slice is nonempty: fixed coordinates are not below origin + np.all( + fixed_coord_vals_arr + >= self.origin[fixed_coords] - POINT_IN_UNCERTAINTY_SET_TOL + ) + # slice is nonempty: budget constraints involving only + # fixed coordinates are satisfiable + and np.all( + effective_rhs_vec[is_unfixed_budget_mat_row_zeros] + >= -POINT_IN_UNCERTAINTY_SET_TOL + ) + # budgets allow unfixed coordinates to have + # nonzero deviations from set's origin. + # use tolerance conservatively + and np.all( + effective_rhs_vec[~is_unfixed_budget_mat_row_zeros] + >= UNCERTAINTY_SET_MEASURE_TOL + ) + ) + class FactorModelSet(UncertaintySet): r""" @@ -2727,7 +2904,7 @@ def beta(self, val): @property def dim(self): """ - int : Dimension `N` of the factor model set. + int : Ambient dimension `N` of the factor model set. """ return len(self.origin) @@ -2925,6 +3102,86 @@ def validate(self, config): f"and 1 inclusive (provided value {beta})" ) + @copy_docstring(UncertaintySet._has_positive_measure) + def _has_positive_measure(self, config, fixed_coord_vals=None): + if not fixed_coord_vals: + # no coordinates fixed + return ( + # use tolerance conservatively + self.beta * self.number_of_factors >= UNCERTAINTY_SET_MEASURE_TOL + and ( + # full row rank + np.linalg.matrix_rank(self.psi_mat) + == self.psi_mat.shape[0] + >= self.psi_mat.shape[1] + ) + ) + elif set(fixed_coord_vals.keys()) == set(range(self.dim)): + # all coordinates fixed. check 0D slice is nonempty + return self.point_in_set([fixed_coord_vals[idx] for idx in range(self.dim)]) + elif ( + # for positive Lebesgue measure, it is necessary for + # the rows of psi_mat that correspond to unfixed coordinates + # to surjectively map the nullspace of the other rows + # of psi_mat. check ranks to determine this + np.linalg.matrix_rank(self.psi_mat) + != np.linalg.matrix_rank(self.psi_mat[list(fixed_coord_vals)]) + + (self.dim - len(fixed_coord_vals)) + ): + return False + else: + # the nullspace rank check passed. + # now solve a slack maximization model to + # check that the latent factor space has an interior point + # even after fixing of some of the factor set's coordinates + m = ConcreteModel() + m.param_vars = Var(range(self.dim)) + m.aux_vars = Var(range(self.number_of_factors)) + m.slack_var = Var(domain=NonNegativeReals) + m.slack_obj = Objective(expr=m.slack_var, sense=maximize) + + @m.Constraint(list(fixed_coord_vals.keys())) + def factor_eq_con(b, fixed_idx): + return ( + sum( + psi_val * aux_var + for psi_val, aux_var in zip( + self.psi_mat[fixed_idx], b.aux_vars.values() + ) + ) + == fixed_coord_vals[fixed_idx] - self.origin[fixed_idx] + ) + + @m.Constraint(range(self.number_of_factors)) + def factor_slack_con_lb(b, fac_idx): + return -1 + b.slack_var <= b.aux_vars[fac_idx] + + @m.Constraint(range(self.number_of_factors)) + def factor_slack_con_ub(b, fac_idx): + return b.aux_vars[fac_idx] <= 1 - b.slack_var + + @m.Constraint() + def factor_sum_slack_con_lb(b): + return -self.beta * self.number_of_factors + b.slack_var <= sum( + b.aux_vars.values() + ) + + @m.Constraint() + def factor_sum_slack_con_ub(b): + return ( + sum(b.aux_vars.values()) + <= self.beta * self.number_of_factors - b.slack_var + ) + + res = config.global_solver.solve(m, load_solutions=False) + if not check_optimal_termination(res): + # can't confirm sufficiency + return False + else: + m.solutions.load_from(res) + # use tolerance conservatively + return m.slack_var.value >= UNCERTAINTY_SET_MEASURE_TOL + class AxisAlignedEllipsoidalSet(UncertaintySet): r""" @@ -3058,7 +3315,7 @@ def half_lengths(self, val): @property def dim(self): """ - int : Dimension `N` of the axis-aligned ellipsoidal set. + int : Ambient dimension `N` of the axis-aligned ellipsoidal set. """ return len(self.center) @@ -3160,6 +3417,56 @@ def validate(self, config): "is negative. All half-lengths must be nonnegative" ) + @copy_docstring(UncertaintySet._has_positive_measure) + def _has_positive_measure(self, config, fixed_coord_vals=None): + if fixed_coord_vals is None: + fixed_coord_vals = {} + fixed_coords = list(fixed_coord_vals.keys()) + fixed_coord_vals_arr = np.array(list(fixed_coord_vals.values())) + resolved_coords = np.full(self.dim, np.nan) + resolved_coords[fixed_coords] = fixed_coord_vals_arr + is_fixed_zero_half_len = np.logical_and( + self.half_lengths == 0, np.isin(np.arange(self.dim), fixed_coords) + ) + is_fixed_nonzero_half_len = np.logical_and( + self.half_lengths > 0, np.isin(np.arange(self.dim), fixed_coords) + ) + unfixed_coords = list( + filter(lambda idx: idx not in set(fixed_coords), range(self.dim)) + ) + return ( + # slice is nonempty: + # fixed coordinates for which half-lengths are zero + # are equal to the central values (LB) + np.all( + self.center[is_fixed_zero_half_len] - POINT_IN_UNCERTAINTY_SET_TOL + <= resolved_coords[is_fixed_zero_half_len] + ) + # slice is nonempty: + # fixed coordinates for which half-lengths are zero + # are equal to the central values (UB) + and np.all( + resolved_coords[is_fixed_zero_half_len] + <= self.center[is_fixed_zero_half_len] + POINT_IN_UNCERTAINTY_SET_TOL + ) + # half-lengths don't prevent nonzero deviations of + # unfixed coordinates from center. + # use tolerance conservatively + and np.all(self.half_lengths[unfixed_coords] >= UNCERTAINTY_SET_MEASURE_TOL) + # fixed coordinates don't prevent nonzero deviations of + # unfixed coordinates from center. + # use tolerance conservatively + and ( + ( + resolved_coords[is_fixed_nonzero_half_len] + - self.center[is_fixed_nonzero_half_len] + ) + ** 2 + / self.half_lengths[is_fixed_nonzero_half_len] ** 2 + ).sum() + <= 1 - UNCERTAINTY_SET_MEASURE_TOL + ) + class EllipsoidalSet(UncertaintySet): r""" @@ -3406,7 +3713,7 @@ def gaussian_conf_lvl(self, val): @property def dim(self): """ - int : Dimension `N` of the ellipsoidal set. + int : Ambient dimension `N` of the ellipsoidal set. """ return len(self.center) @@ -3583,6 +3890,48 @@ def validate(self, config): else: raise + @copy_docstring(UncertaintySet._has_positive_measure) + def _has_positive_measure(self, config, fixed_coord_vals=None): + # in case all coordinates fixed + if fixed_coord_vals and set(fixed_coord_vals.keys()) == set(range(self.dim)): + return self.point_in_set([fixed_coord_vals[idx] for idx in range(self.dim)]) + + if not fixed_coord_vals: + # trivial case + return self.scale >= UNCERTAINTY_SET_MEASURE_TOL + + fixed_coords = list(fixed_coord_vals.keys()) + fixed_coord_vals_arr = np.array(list(fixed_coord_vals.values())) + unfixed_coords = list( + filter(lambda idx: idx not in set(fixed_coords), range(self.dim)) + ) + + inv_shape_cho_factor, lower = sp.linalg.cho_factor( + self.shape_matrix, lower=True + ) + inv_shape_mat = sp.linalg.cho_solve( + (inv_shape_cho_factor, lower), np.eye(self.dim) + ) + + mat_unf_unf = inv_shape_mat[np.ix_(unfixed_coords, unfixed_coords)] + mat_unf_fix = inv_shape_mat[np.ix_(unfixed_coords, fixed_coords)] + mat_fix_unf = inv_shape_mat[np.ix_(fixed_coords, unfixed_coords)] + mat_fix_fix = inv_shape_mat[np.ix_(fixed_coords, fixed_coords)] + + fixed_coord_devs = fixed_coord_vals_arr - self.center[fixed_coords] + + inv_mat_uu_cho_factor, lower_uu = sp.linalg.cho_factor(mat_unf_unf, lower=True) + inv_mat_unf_unf = sp.linalg.cho_solve( + (inv_mat_uu_cho_factor, lower_uu), np.eye(mat_unf_unf.shape[0]) + ) + return ( + fixed_coord_devs + @ (mat_fix_fix - mat_fix_unf @ inv_mat_unf_unf @ mat_unf_fix) + @ fixed_coord_devs + # apply tolerance conservatively + <= self.scale - UNCERTAINTY_SET_MEASURE_TOL + ) + class DiscreteScenarioSet(UncertaintySet): r""" @@ -3670,7 +4019,7 @@ def scenarios(self, val): @property def dim(self): """ - int : Dimension `N` of the discrete scenario set. + int : Ambient dimension `N` of the discrete scenario set. """ return len(self.scenarios[0]) @@ -3891,7 +4240,7 @@ def all_sets(self, val): @property def dim(self): """ - int : Dimension of the intersection set. + int : Ambient dimension of the intersection set. """ return self.all_sets[0].dim @@ -4205,7 +4554,7 @@ def type(self): @property def dim(self): """ - int : Dimension of the cartesian product set. + int : Ambient dimension of the Cartesian product set. """ return sum(uset.dim for uset in self._all_sets) @@ -4429,3 +4778,24 @@ def validate(self, config): finally: # ensure the config's state ultimately remains unchanged config.nominal_uncertain_param_vals = full_nom_param_vals + + @copy_docstring(UncertaintySet._has_positive_measure) + def _has_positive_measure(self, config, fixed_coord_vals=None): + if fixed_coord_vals is None: + fixed_coord_vals = {} + fixed_coord_idxs_arr = np.array(list(fixed_coord_vals.keys())) + for start_dim, stop_dim, uset in self._iterate_over_all_sets(): + if not uset._has_positive_measure( + config=config, + fixed_coord_vals={ + idx - start_dim: fixed_coord_vals[idx] + for idx in fixed_coord_idxs_arr[ + np.logical_and( + fixed_coord_idxs_arr >= start_dim, + fixed_coord_idxs_arr < stop_dim, + ) + ] + }, + ): + return False + return True diff --git a/pyomo/contrib/pyros/util.py b/pyomo/contrib/pyros/util.py index 6d2b2a37070..aa6777b6ee4 100644 --- a/pyomo/contrib/pyros/util.py +++ b/pyomo/contrib/pyros/util.py @@ -70,6 +70,7 @@ ABS_CON_CHECK_FEAS_TOL = 1e-5 PRETRIANGULAR_VAR_COEFF_TOL = 1e-6 POINT_IN_UNCERTAINTY_SET_TOL = 1e-8 +UNCERTAINTY_SET_MEASURE_TOL = 1e-8 DR_POLISHING_PARAM_PRODUCT_ZERO_TOL = 1e-10 TIC_TOC_SOLVE_TIME_ATTR = "pyros_tic_toc_time" @@ -2622,7 +2623,8 @@ def _reformulate_eq_con_continuous_uncertainty( visitor = setup_quadratic_expression_visitor(wrt=originally_unfixed_vars) expr_repn = visitor.walk_expression(con_expr_after_all_substitutions) - if expr_repn.nonlinear is not None: + effective_unc_set_is_matchable = None + if not (expr_is_matchable := expr_repn.nonlinear is None): config.progress_logger.debug( f"Equality constraint {ss_eq_con.name!r} " "is state-variable independent, but cannot be written " @@ -2634,7 +2636,29 @@ def _reformulate_eq_con_continuous_uncertainty( "of this constraint." "Recasting to two inequality constraints." ) + elif not ( + effective_unc_set_is_matchable := config.uncertainty_set._has_positive_measure( + config=config, + fixed_coord_vals={ + idx: config.nominal_uncertain_param_vals[idx] + for idx in filter( + lambda cidx: cidx + not in set(working_model.effective_uncertain_dimensions), + range(config.uncertainty_set.dim), + ) + }, + ) + ): + config.progress_logger.info( + f"Equality constraint {ss_eq_con.name!r} " + "is state-variable independent and can be written " + "as a polynomial in the uncertain parameters, " + "but the specified uncertainty set does not meet conditions for " + "exactness of a coefficient matching reformulation. " + "Recasting to two inequality constraints." + ) + if not (expr_is_matchable and effective_unc_set_is_matchable): # keeping this constraint as an equality is not appropriate, # as it effectively constrains the uncertain parameters # in the separation problems, since the effective DOF