Exemplo n.º 1
0
    def test_validation(self):
        """ Validation Test """
        num_var = 3
        # validate an object type of the input.
        with self.assertRaises(AquaError):
            docplex._validate_input_model("Model")

        # validate the types of the variables are binary or not
        with self.assertRaises(AquaError):
            mdl = Model(name='Error_integer_variables')
            x = {
                i: mdl.integer_var(name='x_{0}'.format(i))
                for i in range(num_var)
            }
            obj_func = mdl.sum(x[i] for i in range(num_var))
            mdl.maximize(obj_func)
            docplex.get_operator(mdl)

        # validate types of constraints are equality constraints or not.
        with self.assertRaises(AquaError):
            mdl = Model(name='Error_inequality_constraints')
            x = {
                i: mdl.binary_var(name='x_{0}'.format(i))
                for i in range(num_var)
            }
            obj_func = mdl.sum(x[i] for i in range(num_var))
            mdl.maximize(obj_func)
            mdl.add_constraint(mdl.sum(x[i] for i in range(num_var)) <= 1)
            docplex.get_operator(mdl)
Exemplo n.º 2
0
    def test_docplex_constant_and_quadratic_terms_in_object_function(self):
        """ Docplex Constant and Quadratic terms in Object function test """
        # Create an Ising Hamiltonian with docplex
        laplacian = np.array([[-3., 1., 1., 1.], [1., -2., 1., -0.],
                              [1., 1., -3., 1.], [1., -0., 1., -2.]])

        mdl = Model()
        # pylint: disable=unsubscriptable-object
        n = laplacian.shape[0]
        bias = [0] * 4
        x = {i: mdl.binary_var(name='x_{0}'.format(i)) for i in range(n)}
        couplers_func = mdl.sum(2 * laplacian[i, j] * (2 * x[i] - 1) *
                                (2 * x[j] - 1) for i in range(n - 1)
                                for j in range(i, n))
        bias_func = mdl.sum(float(bias[i]) * x[i] for i in range(n))
        ising_func = couplers_func + bias_func
        mdl.minimize(ising_func)
        qubit_op, offset = docplex.get_operator(mdl)

        e_e = NumPyMinimumEigensolver(qubit_op)
        result = e_e.run()

        expected_result = -22

        # Compare objective
        self.assertAlmostEqual(result.eigenvalue.real + offset,
                               expected_result)
Exemplo n.º 3
0
    def test_docplex_tsp(self):
        """ Docplex tsp test """
        # Generating a graph of 3 nodes
        n = 3
        ins = tsp.random_tsp(n)
        graph = nx.Graph()
        graph.add_nodes_from(np.arange(0, n, 1))
        num_node = ins.dim

        # Create an Ising Hamiltonian with docplex.
        mdl = Model(name='tsp')
        x = {(i, p): mdl.binary_var(name='x_{0}_{1}'.format(i, p))
             for i in range(num_node) for p in range(num_node)}
        tsp_func = mdl.sum(ins.w[i, j] * x[(i, p)] * x[(j, (p + 1) % num_node)]
                           for i in range(num_node) for j in range(num_node)
                           for p in range(num_node))
        mdl.minimize(tsp_func)
        for i in range(num_node):
            mdl.add_constraint(
                mdl.sum(x[(i, p)] for p in range(num_node)) == 1)
        for j in range(num_node):
            mdl.add_constraint(
                mdl.sum(x[(i, j)] for i in range(num_node)) == 1)
        qubit_op, offset = docplex.get_operator(mdl)

        e_e = NumPyMinimumEigensolver(qubit_op)
        result = e_e.run()

        ee_expected = NumPyMinimumEigensolver(QUBIT_OP_TSP)
        expected_result = ee_expected.run()

        # Compare objective
        self.assertAlmostEqual(result.eigenvalue.real + offset,
                               expected_result.eigenvalue.real + OFFSET_TSP)
Exemplo n.º 4
0
    def test_docplex_maxcut(self):
        """ Docplex maxcut test """
        # Generating a graph of 4 nodes
        n = 4
        graph = nx.Graph()
        graph.add_nodes_from(np.arange(0, n, 1))
        elist = [(0, 1, 1.0), (0, 2, 1.0), (0, 3, 1.0), (1, 2, 1.0),
                 (2, 3, 1.0)]
        graph.add_weighted_edges_from(elist)
        # Computing the weight matrix from the random graph
        w = np.zeros([n, n])
        for i in range(n):
            for j in range(n):
                temp = graph.get_edge_data(i, j, default=0)
                if temp != 0:
                    w[i, j] = temp['weight']

        # Create an Ising Hamiltonian with docplex.
        mdl = Model(name='max_cut')
        mdl.node_vars = mdl.binary_var_list(list(range(4)), name='node')
        maxcut_func = mdl.sum(w[i, j] * mdl.node_vars[i] *
                              (1 - mdl.node_vars[j]) for i in range(n)
                              for j in range(n))
        mdl.maximize(maxcut_func)
        qubit_op, offset = docplex.get_operator(mdl)

        e_e = NumPyMinimumEigensolver(qubit_op)
        result = e_e.run()

        ee_expected = NumPyMinimumEigensolver(QUBIT_OP_MAXCUT)
        expected_result = ee_expected.run()

        # Compare objective
        self.assertAlmostEqual(result.eigenvalue.real + offset,
                               expected_result.eigenvalue.real + OFFSET_MAXCUT)
Exemplo n.º 5
0
    def run_simulation(self, backend):

        seed = int(os.environ.get("SEED", "40598"))
        n = int(os.environ.get("N", "4"))
        #
        # Random 3-regular graph with 12 nodes
        #
        graph = nx.random_regular_graph(3, n, seed=seed)
        for e in graph.edges():
            graph[e[0]][e[1]]["weight"] = 1.0

        # Compute the weight matrix from the graph
        w = np.zeros([n, n])
        for i in range(n):
            for j in range(n):
                temp = graph.get_edge_data(i, j, default=0)
                if temp != 0:
                    w[i, j] = temp["weight"]

        # Create an Ising Hamiltonian with docplex.
        mdl = Model(name="max_cut")
        mdl.node_vars = mdl.binary_var_list(list(range(n)), name="node")
        maxcut_func = mdl.sum(w[i, j] * mdl.node_vars[i] *
                              (1 - mdl.node_vars[j]) for i in range(n)
                              for j in range(n))
        mdl.maximize(maxcut_func)
        qubit_op, offset = docplex.get_operator(mdl)

        aqua_globals.random_seed = seed

        # Run quantum algorithm QAOA on qasm simulator
        spsa = SPSA(max_trials=250)
        qaoa = QAOA(qubit_op, spsa, p=5, max_evals_grouped=4)

        quantum_instance = QuantumInstance(
            backend,
            shots=1024,
            seed_simulator=seed,
            seed_transpiler=seed,
            optimization_level=0,
        )
        result = qaoa.run(quantum_instance)

        x = sample_most_likely(result["eigvecs"][0])
        result["solution"] = max_cut.get_graph_solution(x)
        result["solution_objective"] = max_cut.max_cut_value(x, w)
        result["maxcut_objective"] = result["energy"] + offset
        """
        print("energy:", result["energy"])
        print("time:", result["eval_time"])
        print("max-cut objective:", result["energy"] + offset)
        print("solution:", max_cut.get_graph_solution(x))
        print("solution objective:", max_cut.max_cut_value(x, w))
        """
        return result
Exemplo n.º 6
0
    def test_constants_in_left_side_and_variables_in_right_side(self):
        """ Test Constant values on the left-hand side of constraints and
        variables on the right-hand side of constraints for the DOcplex translator"""
        mdl = Model('left_constants_and_right_variables')
        x = mdl.binary_var(name='x')
        y = mdl.binary_var(name='y')
        mdl.maximize(mdl.sum(x + y))
        mdl.add_constraint(x == y)

        qubit_op, offset = docplex.get_operator(mdl)
        print(qubit_op.print_details())
        e_e = NumPyMinimumEigensolver(qubit_op)
        result = e_e.run()

        self.assertEqual(result['eigenvalue'] + offset, -2)
        actual_sol = result['eigenstate'].to_matrix().tolist()
        self.assertListEqual(actual_sol, [0, 0, 0, 1])
Exemplo n.º 7
0
    def test_docplex_integer_constraints(self):
        """ Docplex Integer Constraints test """
        # Create an Ising Hamiltonian with docplex
        mdl = Model(name='integer_constraints')
        x = {i: mdl.binary_var(name='x_{0}'.format(i)) for i in range(1, 5)}
        max_vars_func = mdl.sum(x[i] for i in range(1, 5))
        mdl.maximize(max_vars_func)
        mdl.add_constraint(mdl.sum(i * x[i] for i in range(1, 5)) == 3)
        qubit_op, offset = docplex.get_operator(mdl)

        e_e = NumPyMinimumEigensolver(qubit_op)
        result = e_e.run()

        expected_result = -2

        # Compare objective
        self.assertEqual(result.eigenvalue.real + offset, expected_result)
Exemplo n.º 8
0
    def test_readme_sample(self):
        """ readme sample test """

        # pylint: disable=import-outside-toplevel,redefined-builtin

        def print(*args):
            """ overloads print to log values """
            if args:
                self.log.debug(args[0], *args[1:])

        # --- Exact copy of sample code ----------------------------------------

        import networkx as nx
        import numpy as np
        from docplex.mp.model import Model

        from qiskit import BasicAer
        from qiskit.aqua import aqua_globals, QuantumInstance
        from qiskit.aqua.algorithms import QAOA
        from qiskit.aqua.components.optimizers import SPSA
        from qiskit.optimization.applications.ising import docplex, max_cut
        from qiskit.optimization.applications.ising.common import sample_most_likely

        # Generate a graph of 4 nodes
        n = 4
        graph = nx.Graph()
        graph.add_nodes_from(np.arange(0, n, 1))
        elist = [(0, 1, 1.0), (0, 2, 1.0), (0, 3, 1.0), (1, 2, 1.0),
                 (2, 3, 1.0)]
        graph.add_weighted_edges_from(elist)
        # Compute the weight matrix from the graph
        w = np.zeros([n, n])
        for i in range(n):
            for j in range(n):
                temp = graph.get_edge_data(i, j, default=0)
                if temp != 0:
                    w[i, j] = temp['weight']

        # Create an Ising Hamiltonian with docplex.
        mdl = Model(name='max_cut')
        mdl.node_vars = mdl.binary_var_list(list(range(n)), name='node')
        maxcut_func = mdl.sum(w[i, j] * mdl.node_vars[i] *
                              (1 - mdl.node_vars[j]) for i in range(n)
                              for j in range(n))
        mdl.maximize(maxcut_func)
        qubit_op, offset = docplex.get_operator(mdl)

        # Run quantum algorithm QAOA on qasm simulator
        seed = 40598
        aqua_globals.random_seed = seed

        spsa = SPSA(max_trials=250)
        qaoa = QAOA(qubit_op, spsa, p=5)
        backend = BasicAer.get_backend('qasm_simulator')
        quantum_instance = QuantumInstance(backend,
                                           shots=1024,
                                           seed_simulator=seed,
                                           seed_transpiler=seed)
        result = qaoa.run(quantum_instance)

        x = sample_most_likely(result.eigenstate)
        print('energy:', result.eigenvalue.real)
        print('time:', result.optimizer_time)
        print('max-cut objective:', result.eigenvalue.real + offset)
        print('solution:', max_cut.get_graph_solution(x))
        print('solution objective:', max_cut.max_cut_value(x, w))

        # ----------------------------------------------------------------------

        self.assertListEqual(
            max_cut.get_graph_solution(x).tolist(), [1, 0, 1, 0])
        self.assertAlmostEqual(max_cut.max_cut_value(x, w), 4.0)
Exemplo n.º 9
0
pos = nx.spring_layout(G)

w = my_graphs.adjacency_matrix(G)
print("\nAdjacency matrix\n", w, "\n")

# setting p
p = 1

# ... QAOA ...
# Create an Ising Hamiltonian with docplex.
mdl = Model(name='max_cut')
mdl.node_vars = mdl.binary_var_list(list(range(n)), name='node')
maxcut_func = mdl.sum(w[i, j] * mdl.node_vars[i] * (1 - mdl.node_vars[j])
                      for i in range(n) for j in range(n))
mdl.maximize(maxcut_func)
qubit_op, offset = docplex.get_operator(mdl)

# Run quantum algorithm QAOA on qasm simulator
optimizer = NELDER_MEAD()
qaoa = QAOA(qubit_op, optimizer, p=p)
backend = Aer.get_backend('qasm_simulator')
quantum_instance = QuantumInstance(backend, shots=1000)
result = qaoa.run(quantum_instance)

x = sample_most_likely(result.eigenstate)
print('energy:', result.eigenvalue.real)
print('time:', result.optimizer_time, 's')
print('max-cut objective:', result.eigenvalue.real + offset)
print('solution:', max_cut.get_graph_solution(x))
print('solution objective:', max_cut.max_cut_value(x, w))
print('angles:', result.optimal_point)
Exemplo n.º 10
0
def run_experiment(
    G,
    p,
    optimizer,
    backend,
    n_shots=100,  #important for running time, max is 8192
    print_result=False,
    skip_qobj_validation=False,
    noise_model=None,
    coupling_map=None,
    basis_gates=None,
):
    '''Runs (Qiskit) QAOA experiment with the given parameters
    Inputs
    - G, graph
    - p, number of angles
    - optimizer, classical optimizer
    - backend
    - number of shots (n_shots) - Note, this parameter is important for running time but also affects accuracy if too low
    - ...
    
    Returns a dictionary with the following keys
    - energy
    - time (in seconds)
    - iterations
    - max-cut objective
    - solution
    - solution objective
    - eigenstate distribution
    - angles
    
    '''

    n = len(G)  # number of nodes
    w = adjacency_matrix(G)  # calculating adjacency matrix from graph

    # ... QAOA ...
    # Create an Ising Hamiltonian with docplex.
    mdl = Model(name='max_cut')
    mdl.node_vars = mdl.binary_var_list(list(range(n)), name='node')
    maxcut_func = mdl.sum(w[i, j] * mdl.node_vars[i] * (1 - mdl.node_vars[j])
                          for i in range(n) for j in range(n))
    mdl.maximize(maxcut_func)
    qubit_op, offset = docplex.get_operator(mdl)

    # Construct a circuit from the model
    qaoa = QAOA(qubit_op, optimizer, p=p)
    quantum_instance = QuantumInstance(
        backend,
        shots=n_shots,
        skip_qobj_validation=skip_qobj_validation,
        coupling_map=coupling_map,
        basis_gates=basis_gates,
        noise_model=noise_model)

    # Run quantum algorithm QAOA on the backend
    result = qaoa.run(quantum_instance)
    x = sample_most_likely(result.eigenstate)

    # Results
    energy = result.eigenvalue.real
    time = result.optimizer_time
    iterations = result.optimizer_evals
    objective = result.eigenvalue.real + offset  # why offset?
    solution = max_cut.get_graph_solution(x)
    solution_objective = max_cut.max_cut_value(x, w)
    distribution = result.eigenstate
    angles = result.optimal_point

    if print_result:
        print('energy:', energy)
        print('time:', time, 's')
        print('max-cut objective:', objective)
        print('solution:', solution)
        print('solution objective:', solution_objective)
        print('angles:', angles)

    return {
        'energy': energy,
        'time': time,
        'iterations': iterations,
        'max-cut objective': objective,
        'solution': solution,
        'solution objective': solution_objective,
        'distribution': distribution,
        'angles': angles,
        'n_shots': n_shots
    }