def test_group_experiments(): expts = [ # cf above, I removed the inner nesting. Still grouped visually ExperimentSetting(sI(), sX(0) * sI(1)), ExperimentSetting(sI(), sI(0) * sX(1)), ExperimentSetting(sI(), sZ(0) * sI(1)), ExperimentSetting(sI(), sI(0) * sZ(1)), ] suite = TomographyExperiment(expts, Program(), qubits=[0, 1]) grouped_suite = group_experiments(suite) assert len(suite) == 4 assert len(grouped_suite) == 2
def test_measure_observables(forest): expts = [ ExperimentSetting(sI(), o1 * o2) for o1, o2 in itertools.product([sI(0), sX(0), sY(0), sZ(0)], [sI(1), sX(1), sY(1), sZ(1)]) ] suite = TomographyExperiment(expts, program=Program(X(0), CNOT(0, 1)), qubits=[0, 1]) assert len(suite) == 4 * 4 gsuite = group_experiments(suite) assert len(gsuite) == 3 * 3 # can get all the terms with I for free in this case qc = get_qc('2q-qvm') for res in measure_observables(qc, gsuite, n_shots=10_000): if res.setting.out_operator in [sI(), sZ(0), sZ(1), sZ(0) * sZ(1)]: assert np.abs(res.expectation) > 0.9 else: assert np.abs(res.expectation) < 0.1
def test_qc_expectation_on_qvm(client_configuration: QCSClientConfiguration, dummy_compiler: DummyCompiler): # regression test for https://github.com/rigetti/forest-tutorials/issues/2 qc = QuantumComputer(name="testy!", qam=QVM(client_configuration=client_configuration), compiler=dummy_compiler) p = Program() theta = p.declare("theta", "REAL") p += RESET() p += RY(theta, 0) p.wrap_in_numshots_loop(10000) sx = ExperimentSetting(in_state=_pauli_to_product_state(sZ(0)), out_operator=sX(0)) e = Experiment(settings=[sx], program=p) thetas = [-np.pi / 2, 0.0, np.pi / 2] results = [] # Verify that multiple calls to qc.experiment with the same experiment backed by a QVM that # requires_exectutable does not raise an exception. for theta in thetas: results.append(qc.experiment(e, memory_map={"theta": [theta]})) assert np.isclose(results[0][0].expectation, -1.0, atol=0.01) assert np.isclose(results[0][0].std_err, 0) assert results[0][0].total_counts == 20000 # bounds on atol and std_err here are a little loose to try and avoid test flakiness. assert np.isclose(results[1][0].expectation, 0.0, atol=0.1) assert results[1][0].std_err < 0.01 assert results[1][0].total_counts == 20000 assert np.isclose(results[2][0].expectation, 1.0, atol=0.01) assert np.isclose(results[2][0].std_err, 0) assert results[2][0].total_counts == 20000
def test_experiment_result(): er = ExperimentResult( setting=ExperimentSetting(sX(0), sZ(0)), expectation=0.9, stddev=0.05, ) assert str(er) == '(1+0j)*X0→(1+0j)*Z0: 0.9 +- 0.05'
def test_experiment_deser(tmpdir): expts = [ [ ExperimentSetting(TensorProductState(), sX(0) * sI(1)), ExperimentSetting(TensorProductState(), sI(0) * sX(1)), ], [ ExperimentSetting(TensorProductState(), sZ(0) * sI(1)), ExperimentSetting(TensorProductState(), sI(0) * sZ(1)), ], ] suite = Experiment(settings=expts, program=Program(X(0), Y(1))) to_json(f"{tmpdir}/suite.json", suite) suite2 = read_json(f"{tmpdir}/suite.json") assert suite == suite2
def test_stats_from_measurements(): d_results = {0: np.array([0] * 10), 1: np.array([1] * 10)} setting = ExperimentSetting(TensorProductState(), sZ(0) * sX(1)) n_shots = 1000 obs_mean, obs_var = _stats_from_measurements(d_results, setting, n_shots) assert obs_mean == -1.0 assert obs_var == 0.0
def test_is_identity(): pt1 = -1.5j * sI(2) pt2 = 1.5 * sX(1) * sZ(2) assert is_identity(pt1) assert is_identity(pt2 + (-1 * pt2) + sI(0)) assert not is_identity(0 * pt1) assert not is_identity(pt2 + (-1 * pt2))
def test_experiment_result(): er = ExperimentResult( setting=ExperimentSetting(plusX(0), sZ(0)), expectation=0.9, stddev=0.05, total_counts=100, ) assert str(er) == 'X0_0→(1+0j)*Z0: 0.9 +- 0.05'
def train_xor(samples): param = [np.pi,0,0,np.pi,np.pi,np.pi,0,0,np.pi] s = samples[2] sec_reg = QubitPlaceholder() val = sim.expectation(address_qubits(fun_xor(s[1], param, s[0])), [sZ(7)]).real[0] print(address_qubits(fun_xor(s[1], param, s[0]))) print(val) print(s[2]) print(abs(val-s[2])) # x = sim.expectation(address_qubits(p), [sZ(3)]) # print(address_qubits(fun_xor(s[1], sec_reg, s[2], param, s[0]))) # x = sim.expectation(address_qubits(fun_xor(s[1], s[3], x, s[0])), ) # for s in samples: fun = lambda x: abs(sim.expectation(address_qubits(fun_xor(s[1], param, s[0])), [sZ(7)]).real[0] - s[2]) # fun = lambda x: sim.expectation(address_qubits(fun_xor(s[1], sec_reg, s[2], x, s[0]), [sZ(8)*sZ(0)])) res = minimize(fun, np.array(param), method="Nelder-Mead", tol=10**-6) return res.x, res.fun
def test_setting_no_in(): out_ops = _generate_random_paulis(n_qubits=4, n_terms=7) for oop in out_ops: expt = ExperimentSetting(zeros_state(oop.get_qubits()), oop) expt2 = ExperimentSetting.from_str(str(expt)) assert expt == expt2 assert expt2.in_operator == functools.reduce(mul, [sZ(q) for q in oop.get_qubits()], sI()) assert expt2.out_operator == oop
def test_stabilizer_projection_Z(): """ test if we project out the correct state """ stabilizer_state = project_stabilized_state([sZ(0)]) true_state = np.zeros((2, 1)) true_state[0, 0] = 1 assert np.allclose(true_state, stabilizer_state.todense())
def test_tomo_experiment_pre_grouped(): expts = [ [ExperimentSetting(sI(), sX(0) * sI(1)), ExperimentSetting(sI(), sI(0) * sX(1))], [ExperimentSetting(sI(), sZ(0) * sI(1)), ExperimentSetting(sI(), sI(0) * sZ(1))], ] suite = TomographyExperiment( settings=expts, program=Program(X(0), Y(1)), qubits=[0, 1] ) assert len(suite) == 2 # number of groups for es1, es2 in zip(expts, suite): for e1, e2 in zip(es1, es2): assert e1 == e2 prog_str = str(suite).splitlines()[0] assert prog_str == 'X 0; Y 1'
def test_expectation(forest: ForestConnection): # The forest fixture (argument) to this test is to ensure this is # skipped when a forest web api key is unavailable. You could also # pass it to the constructor of WavefunctionSimulator() but it is not # necessary. wfnsim = WavefunctionSimulator() bell = Program( H(0), CNOT(0, 1), ) expects = wfnsim.expectation(bell, [ sZ(0) * sZ(1), sZ(0), sZ(1), sX(0) * sX(1), ]) assert expects.size == 4 np.testing.assert_allclose(expects, [1, 0, 0, 1])
def test_multiaddress(): p = Program() q0, q1 = [QubitPlaceholder() for _ in range(2)] p += exponential_map(sZ(q0) * sZ(q1))(0.5) map1 = {q0: 0, q1: 1} map2 = {q0: 9, q1: 10} p1 = address_qubits(p, map1) with pytest.raises(RuntimeError): _ = p.out() # make sure the original isn't affected assert p1.out() == "CNOT 0 1\nRZ(1.0) 1\nCNOT 0 1\n" p2 = address_qubits(p, map2) assert p1.out() == "CNOT 0 1\nRZ(1.0) 1\nCNOT 0 1\n" assert p2.out() == "CNOT 9 10\nRZ(1.0) 10\nCNOT 9 10\n"
def test_expt_settings_diagonal_in_tpb(): def _expt_settings_diagonal_in_tpb(es1: ExperimentSetting, es2: ExperimentSetting): """ Extends the concept of being diagonal in the same tpb to ExperimentSettings, by determining if the pairs of in_states and out_operators are separately diagonal in the same tpb """ max_weight_in = _max_weight_state([es1.in_state, es2.in_state]) max_weight_out = _max_weight_operator([es1.out_operator, es2.out_operator]) return max_weight_in is not None and max_weight_out is not None expt_setting1 = ExperimentSetting(plusZ(1) * plusX(0), sY(1) * sZ(0)) expt_setting2 = ExperimentSetting(plusY(2) * plusZ(1), sZ(2) * sY(1)) assert _expt_settings_diagonal_in_tpb(expt_setting1, expt_setting2) expt_setting3 = ExperimentSetting(plusX(2) * plusZ(1), sZ(2) * sY(1)) expt_setting4 = ExperimentSetting(plusY(2) * plusZ(1), sX(2) * sY(1)) assert not _expt_settings_diagonal_in_tpb(expt_setting2, expt_setting3) assert not _expt_settings_diagonal_in_tpb(expt_setting2, expt_setting4)
def test_experiment_suite(): expts = [ ExperimentSetting(sI(), sX(0) * sY(1)), ExperimentSetting(sZ(0), sZ(0)), ] suite = TomographyExperiment(settings=expts, program=Program(X(0), Y(1)), qubits=[0, 1]) assert len(suite) == 2 for e1, e2 in zip(expts, suite): # experiment suite puts in groups of length 1 assert len(e2) == 1 e2 = e2[0] assert e1 == e2 prog_str = str(suite).splitlines()[0] assert prog_str == 'X 0; Y 1'
def test_expectation_helper(): n_qubits = 3 wf = np.zeros(shape=((2, ) * n_qubits), dtype=np.complex) wf[0, 0, 0] = 1 z0 = _term_expectation(wf, 0.4 * sZ(0)) assert z0 == 0.4 x0 = _term_expectation(wf, sX(2)) assert x0 == 0
def test_expt_settings_share_ntpb(): expts = [[ ExperimentSetting(zeros_state([0, 1]), sX(0) * sI(1)), ExperimentSetting(zeros_state([0, 1]), sI(0) * sX(1)) ], [ ExperimentSetting(zeros_state([0, 1]), sZ(0) * sI(1)), ExperimentSetting(zeros_state([0, 1]), sI(0) * sZ(1)) ]] for group in expts: for e1, e2 in itertools.combinations(group, 2): assert _max_weight_state([e1.in_state, e2.in_state]) is not None assert _max_weight_operator([e1.out_operator, e2.out_operator]) is not None
def test_expt_settings_diagonal_in_tpb(): expt_setting1 = ExperimentSetting(sZ(1) * sX(0), sY(1) * sZ(0)) expt_setting2 = ExperimentSetting(sY(2) * sZ(1), sZ(2) * sY(1)) assert _expt_settings_diagonal_in_tpb(expt_setting1, expt_setting2) expt_setting3 = ExperimentSetting(sX(2) * sZ(1), sZ(2) * sY(1)) expt_setting4 = ExperimentSetting(sY(2) * sZ(1), sX(2) * sY(1)) assert not _expt_settings_diagonal_in_tpb(expt_setting2, expt_setting3) assert not _expt_settings_diagonal_in_tpb(expt_setting2, expt_setting4)
def test_rotation_programs(): """ Testing the generation of post rotations """ test_term = sZ(0) * sX(20) * sI(100) * sY(5) # note: string comparison of programs requires gates to be in the same order true_rotation_program = Program().inst( [RX(np.pi / 2)(5), RY(-np.pi / 2)(20)]) test_rotation_program = get_rotation_program(test_term) assert true_rotation_program.out() == test_rotation_program.out()
def test_projector_generator(): """ Test if we are getting accurate projectors--multiqubit case """ true_zero_projector = 0.5 * (sZ(0) + sI(0)) zero_projector = projector_generator([0], [0]) assert true_zero_projector == zero_projector one_projector = projector_generator([1], [1]) true_one_projector = 0.5 * (sI(0) - sZ(0)) assert true_one_projector == one_projector lowering_projector = projector_generator([0], [1]) true_lowering_projector = 0.5 * (sX(0) + 1j * sY(0)) assert true_lowering_projector == lowering_projector raising_projector = projector_generator([1], [0]) true_raising_projector = 0.5 * (sX(0) - 1j * sY(0)) assert true_raising_projector == raising_projector
def test_build_symmetrization_memory_maps(): p = Program() s = ExperimentSetting(in_state=sZ(0) * sZ(1), out_operator=sZ(0) * sZ(1)) e = TomographyExperiment(settings=[s], program=p) memory_maps = [ { "symmetrization": [0.0, 0.0] }, { "symmetrization": [0.0, np.pi] }, { "symmetrization": [np.pi, 0.0] }, { "symmetrization": [np.pi, np.pi] }, ] assert e.build_symmetrization_memory_maps([0, 1]) == memory_maps
def test_term_powers(): for qubit in QubitPlaceholder.register(2): pauli_terms = [sI(qubit), sX(qubit), sY(qubit), sZ(qubit)] for pauli_term in pauli_terms: assert pauli_term**0 == sI(qubit) assert pauli_term**1 == pauli_term assert pauli_term**2 == sI(qubit) assert pauli_term**3 == pauli_term with pytest.raises(ValueError): pauli_terms[0]**-1
def error(order, time_step_length): a_pauli = time_step_length * sZ(0) * sY(1) * sX(2) a_program = a_pauli.program b_pauli = time_step_length * sX(0) * sZ(1) * sY(2) b_program = b_pauli.program num_qubits = len(a_program.get_qubits()) assert num_qubits == len(b_program.get_qubits()) a = program_unitary(a_program, num_qubits) b = program_unitary(b_program, num_qubits) a_plus_b = a + b exp_a_plus_b = expmi(time_step_length * a_plus_b) trotter_program = trotterize(a_pauli, b_pauli, trotter_order=order) trotter = program_unitary(trotter_program, num_qubits) return np.linalg.norm(exp_a_plus_b - trotter, np.inf)
def init_ham(N_, D_): global N global D global n global q N = N_ D = D_ if D_ == 2: n = 4 * N_ - 10 q = [sZ(x) for x in range(n)]
def test_max_tpb_overlap_3(): # add another ExperimentSetting to the above expt_setting = ExperimentSetting(PauliTerm.from_compact_str('(1+0j)*Z7Y8Z1Y4Z2Y5Y0X6'), PauliTerm.from_compact_str('(1+0j)*Z4X8Y5X3Y7Y1')) expt_setting2 = ExperimentSetting(sZ(7), sY(1)) p = Program(H(0), H(1), H(2)) qubits = [0, 1, 2] tomo_expt2 = TomographyExperiment([expt_setting, expt_setting2], p, qubits) expected_dict2 = {expt_setting: [expt_setting, expt_setting2]} assert expected_dict2 == _max_tpb_overlap(tomo_expt2)
def test_tomo_experiment_pre_grouped(): expts = [ [ ExperimentSetting(TensorProductState(), sX(0) * sI(1)), ExperimentSetting(TensorProductState(), sI(0) * sX(1)), ], [ ExperimentSetting(TensorProductState(), sZ(0) * sI(1)), ExperimentSetting(TensorProductState(), sI(0) * sZ(1)), ], ] suite = Experiment(settings=expts, program=Program(X(0), Y(1))) assert len(suite) == 2 # number of groups for es1, es2 in zip(expts, suite): for e1, e2 in zip(es1, es2): assert e1 == e2 prog_str = str(suite).splitlines()[3:5] assert prog_str == EXPERIMENT_REPR.splitlines()[4:6]
def test_all_ops_belong_to_tpb(): expts = [ [ ExperimentSetting(sI(), sX(0) * sI(1)), ExperimentSetting(sI(), sI(0) * sX(1)) ], [ ExperimentSetting(sI(), sZ(0) * sI(1)), ExperimentSetting(sI(), sI(0) * sZ(1)) ], ] for group in expts: for e1, e2 in itertools.combinations(group, 2): assert _all_qubits_diagonal_in_tpb(e1.in_operator, e2.in_operator) assert _all_qubits_diagonal_in_tpb(e1.out_operator, e2.out_operator)
def test_group_experiments_greedy(): ungrouped_tomo_expt = TomographyExperiment([[ ExperimentSetting( PauliTerm.from_compact_str('(1+0j)*Z7Y8Z1Y4Z2Y5Y0X6'), PauliTerm.from_compact_str('(1+0j)*Z4X8Y5X3Y7Y1')) ], [ExperimentSetting(sZ(7), sY(1))]], program=Program( H(0), H(1), H(2)), qubits=[0, 1, 2]) grouped_tomo_expt = group_experiments_greedy(ungrouped_tomo_expt) expected_grouped_tomo_expt = TomographyExperiment([[ ExperimentSetting( PauliTerm.from_compact_str('(1+0j)*Z7Y8Z1Y4Z2Y5Y0X6'), PauliTerm.from_compact_str('(1+0j)*Z4X8Y5X3Y7Y1')), ExperimentSetting(sZ(7), sY(1)) ]], program=Program( H(0), H(1), H(2)), qubits=[0, 1, 2]) assert grouped_tomo_expt == expected_grouped_tomo_expt
def test_append(): expts = [ [ ExperimentSetting(sI(), sX(0) * sI(1)), ExperimentSetting(sI(), sI(0) * sX(1)) ], [ ExperimentSetting(sI(), sZ(0) * sI(1)), ExperimentSetting(sI(), sI(0) * sZ(1)) ], ] suite = TomographyExperiment(settings=expts, program=Program(X(0), Y(1)), qubits=[0, 1]) suite.append(ExperimentSetting(sI(), sY(0) * sX(1))) assert (len(str(suite))) > 0
from pyquil.paulis import ID, sX, sY, sZ from pyquil import * from pyquil.gates import H import pyquil.paulis as pl # Pauli term takes an operator "X", "Y", "Z", or "I"; a qubit to act on, and # an optional coefficient. a = 1 * ID() b = -0.75 * sX(0) * sY(1) * sZ(3) c = (5-2j) * sZ(1) * sX(2) # Construct a sum of Pauli terms. sigma = a + b + c print("sigma = {}".format(sigma)) p = Program() p.inst(pl.exponentiate_commuting_pauli_sum(sigma)) print(p)