def test_binary_to_integer(self): """Test binary to integer""" op = QuadraticProgram() for i in range(0, 2): op.binary_var(name="x{}".format(i)) op.integer_var(name="x2", lowerbound=0, upperbound=5) linear = {"x0": 1, "x1": 2, "x2": 1} op.maximize(0, linear, {}) linear = {} for x in op.variables: linear[x.name] = 1 op.linear_constraint(linear, Constraint.Sense.EQ, 6, "x0x1x2") conv = IntegerToBinary() _ = conv.convert(op) new_x = conv.interpret([0, 1, 1, 1, 1]) np.testing.assert_array_almost_equal(new_x, [0, 1, 5])
def test_integer_to_binary(self): """ Test integer to binary """ op = QuadraticProgram() for i in range(0, 2): op.binary_var(name='x{}'.format(i)) op.integer_var(name='x2', lowerbound=0, upperbound=5) linear = {} for i, x in enumerate(op.variables): linear[x.name] = i + 1 op.maximize(0, linear, {}) conv = IntegerToBinary() op2 = conv.convert(op) self.assertEqual(op2.get_num_vars(), 5) self.assertListEqual([x.vartype for x in op2.variables], [Variable.Type.BINARY] * 5) self.assertListEqual([x.name for x in op2.variables], ['x0', 'x1', 'x2@0', 'x2@1', 'x2@2']) dct = op2.objective.linear.to_dict() self.assertEqual(dct[2], 3) self.assertEqual(dct[3], 6) self.assertEqual(dct[4], 6)
def test_continuous_variable_decode(self): """Test decode func of IntegerToBinaryConverter for continuous variables""" mdl = Model("test_continuous_varable_decode") c = mdl.continuous_var(lb=0, ub=10.9, name="c") x = mdl.binary_var(name="x") mdl.maximize(c + x * x) op = from_docplex_mp(mdl) converter = IntegerToBinary() op = converter.convert(op) admm_params = ADMMParameters() qubo_optimizer = MinimumEigenOptimizer(NumPyMinimumEigensolver()) continuous_optimizer = CplexOptimizer() solver = ADMMOptimizer( qubo_optimizer=qubo_optimizer, continuous_optimizer=continuous_optimizer, params=admm_params, ) result = solver.solve(op) new_x = converter.interpret(result.x) self.assertEqual(new_x[0], 10.9)
def test_continuous_variable_decode(self): """ Test decode func of IntegerToBinaryConverter for continuous variables""" try: mdl = Model('test_continuous_varable_decode') c = mdl.continuous_var(lb=0, ub=10.9, name='c') x = mdl.binary_var(name='x') mdl.maximize(c + x * x) op = QuadraticProgram() op.from_docplex(mdl) converter = IntegerToBinary() op = converter.convert(op) admm_params = ADMMParameters() qubo_optimizer = MinimumEigenOptimizer(NumPyMinimumEigensolver()) continuous_optimizer = CplexOptimizer() solver = ADMMOptimizer( qubo_optimizer=qubo_optimizer, continuous_optimizer=continuous_optimizer, params=admm_params, ) result = solver.solve(op) new_x = converter.interpret(result.x) self.assertEqual(new_x[0], 10.9) except MissingOptionalLibraryError as ex: self.skipTest(str(ex))