Esempio n. 1
0
    def test_qaoa(self, w, prob, m, solutions, convert_to_matrix_op):
        """ QAOA test """
        seed = 0
        aqua_globals.random_seed = seed
        self.log.debug('Testing %s-step QAOA with MaxCut on graph\n%s', prob,
                       w)

        backend = BasicAer.get_backend('statevector_simulator')
        optimizer = COBYLA()
        qubit_op, offset = max_cut.get_operator(w)
        qubit_op = qubit_op.to_opflow()
        if convert_to_matrix_op:
            qubit_op = qubit_op.to_matrix_op()

        qaoa = QAOA(qubit_op, optimizer, prob, mixer=m)
        quantum_instance = QuantumInstance(backend,
                                           seed_simulator=seed,
                                           seed_transpiler=seed)

        result = qaoa.run(quantum_instance)
        x = sample_most_likely(result.eigenstate)
        graph_solution = max_cut.get_graph_solution(x)
        self.log.debug('energy:             %s', result.eigenvalue.real)
        self.log.debug('time:               %s', result.optimizer_time)
        self.log.debug('maxcut objective:   %s',
                       result.eigenvalue.real + offset)
        self.log.debug('solution:           %s', graph_solution)
        self.log.debug('solution objective: %s', max_cut.max_cut_value(x, w))
        self.assertIn(''.join([str(int(i)) for i in graph_solution]),
                      solutions)
Esempio n. 2
0
    def test_qaoa_qc_mixer(self, w, prob, solutions, convert_to_matrix_op):
        """ QAOA test with a mixer as a parameterized circuit"""
        seed = 0
        aqua_globals.random_seed = seed
        self.log.debug(
            'Testing %s-step QAOA with MaxCut on graph with '
            'a mixer as a parameterized circuit\n%s', prob, w)

        backend = BasicAer.get_backend('statevector_simulator')
        optimizer = COBYLA()
        qubit_op, _ = max_cut.get_operator(w)
        qubit_op = qubit_op.to_opflow()
        if convert_to_matrix_op:
            qubit_op = qubit_op.to_matrix_op()

        num_qubits = qubit_op.num_qubits
        mixer = QuantumCircuit(num_qubits)
        theta = Parameter('θ')
        mixer.rx(theta, range(num_qubits))

        qaoa = QAOA(qubit_op, optimizer, prob, mixer=mixer)
        quantum_instance = QuantumInstance(backend,
                                           seed_simulator=seed,
                                           seed_transpiler=seed)

        result = qaoa.run(quantum_instance)
        x = sample_most_likely(result.eigenstate)
        graph_solution = max_cut.get_graph_solution(x)
        self.assertIn(''.join([str(int(i)) for i in graph_solution]),
                      solutions)
Esempio n. 3
0
    def test_qaoa_initial_point(self, w, solutions, init_pt):
        """ Check first parameter value used is initial point as expected """
        optimizer = COBYLA()
        qubit_op, _ = max_cut.get_operator(w)

        first_pt = []

        def cb_callback(eval_count, parameters, mean, std):
            nonlocal first_pt
            if eval_count == 1:
                first_pt = list(parameters)

        quantum_instance = QuantumInstance(
            BasicAer.get_backend('statevector_simulator'))
        qaoa = QAOA(qubit_op,
                    optimizer,
                    initial_point=init_pt,
                    callback=cb_callback,
                    quantum_instance=quantum_instance)

        result = qaoa.compute_minimum_eigenvalue()
        x = sample_most_likely(result.eigenstate)
        graph_solution = max_cut.get_graph_solution(x)

        if init_pt is None:  # If None the preferred initial point of QAOA variational form
            init_pt = [0.0,
                       0.0]  # i.e. 0,0 should come through as the first point

        with self.subTest('Initial Point'):
            self.assertListEqual(init_pt, first_pt)

        with self.subTest('Solution'):
            self.assertIn(''.join([str(int(i)) for i in graph_solution]),
                          solutions)
Esempio n. 4
0
    def test_qaoa_qc_mixer_many_parameters(self):
        """ QAOA test with a mixer as a parameterized circuit with the num of parameters > 1. """
        seed = 0
        aqua_globals.random_seed = seed

        optimizer = COBYLA()
        qubit_op, _ = max_cut.get_operator(W1)
        qubit_op = qubit_op.to_opflow()

        num_qubits = qubit_op.num_qubits
        mixer = QuantumCircuit(num_qubits)
        for i in range(num_qubits):
            theta = Parameter('θ' + str(i))
            mixer.rx(theta, range(num_qubits))

        qaoa = QAOA(qubit_op, optimizer=optimizer, p=2, mixer=mixer)
        backend = BasicAer.get_backend('statevector_simulator')
        quantum_instance = QuantumInstance(backend,
                                           seed_simulator=seed,
                                           seed_transpiler=seed)
        result = qaoa.run(quantum_instance)
        x = sample_most_likely(result.eigenstate)
        print(x)
        graph_solution = max_cut.get_graph_solution(x)
        self.assertIn(''.join([str(int(i)) for i in graph_solution]), S1)
Esempio 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
Esempio n. 6
0
    def test_change_operator_size(self):
        """ QAOA change operator size test """

        aqua_globals.random_seed = 0
        qubit_op, _ = max_cut.get_operator(
            np.array([[0, 1, 0, 1], [1, 0, 1, 0], [0, 1, 0, 1], [1, 0, 1, 0]]))
        qaoa = QAOA(qubit_op.to_opflow(), COBYLA(), 1)
        quantum_instance = QuantumInstance(
            BasicAer.get_backend('statevector_simulator'),
            seed_simulator=aqua_globals.random_seed,
            seed_transpiler=aqua_globals.random_seed)
        result = qaoa.run(quantum_instance)
        x = sample_most_likely(result.eigenstate)
        graph_solution = max_cut.get_graph_solution(x)
        with self.subTest(msg='QAOA 4x4'):
            self.assertIn(''.join([str(int(i)) for i in graph_solution]),
                          {'0101', '1010'})

        try:
            qubit_op, _ = max_cut.get_operator(
                np.array([
                    [0, 1, 0, 1, 0, 1],
                    [1, 0, 1, 0, 1, 0],
                    [0, 1, 0, 1, 0, 1],
                    [1, 0, 1, 0, 1, 0],
                    [0, 1, 0, 1, 0, 1],
                    [1, 0, 1, 0, 1, 0],
                ]))
            qaoa.operator = qubit_op.to_opflow()
        except Exception as ex:  # pylint: disable=broad-except
            self.fail("Failed to change operator. Error: '{}'".format(str(ex)))
            return

        result = qaoa.run()
        x = sample_most_likely(result.eigenstate)
        graph_solution = max_cut.get_graph_solution(x)
        with self.subTest(msg='QAOA 6x6'):
            self.assertIn(''.join([str(int(i)) for i in graph_solution]),
                          {'010101', '101010'})
Esempio n. 7
0
 def test_cplex_ising(self):
     """ cplex ising test """
     try:
         algo = ClassicalCPLEX(self.qubit_op, display=0)
         result = algo.run()
         self.assertEqual(result['energy'], -20.5)
         x_dict = result['x_sol']
         x = np.array([x_dict[i] for i in sorted(x_dict.keys())])
         np.testing.assert_array_equal(
             max_cut.get_graph_solution(x), [1, 0, 1, 1])
         self.assertEqual(max_cut.max_cut_value(x, self.w), 24)
     except NameError as ex:
         self.skipTest(str(ex))
Esempio n. 8
0
    def test_qaoa_initial_point(self, w, solutions, init_pt):
        """ Check first parameter value used is initial point as expected """
        aqua_globals.random_seed = 10598
        optimizer = COBYLA()
        qubit_op, _ = max_cut.get_operator(w)

        first_pt = []

        def cb_callback(eval_count, parameters, mean, std):
            nonlocal first_pt
            if eval_count == 1:
                first_pt = list(parameters)

        quantum_instance = QuantumInstance(
            BasicAer.get_backend('statevector_simulator'),
            seed_simulator=aqua_globals.random_seed,
            seed_transpiler=aqua_globals.random_seed)
        qaoa = QAOA(qubit_op,
                    optimizer,
                    initial_point=init_pt,
                    callback=cb_callback,
                    quantum_instance=quantum_instance)

        result = qaoa.compute_minimum_eigenvalue()
        x = sample_most_likely(result.eigenstate)
        graph_solution = max_cut.get_graph_solution(x)

        with self.subTest('Initial Point'):
            # If None the preferred random initial point of QAOA variational form
            if init_pt is None:
                np.testing.assert_almost_equal([1.5108, 0.3378],
                                               first_pt,
                                               decimal=4)
            else:
                self.assertListEqual(init_pt, first_pt)

        with self.subTest('Solution'):
            self.assertIn(''.join([str(int(i)) for i in graph_solution]),
                          solutions)
Esempio n. 9
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)
Esempio n. 10
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)
Esempio n. 11
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
    }