def test_PrepareAndMeasureOnWFSim(): p = Program() params = p.declare("params", memory_type="REAL", memory_size=2) p.inst(RX(params[0], 0)) p.inst(RX(params[1], 1)) def make_memory_map(params): return {"params": params} # ham = PauliSum.from_compact_str("1.0*Z0 + 1.0*Z1") term1 = PauliTerm("Z", 0) term2 = PauliTerm("Z", 1) ham = PauliSum([term1, term2]) sim = WavefunctionSimulator() with local_qvm(): cost_fn = PrepareAndMeasureOnWFSim(p, make_memory_map, ham, sim, scalar_cost_function=False, enable_logging=True) out = cost_fn([np.pi, np.pi / 2], nshots=100) print(cost_fn.log) assert np.allclose(cost_fn.log[0].fun, (-1.0, 0.1)) assert np.allclose(out, (-1, 0.1))
def test_PrepareAndMeasureOnQVM_QubitPlaceholders_nondiag_hamiltonian(): q1, q2, q3 = QubitPlaceholder(), QubitPlaceholder(), QubitPlaceholder() ham = PauliTerm("Y", q1) * PauliTerm("Z", q3) ham += PauliTerm("Y", q1) * PauliTerm("Z", q2, -0.3) ham += PauliTerm("Y", q1) * PauliTerm("X", q3, 2.0) params = [3.0, 0.4, 4.5] prepare_ansatz = Program() param_register = prepare_ansatz.declare("params", memory_type="REAL", memory_size=3) prepare_ansatz.inst(RX(param_register[0], q1)) prepare_ansatz.inst(RY(param_register[1], q2)) prepare_ansatz.inst(RY(param_register[2], q3)) def make_memory_map(params): return {"params": params} qubit_mapping = get_default_qubit_mapping(prepare_ansatz) qvm = get_qc("3q-qvm") with local_qvm(): cost_fn = PrepareAndMeasureOnQVM(prepare_ansatz, make_memory_map, qvm=qvm, hamiltonian=ham, scalar_cost_function=False, base_numshots=100, qubit_mapping=qubit_mapping) out = cost_fn(params, nshots=10) assert np.allclose(out, (0.346, 0.07), rtol=1.1)
def test_two_qubit_state_change(prog): wf_sim = WavefunctionSimulator() with local_qvm(): state = wf_sim.wavefunction(prog) amp_cos = (1/math.sqrt(2))*math.cos(math.pi/14) amp_sin = (1/math.sqrt(2))*math.sin(math.pi/14) if (abs(state[0].real - amp_cos) < 0.0001) and (abs(state[-1].real + amp_sin) < 0.0001): print(state[1], 'sin is:', amp_sin) print(state[2], 'cos is:', amp_cos) if (abs(state[1].real - amp_sin) < 0.0001) and (abs(state[2].real - amp_cos) < 0.0001): print(state[1], 'sin is:', amp_sin) print(state[2], 'cos is:', amp_cos) print("\nNice one, you built the state:") print(state) else: print("oops, you built the state:") print(state) print("Try again...\n") else: print("oops, you built the state:") print(state)
def test_PrepareAndMeasureOnQVM(): prepare_ansatz = Program() param_register = prepare_ansatz.declare("params", memory_type="REAL", memory_size=2) prepare_ansatz.inst(RX(param_register[0], 0)) prepare_ansatz.inst(RX(param_register[1], 1)) def make_memory_map(params): return {"params": params} # ham = PauliSum.from_compact_str("1.0*Z0 + 1.0*Z1") term1 = PauliTerm("Z", 0) term2 = PauliTerm("Z", 1) ham = PauliSum([term1, term2]) qvm = get_qc("2q-qvm") with local_qvm(): # qvm = proc.qvm cost_fn = PrepareAndMeasureOnQVM(prepare_ansatz, make_memory_map, qvm=qvm, hamiltonian=ham, enable_logging=True, scalar_cost_function=True, base_numshots=10, nshots=10) out = cost_fn([np.pi, np.pi / 2]) assert np.allclose(cost_fn.log[0].fun, (-1.0, 0.1), rtol=1.1) assert np.allclose(out, -1, rtol=1.1)
def test_minus_input_to_one(prog): wf_sim = WavefunctionSimulator() with local_qvm(): if len(prog._instructions) == 0: print( "Hmm, I'm not sure you have any gates applied to the state. Better add some.." ) else: state = wf_sim.wavefunction(prog) amp = 1 if abs(state[0].real - amp) < 0.0001: print("\nExcellent! You built the state:") print(state) elif abs(state[1].real - amp) < 0.0001 and len( prog._instructions) < 4: print("\nAh shucks, you made:") print(state) print("Maybe you need more gates?") else: print("oops, you built the state:") print(state) print("Perhaps an alternative unitary would work?\n")
def test_pi_three_phase(prog): wf_sim = WavefunctionSimulator() with local_qvm(): if len(prog._instructions) == 0: print( "Hmm, I'm not sure you have any gates applied to the state. Better add some.." ) else: state = wf_sim.wavefunction(prog) amp_plus = 1 / math.sqrt(2) amp_phase = np.exp(1j * np.pi / 3) / math.sqrt(2) if abs(state[0].real - amp_plus) < 0.0001 and abs( state[1].real - amp_phase.real) < 0.0001 and abs( state[1].imag - amp_phase.imag) < 0.0001: print( "\nGood job! You built the state with the relative phase:") print(state) else: print("\nHmm, you built the state:") print(state) print("Maybe try a different gate?\n")
def test_qaoa_on_wfsim(): # ham = PauliSum.from_compact_str("(-1.0)*Z0*Z1 + 0.8*Z0 + (-0.5)*Z1") term1 = PauliTerm("Z", 0, -1) * PauliTerm("Z", 1) term2 = PauliTerm("Z", 0, 0.8) term3 = PauliTerm("Z", 1, -0.5) ham = PauliSum([term1, term2, term3]) params = FourierParams.linear_ramp_from_hamiltonian(ham, n_steps=10, q=2) p0 = params.raw() sim = WavefunctionSimulator() cost_fun = QAOACostFunctionOnWFSim(ham, params, sim, scalar_cost_function=True, nshots=100, noisy=True) with local_qvm(): out = minimize(cost_fun, p0, tol=1e-3, method="Cobyla", options={"maxiter": 500}) wf = sim.wavefunction(cost_fun.prepare_ansatz, memory_map=cost_fun.make_memory_map(params)) assert np.allclose(out["fun"], -1.3, rtol=1.1) assert out["success"] assert np.allclose(wf.probabilities(), [0, 0, 0, 1], rtol=1.5, atol=0.05) print(out)
def test_PrepareAndMeasureOnQVM_QubitPlaceholders(): q1, q2 = QubitPlaceholder(), QubitPlaceholder() prepare_ansatz = Program() param_register = prepare_ansatz.declare("params", memory_type="REAL", memory_size=2) prepare_ansatz.inst(RX(param_register[0], q1)) prepare_ansatz.inst(RX(param_register[1], q2)) def make_memory_map(params): return {"params": params} ham = PauliSum([PauliTerm("Z", q1), PauliTerm("Z", q2)]) qubit_mapping = get_default_qubit_mapping(prepare_ansatz) qvm = get_qc("2q-qvm") with local_qvm(): # qvm = proc.qvm cost_fn = PrepareAndMeasureOnQVM(prepare_ansatz, make_memory_map, qvm=qvm, hamiltonian=ham, enable_logging=True, scalar_cost_function=False, base_numshots=10, qubit_mapping=qubit_mapping) out = cost_fn([np.pi, np.pi / 2], nshots=10) assert np.allclose(cost_fn.log[0].fun, (-1.0, 0.1), rtol=1.1) assert np.allclose(out, (-1, 0.1), rtol=1.1)
def test_PrepareAndMeasureOnWFSim_QubitPlaceholders(): q1, q2 = QubitPlaceholder(), QubitPlaceholder() p = Program() params = p.declare("params", memory_type="REAL", memory_size=2) p.inst(RX(params[0], q1)) p.inst(RX(params[1], q2)) def make_memory_map(params): return {"params": params} ham = PauliSum([PauliTerm("Z", q1), PauliTerm("Z", q2)]) qubit_mapping = get_default_qubit_mapping(p) sim = WavefunctionSimulator() with local_qvm(): cost_fn = PrepareAndMeasureOnWFSim( p, make_memory_map, ham, sim, enable_logging=True, qubit_mapping=qubit_mapping, scalar_cost_function=False, ) out = cost_fn([np.pi, np.pi / 2], nshots=100) assert np.allclose(cost_fn.log[0].fun, (-1.0, 0.1)) assert np.allclose(out, (-1, 0.1))
def test_run_and_measure(local_qvm_quilc): qc = get_qc("9q-generic-qvm") prog = Program(I(8)) trials = 11 with local_qvm(): # Redundant with test fixture. bitstrings = qc.run_and_measure(prog, trials) bitstring_array = np.vstack(bitstrings[q] for q in sorted(qc.qubits())).T assert bitstring_array.shape == (trials, len(qc.qubits()))
def local_qvm_quilc(): """Execute test with local qvm and quilc running""" if shutil.which('qvm') is None or shutil.which('quilc') is None: return pytest.skip("This test requires 'qvm' and 'quilc' " "executables to be installed locally.") with local_qvm() as context: yield context
def test_run_and_measure(local_qvm_quilc): qc = get_qc("9q-generic-qvm") prog = Program(I(8)) trials = 11 # note to devs: this is included as an example in the run_and_measure docstrings # so if you change it here ... change it there! with local_qvm(): # Redundant with test fixture. bitstrings = qc.run_and_measure(prog, trials) bitstring_array = np.vstack(bitstrings[q] for q in qc.qubits()).T assert bitstring_array.shape == (trials, len(qc.qubits()))
def test_QAOACostFunctionOnQVM(): qvm = get_qc("2q-qvm") params = AnnealingParams.linear_ramp_from_hamiltonian(hamiltonian, n_steps=4) with local_qvm(): cost_function = QAOACostFunctionOnQVM(hamiltonian, params=params, qvm=qvm, scalar_cost_function=False) out = cost_function(params.raw(), nshots=1) print("output of QAOACostFunctionOnQVM: ", out)
def test_prep_comp_bitstring(circuit, bitstring): with local_qvm(): wavefunc = make_wf.wavefunction(circuit) probs = wavefunc.get_outcome_probs() bitstring_as_str = "".join(str(x) for x in list(bitstring))[::-1] if probs[bitstring_as_str] != 1: print("It doens't look like the correct state was produced :( ") else: print("Congrats, you prepared the correct state!")
def test_qaoa_on_WFSim(): params = FourierParams.linear_ramp_from_hamiltonian(hamiltonian, n_steps=10, q=2) p0 = params.raw() sim = WavefunctionSimulator() cost_fun = QAOACostFunctionOnWFSim(hamiltonian=hamiltonian, params=params, sim=sim, return_standard_deviation=True, noisy=False) with local_qvm(): out = scipy_optimizer(cost_fun, p0, epsilon=1e-3) print(out)
def test_QAOACostFunctionOnWFSim(): sim = WavefunctionSimulator() params = AnnealingParams.linear_ramp_from_hamiltonian(hamiltonian, n_steps=4) with local_qvm(): cost_function = QAOACostFunctionOnWFSim(hamiltonian, params=params, sim=sim, scalar_cost_function=False, noisy=True, enable_logging=True) out = cost_function(params.raw(), nshots=100) print("Log:", cost_function.log) print("output of QAOACostFunctionOnWFSim: ", out)
def test_bell_state_unitary(prog, flag): wf_sim = WavefunctionSimulator() with local_qvm(): state = wf_sim.wavefunction(prog) amp_plus = 1/math.sqrt(2) amp_minus = -1/math.sqrt(2) if (flag == 'phi+'): if (abs(state[0].real - amp_plus) < 0.0001) and (abs(state[-1].real - amp_plus) < 0.0001): print("\nCongratulations, you built the state:") print(state) else: print("oops, you built the state:") print(state) print("Perhaps an alternative unitary would work?\n") elif (flag == 'phi-'): if (abs(state[0].real - amp_plus) < 0.0001) and (abs(state[-1].real - amp_minus) < 0.0001): print("\nCongratulations, you built the state:") print(state) else: print("oops, you built the state:") print(state) print("Perhaps an alternative unitary would work?\n") elif (flag == 'psi+'): if (abs(state[1].real - amp_plus) < 0.0001) and (abs(state[-2].real - amp_plus) < 0.0001): print("\nCongratulations, you built the state:") print(state) else: print("oops, you built the state:") print(state) print("Perhaps an alternative unitary would work?\n") elif (flag == 'psi-'): if (abs(state[1].real - amp_plus) < 0.0001) and (abs(state[-2].real - amp_minus) < 0.0001): print("\nCongratulations, you built the state:") print(state) else: print("oops, you built the state:") print(state) print("Perhaps an alternative unitary would work?\n") else: raise ValueError('The inputted flag choice is not supported')
def test_vqe_on_QVM(): p0 = [3.1, -1.5, 0, 0] # make it easier when sampling qvm = get_qc("2q-qvm") with local_qvm(): cost_fun = PrepareAndMeasureOnQVM( prepare_ansatz=prepare_ansatz, make_memory_map=lambda p: {"params": p}, hamiltonian=hamiltonian, qvm=qvm, scalar_cost_function=True, nshots=4, base_numshots=50) out = minimize(cost_fun, p0, tol=1e-2, method="Cobyla") print(out) assert np.allclose(out['fun'], -1.3, rtol=1.1) assert out['success']
def test_parameter_infos(): params = ExtendedParams.linear_ramp_from_hamiltonian(hamiltonian, n_steps=2) print(params) p0 = params.raw() print(p0) sim = WavefunctionSimulator() cost_fun = QAOACostFunctionOnWFSim(hamiltonian=hamiltonian, params=params, sim=sim, scalar_cost_function=True, nshots=1, noisy=False) with local_qvm(): out = scipy_optimizer(cost_fun, p0, epsilon=1e-3) print(out)
def test_initial_state(prog): wf_sim = WavefunctionSimulator() with local_qvm(): state = wf_sim.wavefunction(prog) amp = 1 if abs(state[1].real - amp) < 0.0001: print("\nCongratulations, you built the state:") print(state) else: print("oops, you built the state:") print(state) print("Perhaps an alternative unitary would work?\n")
def test_state(prog): wf_sim = WavefunctionSimulator() with local_qvm(): state = wf_sim.wavefunction(prog) amp = 1 / math.sqrt(2) if abs(state[0].real - amp) < 0.0001 and abs(state[1].real - amp) < 0.0001: print("Congratulations, you built the state") print(state) else: print("oops, you built the state") print(state)
def test_vqe_on_WFSim(): sim = WavefunctionSimulator() cost_fun = PrepareAndMeasureOnWFSim( prepare_ansatz=prepare_ansatz, make_memory_map=lambda p: {"params": p}, hamiltonian=hamiltonian, sim=sim, scalar_cost_function=True, nshots=100, noisy=False) with local_qvm(): out = minimize(cost_fun, p0, tol=1e-3, method="COBYLA") wf = sim.wavefunction(prepare_ansatz, {"params": out['x']}) assert np.allclose(wf.probabilities(), [0, 0, 0, 1], rtol=1.5, atol=0.01) assert np.allclose(out['fun'], -1.3) assert out['success']
def test_superposition_unitary(prog): wf_sim = WavefunctionSimulator() with local_qvm(): if len(prog._instructions) == 0: print( "Hmm, I'm not sure you have any gates applied to the state. Better add some.." ) else: state = wf_sim.wavefunction(prog) amp_plus = 1 / math.sqrt(2) amp_minus = -1 / math.sqrt(2) if abs(state[0].real - amp_plus) < 0.0001 and abs( state[1].real - amp_plus) < 0.0001: print("\nGood job! You built the superposition state:") print(state) elif abs(state[0].real - amp_plus) < 0.0001 and abs( state[1].real - amp_minus) < 0.0001: print( "\nNot quite :(, you built a different superposition state:" ) print(state) elif abs(state[0].real - amp_minus) < 0.0001 and abs( state[1].real - amp_plus) < 0.0001: print( "\nNot quite :(, you built a different superposition state:" ) print(state) elif abs(state[0].real - amp_minus) < 0.0001 and abs( state[1].real - amp_minus) < 0.0001: print( "\nNot quite :(, you built a different superposition state:" ) print(state) print( "This state is actually physically indistinguisable from the correct state up to a global phase. However, it's still not quite right." ) else: print("\nHmm, you built the state:") print(state) print("Maybe try a different gate?\n")
def test_two_qubit_reset(prog): wf_sim = WavefunctionSimulator() with local_qvm(): state = wf_sim.wavefunction(prog) amp = 1 if (abs(state[0].real - amp) < 0.0001): print("\nGood job, you built the state:") print(state) else: print("Unfortunately, you built the state:") print(state) print("Possibly try some other unitary?\n")
def test_vqe_on_QVM_QubitPlaceholders(): qubit_mapping = {q0: 0, q1: 1} p0 = [3.1, -1.5, 0, 0] # make it easier when sampling qvm = get_qc("2q-qvm") with local_qvm(): cost_fun = PrepareAndMeasureOnQVM( prepare_ansatz=prepare_ansatz, make_memory_map=lambda p: {"params": p}, hamiltonian=hamiltonian, qvm=qvm, scalar_cost_function=False, base_numshots=50, enable_logging=True, qubit_mapping=qubit_mapping) out = scipy_optimizer(cost_fun, p0, epsilon=1e-2, nshots=4) print(out) print(cost_fun.log) assert np.allclose(out['fun'], -4, rtol=1.1) assert out['success']
def test_plus_input_to_zero(prog): wf_sim = WavefunctionSimulator() with local_qvm(): if len(prog._instructions) == 0: print( "Hmm, I'm not sure you have any gates applied to the state. Better add some.." ) else: state = wf_sim.wavefunction(prog) if abs(state[0].real - 1) < 0.0001: print("\nExcellent! You built the state:") print(state) else: print("oops, you built the state:") print(state) print("Perhaps an alternative unitary would work?\n")
def test_vqe_on_WFSim(): sim = WavefunctionSimulator() cost_fun = PrepareAndMeasureOnWFSim( prepare_ansatz=prepare_ansatz, make_memory_map=lambda p: {"params": p}, hamiltonian=hamiltonian, sim=sim, return_standard_deviation=True, noisy=False) with local_qvm(): out = scipy_optimizer(cost_fun, p0, epsilon=1e-3) print(out) wf = sim.wavefunction(prepare_ansatz, {"params": out['x']}) assert np.allclose(np.abs(wf.amplitudes**2), [0, 0, 0, 1], rtol=1.5, atol=0.01) assert np.allclose(out['fun'], -1.3) assert out['success']
def test_one_phase(prog): wf_sim = WavefunctionSimulator() with local_qvm(): if len(prog._instructions) == 0: print( "Hmm, I'm not sure you have any gates applied to the state. Better add some.." ) else: state = wf_sim.wavefunction(prog) amp = -1 if abs(state[1].real - amp) < 0.0001: print("\nCongratulations, you built the state:") print(state) else: print("oops, you built the state:") print(state) print("Perhaps an alternative unitary would work?\n")
def test_QAOACostFunctionOnWFSim_get_wavefunction(): sim = WavefunctionSimulator() # ham = PauliSum.from_compact_str("0.7*Z0*Z1 + 1.2*Z0*Z2") term1 = PauliTerm("Z", 0, 0.7) * PauliTerm("Z", 1) term2 = PauliTerm("Z", 0, 1.2) * PauliTerm("Z", 2) ham = PauliSum([term1, term2]) timesteps = 2 params = StandardWithBiasParams\ .linear_ramp_from_hamiltonian(ham, timesteps) with local_qvm(): cost_function = QAOACostFunctionOnWFSim(ham, params=params, sim=sim, scalar_cost_function=True, nshots=100) wf = cost_function.get_wavefunction(params.raw()) print(wf.probabilities()) assert np.allclose( wf.probabilities(), np.array([0.01, 0.308, 0.053, 0.13, 0.13, 0.053, 0.308, 0.01]), rtol=1e-2, atol=0.005)
def test_vqe_on_WFSim_QubitPlaceholders(): qubit_mapping = get_default_qubit_mapping(prepare_ansatz) sim = WavefunctionSimulator() cost_fun = PrepareAndMeasureOnWFSim( prepare_ansatz=prepare_ansatz, make_memory_map=lambda p: {"params": p}, hamiltonian=hamiltonian, sim=sim, scalar_cost_function=False, noisy=False, qubit_mapping=qubit_mapping) with local_qvm(): out = scipy_optimizer(cost_fun, p0, epsilon=1e-3) print(out) prog = address_qubits(prepare_ansatz, qubit_mapping=qubit_mapping) wf = sim.wavefunction(prog, {"params": out['x']}) print(wf.probabilities()) assert np.allclose(np.abs(wf.amplitudes**2), [0, 0, 0, 1], rtol=1.5, atol=0.01) assert np.allclose(out['fun'], -4) assert out['success']