def test_add_block_containing_single_variable(self): """ Test that the variable is added correctly to `solver_model`. """ model = ConcreteModel() opt = SolverFactory("cplex", solver_io="python") opt._set_instance(model) self.assertEqual(opt._solver_model.variables.get_num(), 0) self.assertEqual(opt._solver_model.variables.get_num_binary(), 0) model.X = Var(within=Binary) with unittest.mock.patch.object( opt._solver_model.variables, "add", wraps=opt._solver_model.variables.add) as wrapped_add_call: opt._add_block(model) self.assertEqual(wrapped_add_call.call_count, 1) self.assertEqual( wrapped_add_call.call_args, ({ "lb": [0], "names": ["x1"], "types": ["B"], "ub": [1] }, ), ) self.assertEqual(opt._solver_model.variables.get_num(), 1) self.assertEqual(opt._solver_model.variables.get_num_binary(), 1)
def test_add_block_containing_multiple_constraints(self): model = ConcreteModel() model.X = Var(within=Binary) opt = SolverFactory("cplex", solver_io="python") opt._set_instance(model) self.assertEqual(opt._solver_model.linear_constraints.get_num(), 0) model.B = Block() model.B.C1 = Constraint(expr=model.X == 1) model.B.C2 = Constraint(expr=model.X <= 1) model.B.C3 = Constraint(expr=model.X >= 1) con_interface = opt._solver_model.linear_constraints with unittest.mock.patch.object( con_interface, "add", wraps=con_interface.add) as wrapped_add_call: opt._add_block(model.B) self.assertEqual(wrapped_add_call.call_count, 1) self.assertEqual( wrapped_add_call.call_args, ({ "lin_expr": [[[0], (1, )], [[0], (1, )], [[0], (1, )]], "names": ["x2", "x3", "x4"], "range_values": [0.0, 0.0, 0.0], "rhs": [1.0, 1.0, 1.0], "senses": ["E", "L", "G"], }, ), ) self.assertEqual(opt._solver_model.linear_constraints.get_num(), 3)
def test_add_block_containing_multiple_variables(self): """ Test that: - The variable is added correctly to `solver_model` - The CPLEX `variables` interface is called only once - Fixed variable bounds are set correctly """ model = ConcreteModel() opt = SolverFactory("cplex", solver_io="python") opt._set_instance(model) self.assertEqual(opt._solver_model.variables.get_num(), 0) model.X1 = Var(within=Binary) model.X2 = Var(within=NonNegativeReals) model.X3 = Var(within=NonNegativeIntegers) model.X3.fix(5) with unittest.mock.patch.object( opt._solver_model.variables, "add", wraps=opt._solver_model.variables.add ) as wrapped_add_call: opt._add_block(model) self.assertEqual(wrapped_add_call.call_count, 1) self.assertEqual( wrapped_add_call.call_args, ( { "lb": [0, 0, 5], "names": ["x1", "x2", "x3"], "types": ["B", "C", "I"], "ub": [1, cplex.infinity, 5], }, ), ) self.assertEqual(opt._solver_model.variables.get_num(), 3)