|
| 1 | +import ray |
| 2 | +import numpy as np |
| 3 | + |
| 4 | +from qiskit.opflow import Z, I, X |
| 5 | +from qiskit.providers.basicaer import QasmSimulatorPy |
| 6 | +from qiskit.utils import QuantumInstance |
| 7 | +from qiskit.algorithms import VQE |
| 8 | +from qiskit.circuit.library import TwoLocal |
| 9 | +from qiskit.algorithms.optimizers import SLSQP |
| 10 | +from qiskit.providers import Backend |
| 11 | + |
| 12 | +import sys |
| 13 | +print(sys.argv[1:]) |
| 14 | + |
| 15 | +@ray.remote |
| 16 | +def prep_problem(): |
| 17 | + """Prepare demo problem.""" |
| 18 | + op = ( |
| 19 | + (-1.052373245772859 * I ^ I) |
| 20 | + + (0.39793742484318045 * I ^ Z) |
| 21 | + + (-0.39793742484318045 * Z ^ I) |
| 22 | + + (-0.01128010425623538 * Z ^ Z) |
| 23 | + + (0.18093119978423156 * X ^ X) |
| 24 | + ) |
| 25 | + initial_state = np.random.random(8) |
| 26 | + var_form = TwoLocal( |
| 27 | + rotation_blocks="ry", |
| 28 | + entanglement_blocks="cz" |
| 29 | + ) |
| 30 | + |
| 31 | + return (op, var_form, initial_state) |
| 32 | + |
| 33 | +@ray.remote |
| 34 | +def optimize(problem): |
| 35 | + """Optimization demo routine.""" |
| 36 | + backend = QasmSimulatorPy() |
| 37 | + |
| 38 | + op, var_form, init_point = problem |
| 39 | + |
| 40 | + qi = QuantumInstance(backend, seed_transpiler=42, seed_simulator=42) |
| 41 | + ansatz = TwoLocal(rotation_blocks="ry", entanglement_blocks="cz") |
| 42 | + slsqp = SLSQP(maxiter=100) |
| 43 | + |
| 44 | + vqe = VQE( |
| 45 | + var_form, |
| 46 | + optimizer=slsqp, |
| 47 | + quantum_instance=qi, |
| 48 | + initial_point=init_point |
| 49 | + ) |
| 50 | + result = vqe.compute_minimum_eigenvalue(op) |
| 51 | + |
| 52 | + print(f"Optimization result:") |
| 53 | + print(f" - eigenvalue: {result.eigenvalue}") |
| 54 | + print(f" - optimal value: {result.optimal_value}") |
| 55 | + print(f" - optinal parameters: {result.optimal_parameters}") |
| 56 | + |
| 57 | + return result |
| 58 | + |
| 59 | +@ray.remote |
| 60 | +def analyze(results): |
| 61 | + """Analyzing demo results.""" |
| 62 | + return min(results, key=lambda r: r.eigenvalue.real) |
| 63 | + |
| 64 | + |
| 65 | +if __name__ == "__main__": |
| 66 | + with ray.init(): |
| 67 | + number_of_trials = 30 |
| 68 | + |
| 69 | + workflow_graph = analyze.remote( |
| 70 | + results=ray.get([ |
| 71 | + optimize.remote( |
| 72 | + problem=prep_problem.remote() |
| 73 | + ) |
| 74 | + for _ in range(number_of_trials) |
| 75 | + ]) |
| 76 | + ) |
| 77 | + |
| 78 | + result = ray.get(workflow_graph) |
| 79 | + print(f"Final result:") |
| 80 | + print(f" - eigenvalue: {result.eigenvalue}") |
| 81 | + print(f" - optimal value: {result.optimal_value}") |
| 82 | + print(f" - optinal parameters: {result.optimal_parameters}") |
0 commit comments