Beispiel #1
0
 def test_integer_to_binary2(self):
     """Test integer to binary variables 2"""
     mod = QuadraticProgram()
     mod.integer_var(name='x', lowerbound=0, upperbound=1)
     mod.integer_var(name='y', lowerbound=0, upperbound=1)
     mod.minimize(1, {'x': 1}, {('x', 'y'): 2})
     mod.linear_constraint({'x': 1}, '==', 1)
     mod.quadratic_constraint({'x': 1}, {('x', 'y'): 2}, '==', 1)
     mod2 = IntegerToBinary().convert(mod)
     self.assertListEqual([e.name + '@0' for e in mod.variables],
                          [e.name for e in mod2.variables])
     self.assertDictEqual(mod.objective.linear.to_dict(),
                          mod2.objective.linear.to_dict())
     self.assertDictEqual(mod.objective.quadratic.to_dict(),
                          mod2.objective.quadratic.to_dict())
     self.assertEqual(mod.get_num_linear_constraints(),
                      mod2.get_num_linear_constraints())
     for cst, cst2 in zip(mod.linear_constraints, mod2.linear_constraints):
         self.assertDictEqual(cst.linear.to_dict(), cst2.linear.to_dict())
     self.assertEqual(mod.get_num_quadratic_constraints(),
                      mod2.get_num_quadratic_constraints())
     for cst, cst2 in zip(mod.quadratic_constraints,
                          mod2.quadratic_constraints):
         self.assertDictEqual(cst.linear.to_dict(), cst2.linear.to_dict())
         self.assertDictEqual(cst.quadratic.to_dict(),
                              cst2.quadratic.to_dict())
Beispiel #2
0
    def test_converter_list(self):
        """Test converter list"""
        op = QuadraticProgram()
        op.integer_var(0, 3, "x")
        op.binary_var('y')

        op.maximize(linear={'x': 1, 'y': 2})
        op.linear_constraint(linear={
            'x': 1,
            'y': 1
        },
                             sense='LE',
                             rhs=3,
                             name='xy_leq')
        min_eigen_solver = NumPyMinimumEigensolver()
        # a single converter
        qp2qubo = QuadraticProgramToQubo()
        min_eigen_optimizer = MinimumEigenOptimizer(min_eigen_solver,
                                                    converters=qp2qubo)
        result = min_eigen_optimizer.solve(op)
        self.assertEqual(result.fval, 4)
        # a list of converters
        ineq2eq = InequalityToEquality()
        int2bin = IntegerToBinary()
        penalize = LinearEqualityToPenalty()
        converters = [ineq2eq, int2bin, penalize]
        min_eigen_optimizer = MinimumEigenOptimizer(min_eigen_solver,
                                                    converters=converters)
        self.assertEqual(result.fval, 4)
        with self.assertRaises(TypeError):
            invalid = [qp2qubo, "invalid converter"]
            MinimumEigenOptimizer(min_eigen_solver, converters=invalid)
 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()
     op2 = conv.convert(op)
     result = OptimizationResult(x=[0, 1, 1, 1, 1],
                                 fval=17,
                                 variables=op2.variables)
     new_result = conv.interpret(result)
     np.testing.assert_array_almost_equal(new_result.x, [0, 1, 5])
     self.assertEqual(new_result.fval, 17)
     self.assertListEqual(new_result.variable_names, ['x0', 'x1', 'x2'])
     self.assertDictEqual(new_result.variables_dict, {
         'x0': 0,
         'x1': 1,
         'x2': 5
     })
 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)
         result = converter.interpret(result)
         self.assertEqual(result.x[0], 10.9)
         self.assertListEqual(result.variable_names, ['c', 'x'])
         self.assertDictEqual(result.variables_dict, {'c': 10.9, 'x': 0})
     except NameError as ex:
         self.skipTest(str(ex))
Beispiel #5
0
    def test_converter_list(self):
        """Test converters list"""
        # Input.
        model = Model()
        x_0 = model.binary_var(name='x0')
        x_1 = model.binary_var(name='x1')
        model.maximize(-x_0+2*x_1)
        op = QuadraticProgram()
        op.from_docplex(model)

        # Get the optimum key and value.
        n_iter = 8
        # a single converter.
        qp2qubo = QuadraticProgramToQubo()
        gmf = GroverOptimizer(4, num_iterations=n_iter, quantum_instance=self.sv_simulator,
                              converters=qp2qubo)
        results = gmf.solve(op)
        self.validate_results(op, results)
        # a list of converters
        ineq2eq = InequalityToEquality()
        int2bin = IntegerToBinary()
        penalize = LinearEqualityToPenalty()
        converters = [ineq2eq, int2bin, penalize]
        gmf = GroverOptimizer(4, num_iterations=n_iter, quantum_instance=self.sv_simulator,
                              converters=converters)
        results = gmf.solve(op)
        self.validate_results(op, results)
        # invalid converters
        with self.assertRaises(TypeError):
            invalid = [qp2qubo, "invalid converter"]
            GroverOptimizer(4, num_iterations=n_iter,
                            quantum_instance=self.sv_simulator,
                            converters=invalid)
Beispiel #6
0
 def test_empty_problem(self):
     """ Test empty problem """
     op = QuadraticProgram()
     conv = InequalityToEquality()
     op = conv.convert(op)
     conv = IntegerToBinary()
     op = conv.convert(op)
     conv = LinearEqualityToPenalty()
     op = conv.convert(op)
     _, shift = op.to_ising()
     self.assertEqual(shift, 0.0)
Beispiel #7
0
 def test_empty_problem_deprecated(self):
     """ Test empty problem """
     op = QuadraticProgram()
     conv = InequalityToEquality()
     op = conv.encode(op)
     conv = IntegerToBinary()
     op = conv.encode(op)
     conv = LinearEqualityToPenalty()
     op = conv.encode(op)
     conv = QuadraticProgramToIsing()
     _, shift = conv.encode(op)
     self.assertEqual(shift, 0.0)
Beispiel #8
0
 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])
Beispiel #9
0
 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.encode(op)
     for x in op2.variables:
         self.assertEqual(x.vartype, Variable.Type.BINARY)
     dct = op2.objective.linear.to_dict()
     self.assertEqual(dct[2], 3)
     self.assertEqual(dct[3], 6)
     self.assertEqual(dct[4], 6)
Beispiel #10
0
    def test_empty_problem_deprecated(self):
        """ Test empty problem """
        try:
            warnings.filterwarnings(action="ignore",
                                    category=DeprecationWarning)
            op = QuadraticProgram()
            conv = InequalityToEquality()
            op = conv.encode(op)
            conv = IntegerToBinary()
            op = conv.encode(op)
            conv = LinearEqualityToPenalty()
            op = conv.encode(op)
            conv = QuadraticProgramToIsing()
            _, shift = conv.encode(op)
        finally:
            warnings.filterwarnings(action="always",
                                    category=DeprecationWarning)

        self.assertEqual(shift, 0.0)
Beispiel #11
0
 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)
Beispiel #12
0
 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 = {}
     linear['x0'] = 1
     linear['x1'] = 2
     linear['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.encode(op)
     result = OptimizationResult(x=[0, 1, 1, 1, 1], fval=17)
     new_result = conv.decode(result)
     self.assertListEqual(new_result.x, [0, 1, 5])
     self.assertEqual(new_result.fval, 17)
Beispiel #13
0
 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.encode(op)
         admm_params = ADMMParameters()
         qubo_optimizer = MinimumEigenOptimizer(NumPyMinimumEigensolver())
         continuous_optimizer = CplexOptimizer()
         solver = ADMMOptimizer(
             qubo_optimizer=qubo_optimizer,
             continuous_optimizer=continuous_optimizer,
             params=admm_params,
         )
         solution = solver.solve(op)
         solution = converter.decode(solution)
         self.assertEqual(solution.x[0], 10.9)
     except NameError as ex:
         self.skipTest(str(ex))