示例#1
0
    def test_min_eigen_optimizer(self, config):
        """ Min Eigen Optimizer Test """

        # unpack configuration
        min_eigen_solver_name, backend, filename = config

        # get minimum eigen solver
        min_eigen_solver = self.min_eigen_solvers[min_eigen_solver_name]
        if backend:
            min_eigen_solver.quantum_instance = BasicAer.get_backend(backend)

        # construct minimum eigen optimizer
        min_eigen_optimizer = MinimumEigenOptimizer(min_eigen_solver)

        # load optimization problem
        problem = OptimizationProblem()
        problem.read(self.resource_path + filename)

        # solve problem with cplex
        cplex = CplexOptimizer()
        cplex_result = cplex.solve(problem)

        # solve problem
        result = min_eigen_optimizer.solve(problem)

        # analyze results
        self.assertAlmostEqual(cplex_result.fval, result.fval)
示例#2
0
    def test_get_linear_components(self):
        op = OptimizationProblem()
        op.variables.add(names=[str(i) for i in range(4)], types="B" * 4)
        q = op.quadratic_constraints
        z = [
            q.add(name=str(i),
                  lin_expr=[range(i), [1.0 * (j + 1.0) for j in range(i)]])
            for i in range(3)
        ]
        self.assertListEqual(z, [0, 1, 2])
        self.assertEqual(q.get_num(), 3)

        sp = q.get_linear_components(2)
        self.assertListEqual(sp.ind, [0, 1])
        self.assertListEqual(sp.val, [1.0, 2.0])

        sp = q.get_linear_components('0', 1)
        self.assertListEqual(sp[0].ind, [])
        self.assertListEqual(sp[0].val, [])
        self.assertListEqual(sp[1].ind, [0])
        self.assertListEqual(sp[1].val, [1.0])

        sp = q.get_linear_components([1, '0'])
        self.assertListEqual(sp[0].ind, [0])
        self.assertListEqual(sp[0].val, [1.0])
        self.assertListEqual(sp[1].ind, [])
        self.assertListEqual(sp[1].val, [])

        sp = q.get_linear_components()
        self.assertListEqual(sp[0].ind, [])
        self.assertListEqual(sp[0].val, [])
        self.assertListEqual(sp[1].ind, [0])
        self.assertListEqual(sp[1].val, [1.0])
        self.assertListEqual(sp[2].ind, [0, 1])
        self.assertListEqual(sp[2].val, [1.0, 2.0])
示例#3
0
    def test_admm_maximization(self):
        """Tests a simple maximization problem using ADMM optimizer"""
        mdl = Model('test')
        c = mdl.continuous_var(lb=0, ub=10, name='c')
        x = mdl.binary_var(name='x')
        mdl.maximize(c + x * x)
        op = OptimizationProblem()
        op.from_docplex(mdl)
        self.assertIsNotNone(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: ADMMOptimizerResult = solver.solve(op)
        self.assertIsNotNone(solution)
        self.assertIsInstance(solution, ADMMOptimizerResult)

        self.assertIsNotNone(solution.x)
        np.testing.assert_almost_equal([10, 0], solution.x, 3)
        self.assertIsNotNone(solution.fval)
        np.testing.assert_almost_equal(10, solution.fval, 3)
        self.assertIsNotNone(solution.state)
        self.assertIsInstance(solution.state, ADMMState)
示例#4
0
 def test_set_lower_bounds(self):
     op = OptimizationProblem()
     op.variables.add(names=["x0", "x1", "x2"])
     op.variables.set_lower_bounds(0, 1.0)
     self.assertListEqual(op.variables.get_lower_bounds(), [1.0, 0.0, 0.0])
     op.variables.set_lower_bounds([(2, 3.0), ("x1", -1.0)])
     self.assertListEqual(op.variables.get_lower_bounds(), [1.0, -1.0, 3.0])
示例#5
0
 def test_initial2(self):
     op = OptimizationProblem()
     op.variables.add(names=['x1', 'x2', 'x3'], types='B' * 3)
     c = op.quadratic_constraints.add(lin_expr=SparsePair(ind=['x1', 'x3'],
                                                          val=[1.0, -1.0]),
                                      quad_expr=SparseTriple(
                                          ind1=['x1', 'x2'],
                                          ind2=['x2', 'x3'],
                                          val=[1.0, -1.0]),
                                      sense='E',
                                      rhs=1.0)
     quad = op.quadratic_constraints
     self.assertEqual(quad.get_num(), 1)
     self.assertListEqual(quad.get_names(), ['q0'])
     self.assertListEqual(quad.get_rhs(), [1.0])
     self.assertListEqual(quad.get_senses(), ['E'])
     self.assertListEqual(quad.get_linear_num_nonzeros(), [2])
     self.assertListEqual(quad.get_quad_num_nonzeros(), [2])
     l = quad.get_linear_components()
     self.assertEqual(len(l), 1)
     self.assertListEqual(l[0].ind, [0, 2])
     self.assertListEqual(l[0].val, [1.0, -1.0])
     q = quad.get_quadratic_components()
     self.assertEqual(len(q), 1)
     self.assertListEqual(q[0].ind1, [1, 2])
     self.assertListEqual(q[0].ind2, [0, 1])
     self.assertListEqual(q[0].val, [1.0, -1.0])
示例#6
0
    def test_get_quadratic_components2(self):
        op = OptimizationProblem()
        op.variables.add(names=[str(i) for i in range(11)])
        q = op.quadratic_constraints
        [
            q.add(name=str(i),
                  quad_expr=[
                      range(i),
                      range(i), [1.0 * (j + 1.0) for j in range(i)]
                  ]) for i in range(1, 11)
        ]
        s = q.get_quadratic_components(8)
        self.assertListEqual(s.ind1, [0, 1, 2, 3, 4, 5, 6, 7, 8])
        self.assertListEqual(s.ind2, [0, 1, 2, 3, 4, 5, 6, 7, 8])
        self.assertListEqual(s.val,
                             [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0])

        s = q.get_quadratic_components('1', 3)
        self.assertEqual(len(s), 4)
        self.assertListEqual(s[0].ind1, [0])
        self.assertListEqual(s[0].ind2, [0])
        self.assertListEqual(s[0].val, [1.0])
        self.assertListEqual(s[1].ind1, [0, 1])
        self.assertListEqual(s[1].ind2, [0, 1])
        self.assertListEqual(s[1].val, [1.0, 2.0])
        self.assertListEqual(s[2].ind1, [0, 1, 2])
        self.assertListEqual(s[2].ind2, [0, 1, 2])
        self.assertListEqual(s[2].val, [1.0, 2.0, 3.0])
        self.assertListEqual(s[3].ind1, [0, 1, 2, 3])
        self.assertListEqual(s[3].ind2, [0, 1, 2, 3])
        self.assertListEqual(s[3].val, [1.0, 2.0, 3.0, 4.0])

        s = q.get_quadratic_components([2, '1', 5])
        self.assertEqual(len(s), 3)
        self.assertListEqual(s[0].ind1, [0, 1, 2])
        self.assertListEqual(s[0].ind2, [0, 1, 2])
        self.assertListEqual(s[0].val, [1.0, 2.0, 3.0])
        self.assertListEqual(s[1].ind1, [0])
        self.assertListEqual(s[1].ind2, [0])
        self.assertListEqual(s[1].val, [1.0])
        self.assertListEqual(s[2].ind1, [0, 1, 2, 3, 4, 5])
        self.assertListEqual(s[2].ind2, [0, 1, 2, 3, 4, 5])
        self.assertListEqual(s[2].val, [1.0, 2.0, 3.0, 4.0, 5.0, 6.0])

        q.delete(4, 9)
        s = q.get_quadratic_components()
        self.assertEqual(len(s), 4)
        self.assertListEqual(s[0].ind1, [0])
        self.assertListEqual(s[0].ind2, [0])
        self.assertListEqual(s[0].val, [1.0])
        self.assertListEqual(s[1].ind1, [0, 1])
        self.assertListEqual(s[1].ind2, [0, 1])
        self.assertListEqual(s[1].val, [1.0, 2.0])
        self.assertListEqual(s[2].ind1, [0, 1, 2])
        self.assertListEqual(s[2].ind2, [0, 1, 2])
        self.assertListEqual(s[2].val, [1.0, 2.0, 3.0])
        self.assertListEqual(s[3].ind1, [0, 1, 2, 3])
        self.assertListEqual(s[3].ind2, [0, 1, 2, 3])
        self.assertListEqual(s[3].val, [1.0, 2.0, 3.0, 4.0])
示例#7
0
 def test_default_bounds(self):
     op = OptimizationProblem()
     types = ['B', 'I', 'C', 'S', 'N']
     op.variables.add(names=types, types=types)
     self.assertListEqual(op.variables.get_lower_bounds(), [0.0] * 5)
     # the upper bound of binary variable is 1.
     self.assertListEqual(op.variables.get_upper_bounds(),
                          [1.0] + [infinity] * 4)
示例#8
0
 def test_set_names(self):
     op = OptimizationProblem()
     t = op.variables.type
     op.variables.add(types=[t.continuous, t.binary, t.integer])
     op.variables.set_names(0, "first")
     op.variables.set_names([(2, "third"), (1, "second")])
     self.assertListEqual(op.variables.get_names(),
                          ['first', 'second', 'third'])
示例#9
0
 def test_add2(self):
     op = OptimizationProblem()
     op.variables.add(names=['x'])
     self.assertEqual(op.variables.get_indices('x'), 0)
     self.assertListEqual(op.variables.get_indices(), [0])
     op.variables.add(names=['y'])
     self.assertEqual(op.variables.get_indices('x'), 0)
     self.assertEqual(op.variables.get_indices('y'), 1)
     self.assertListEqual(op.variables.get_indices(), [0, 1])
示例#10
0
 def test_get_senses(self):
     op = OptimizationProblem()
     op.variables.add(names=["x0"])
     q = op.quadratic_constraints
     q0 = [q.add(name=str(i), sense=j) for i, j in enumerate('GGLL')]
     self.assertListEqual(q0, [0, 1, 2, 3])
     self.assertEqual(q.get_senses(1), 'G')
     self.assertListEqual(q.get_senses('1', 3), ['G', 'L', 'L'])
     self.assertListEqual(q.get_senses([2, '0', 1]), ['L', 'G', 'G'])
     self.assertListEqual(q.get_senses(), ['G', 'G', 'L', 'L'])
示例#11
0
 def test_add(self):
     op = OptimizationProblem()
     op.variables.add(names=['x', 'y'])
     l = SparsePair(ind=['x'], val=[1.0])
     q = SparseTriple(ind1=['x'], ind2=['y'], val=[1.0])
     self.assertEqual(
         op.quadratic_constraints.add(name='my quad',
                                      lin_expr=l,
                                      quad_expr=q,
                                      rhs=1.0,
                                      sense='G'), 0)
示例#12
0
 def test_get_names(self):
     op = OptimizationProblem()
     op.variables.add(names=['x' + str(i) for i in range(10)])
     self.assertEqual(op.variables.get_num(), 10)
     self.assertEqual(op.variables.get_names(8), 'x8')
     self.assertListEqual(op.variables.get_names(1, 3), ['x1', 'x2', 'x3'])
     self.assertListEqual(op.variables.get_names([2, 0, 5]),
                          ['x2', 'x0', 'x5'])
     self.assertListEqual(
         op.variables.get_names(),
         ['x0', 'x1', 'x2', 'x3', 'x4', 'x5', 'x6', 'x7', 'x8', 'x9'])
示例#13
0
 def test_initial1(self):
     op = OptimizationProblem()
     c1 = op.quadratic_constraints.add(name='c1')
     c2 = op.quadratic_constraints.add(name='c2')
     c3 = op.quadratic_constraints.add(name='c3')
     self.assertEqual(op.quadratic_constraints.get_num(), 3)
     self.assertListEqual(op.quadratic_constraints.get_names(),
                          ['c1', 'c2', 'c3'])
     self.assertListEqual([c1, c2, c3], [0, 1, 2])
     self.assertRaises(QiskitOptimizationError,
                       lambda: op.quadratic_constraints.add(name='c1'))
示例#14
0
 def test_get_lower_bounds(self):
     op = OptimizationProblem()
     op.variables.add(lb=[1.5 * i for i in range(10)],
                      names=[str(i) for i in range(10)])
     self.assertEqual(op.variables.get_num(), 10)
     self.assertEqual(op.variables.get_lower_bounds(8), 12.0)
     self.assertListEqual(op.variables.get_lower_bounds('1', 3),
                          [1.5, 3.0, 4.5])
     self.assertListEqual(op.variables.get_lower_bounds([2, "0", 5]),
                          [3.0, 0.0, 7.5])
     self.assertEqual(op.variables.get_lower_bounds(),
                      [0.0, 1.5, 3.0, 4.5, 6.0, 7.5, 9.0, 10.5, 12.0, 13.5])
示例#15
0
 def test_get_num(self):
     op = OptimizationProblem()
     op.variables.add(names=['x', 'y'])
     l = SparsePair(ind=['x'], val=[1.0])
     q = SparseTriple(ind1=['x'], ind2=['y'], val=[1.0])
     n = 10
     for i in range(n):
         self.assertEqual(
             op.quadratic_constraints.add(name=str(i),
                                          lin_expr=l,
                                          quad_expr=q), i)
     self.assertEqual(op.quadratic_constraints.get_num(), n)
示例#16
0
 def test_set_types(self):
     op = OptimizationProblem()
     op.variables.add(names=[str(i) for i in range(5)])
     op.variables.set_types(0, op.variables.type.continuous)
     op.variables.set_types([("1", op.variables.type.integer),
                             ("2", op.variables.type.binary),
                             ("3", op.variables.type.semi_continuous),
                             ("4", op.variables.type.semi_integer)])
     self.assertListEqual(op.variables.get_types(),
                          ['C', 'I', 'B', 'S', 'N'])
     self.assertEqual(op.variables.type[op.variables.get_types(0)],
                      'continuous')
示例#17
0
 def test_initial(self):
     op = OptimizationProblem()
     op.variables.add(names=["x0", "x1", "x2"])
     self.assertListEqual(op.variables.get_lower_bounds(), [0.0, 0.0, 0.0])
     op.variables.set_lower_bounds(0, 1.0)
     op.variables.set_lower_bounds([("x1", -1.0), (2, 3.0)])
     self.assertListEqual(op.variables.get_lower_bounds(0, "x1"),
                          [1.0, -1.0])
     self.assertListEqual(op.variables.get_lower_bounds(["x1", "x2", 0]),
                          [-1.0, 3.0, 1.0])
     self.assertEqual(op.variables.get_num(), 3)
     op.variables.set_types(0, op.variables.type.binary)
     self.assertEqual(op.variables.get_num_binary(), 1)
示例#18
0
 def test_add(self):
     op = OptimizationProblem()
     op.linear_constraints.add(names=["c0", "c1", "c2"])
     op.variables.add(types=[op.variables.type.integer] * 3)
     op.variables.add(lb=[-1.0, 1.0, 0.0],
                      ub=[100.0, infinity, infinity],
                      types=[op.variables.type.integer] * 3,
                      names=["0", "1", "2"])
     self.assertListEqual(op.variables.get_lower_bounds(),
                          [0.0, 0.0, 0.0, -1.0, 1.0, 0.0])
     self.assertListEqual(
         op.variables.get_upper_bounds(),
         [infinity, infinity, infinity, 100.0, infinity, infinity])
示例#19
0
 def test_get_upper_bounds(self):
     op = OptimizationProblem()
     op.variables.add(ub=[(1.5 * i) + 1.0 for i in range(10)],
                      names=[str(i) for i in range(10)])
     self.assertEqual(op.variables.get_num(), 10)
     self.assertEqual(op.variables.get_upper_bounds(8), 13.0)
     self.assertListEqual(op.variables.get_upper_bounds('1', 3),
                          [2.5, 4.0, 5.5])
     self.assertListEqual(op.variables.get_upper_bounds([2, "0", 5]),
                          [4.0, 1.0, 8.5])
     self.assertListEqual(
         op.variables.get_upper_bounds(),
         [1.0, 2.5, 4.0, 5.5, 7.0, 8.5, 10.0, 11.5, 13.0, 14.5])
示例#20
0
    def create_problem(self) -> OptimizationProblem:
        """Creates an instance of optimization problem based on parameters specified.

        Returns:
            an instance of optimization problem.
        """
        self.op = OptimizationProblem()

        self._create_params()
        self._create_vars()
        self._create_objective()
        self._create_constraints()

        return self.op
示例#21
0
    def test_qubo_gas_int_simple(self):
        """ Test for simple case, with 2 linear coeffs and no quadratic coeffs or constants """

        # Input.
        op = OptimizationProblem()
        op.variables.add(names=["x0", "x1"], types='BB')
        linear = [("x0", -1), ("x1", 2)]
        op.objective.set_linear(linear)

        # Get the optimum key and value.
        n_iter = 8
        gmf = GroverMinimumFinder(num_iterations=n_iter)
        results = gmf.solve(op)
        self.validate_results(op, results, n_iter)
示例#22
0
    def test_qubo_gas_int_zero(self):
        """ Test for when the answer is zero """

        # Input.
        op = OptimizationProblem()
        op.variables.add(names=["x0", "x1"], types='BB')
        linear = [("x0", 0), ("x1", 0)]
        op.objective.set_linear(linear)

        # Will not find a negative, should return 0.
        gmf = GroverMinimumFinder(num_iterations=1)
        results = gmf.solve(op)
        self.assertEqual(results.x, [0, 0])
        self.assertEqual(results.fval, 0.0)
示例#23
0
    def test_cobyla_optimizer(self, config):
        """ Cobyla Optimizer Test """

        # unpack configuration
        filename, fval = config

        # load optimization problem
        problem = OptimizationProblem()
        problem.read(self.resource_path + filename)

        # solve problem with cobyla
        result = self.cobyla_optimizer.solve(problem)

        # analyze results
        self.assertAlmostEqual(result.fval, fval)
示例#24
0
 def test_get_rhs(self):
     op = OptimizationProblem()
     op.variables.add(names=[str(i) for i in range(10)])
     q0 = [
         op.quadratic_constraints.add(rhs=1.5 * i, name=str(i))
         for i in range(10)
     ]
     self.assertListEqual(q0, list(range(10)))
     q = op.quadratic_constraints
     self.assertEqual(q.get_num(), 10)
     self.assertEqual(q.get_rhs(8), 12.0)
     self.assertListEqual(q.get_rhs('1', 3), [1.5, 3.0, 4.5])
     self.assertListEqual(q.get_rhs([2, '0', 5]), [3.0, 0.0, 7.5])
     self.assertListEqual(
         q.get_rhs(), [0.0, 1.5, 3.0, 4.5, 6.0, 7.5, 9.0, 10.5, 12.0, 13.5])
示例#25
0
 def test_get_linear_num_nonzeros(self):
     op = OptimizationProblem()
     op.variables.add(names=[str(i) for i in range(11)], types="B" * 11)
     q = op.quadratic_constraints
     n = 10
     [
         q.add(name=str(i),
               lin_expr=[range(i), [1.0 * (j + 1.0) for j in range(i)]])
         for i in range(n)
     ]
     self.assertEqual(q.get_num(), n)
     self.assertEqual(q.get_linear_num_nonzeros(8), 8)
     self.assertListEqual(q.get_linear_num_nonzeros('1', 3), [1, 2, 3])
     self.assertListEqual(q.get_linear_num_nonzeros([2, '0', 5]), [2, 0, 5])
     self.assertListEqual(q.get_linear_num_nonzeros(),
                          [0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
示例#26
0
 def test_delete(self):
     op = OptimizationProblem()
     q0 = [op.quadratic_constraints.add(name=str(i)) for i in range(10)]
     self.assertListEqual(q0, list(range(10)))
     q = op.quadratic_constraints
     self.assertListEqual(
         q.get_names(), ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'])
     q.delete(8)
     self.assertListEqual(q.get_names(),
                          ['0', '1', '2', '3', '4', '5', '6', '7', '9'])
     q.delete("1", 3)
     self.assertListEqual(q.get_names(), ['0', '4', '5', '6', '7', '9'])
     q.delete([2, "0", 5])
     self.assertListEqual(q.get_names(), ['4', '6', '7'])
     q.delete()
     self.assertListEqual(q.get_names(), [])
示例#27
0
    def test_qubo_gas_int_paper_example(self):
        """ Test the example from https://arxiv.org/abs/1912.04088 """

        # Input.
        op = OptimizationProblem()
        op.variables.add(names=["x0", "x1", "x2"], types='BBB')

        linear = [("x0", -1), ("x1", 2), ("x2", -3)]
        op.objective.set_linear(linear)
        op.objective.set_quadratic_coefficients('x0', 'x2', -2)
        op.objective.set_quadratic_coefficients('x1', 'x2', -1)

        # Get the optimum key and value.
        n_iter = 10
        gmf = GroverMinimumFinder(num_iterations=n_iter)
        results = gmf.solve(op)
        self.validate_results(op, results, 10)
示例#28
0
 def test_quad_num_nonzeros(self):
     op = OptimizationProblem()
     op.variables.add(names=[str(i) for i in range(11)])
     q = op.quadratic_constraints
     [
         q.add(name=str(i),
               quad_expr=[
                   range(i),
                   range(i), [1.0 * (j + 1.0) for j in range(i)]
               ]) for i in range(1, 11)
     ]
     self.assertEqual(q.get_num(), 10)
     self.assertEqual(q.get_quad_num_nonzeros(8), 9)
     self.assertListEqual(q.get_quad_num_nonzeros('1', 2), [1, 2, 3])
     self.assertListEqual(q.get_quad_num_nonzeros([2, '1', 5]), [3, 1, 6])
     self.assertListEqual(q.get_quad_num_nonzeros(),
                          [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
示例#29
0
 def test_delete(self):
     op = OptimizationProblem()
     op.variables.add(names=[str(i) for i in range(10)])
     self.assertEqual(op.variables.get_num(), 10)
     self.assertListEqual(
         op.variables.get_names(),
         ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'])
     op.variables.delete(8)
     self.assertListEqual(op.variables.get_names(),
                          ['0', '1', '2', '3', '4', '5', '6', '7', '9'])
     op.variables.delete("1", 3)
     self.assertListEqual(op.variables.get_names(),
                          ['0', '4', '5', '6', '7', '9'])
     op.variables.delete([2, '0', 5])
     self.assertListEqual(op.variables.get_names(), ['4', '6', '7'])
     op.variables.delete()
     self.assertListEqual(op.variables.get_names(), [])
示例#30
0
    def test_cobyla_optimizer_with_quadratic_constraint(self):
        """ Cobyla Optimizer Test """

        # load optimization problem
        problem = OptimizationProblem()
        problem.variables.add(lb=[0, 0], ub=[1, 1], types='CC')
        problem.objective.set_linear([(0, 1), (1, 1)])

        qc = problem.quadratic_constraints
        linear = SparsePair(ind=[0, 1], val=[-1, -1])
        quadratic = SparseTriple(ind1=[0, 1], ind2=[0, 1], val=[1, 1])
        qc.add(name='qc', lin_expr=linear, quad_expr=quadratic, rhs=-1/2)

        # solve problem with cobyla
        result = self.cobyla_optimizer.solve(problem)

        # analyze results
        self.assertAlmostEqual(result.fval, 1.0, places=2)