def test_toffoli_size_of_modular_negate(): rec = DummyEngine(save_commands=True) eng = MainEngine(backend=rec, engine_list=[ AutoReplacerEx( DecompositionRuleSet(modules=[ swap2cnot, multi_not_rules, addition_rules, increment_rules, pivot_flip_rules, offset_rules, comparison_rules, modular_negate_rules, ])), LimitedCapabilityEngine(allow_toffoli=True, ), ]) t = eng.allocate_qureg(5) controls = eng.allocate_qureg(1) workspace = eng.allocate_qureg(2) modulus = 29 ModularNegate(modulus) & controls | t assert 100 < len(rec.received_commands) < 200 assert workspace is not None
def test_toffoli_size_of_modular_offset(): rec = DummyEngine(save_commands=True) eng = MainEngine(backend=rec, engine_list=[ AutoReplacerEx( DecompositionRuleSet(modules=[ pivot_flip_rules, offset_rules, addition_rules, swap2cnot, increment_rules, multi_not_rules, modular_addition_rules, comparison_rules, ])), LimitedCapabilityEngine(allow_toffoli=True), ]) controls = eng.allocate_qureg(15) target = eng.allocate_qureg(16) dirty = eng.allocate_qureg(2) modulus = 0xAEFD offset = 0x9E0A ModularOffsetGate(offset, modulus) & controls | target assert dirty is not None assert 5000 < len(rec.received_commands) < 15000
def test_simple_test_X_eigenvectors(): rule_set = DecompositionRuleSet(modules=[pe, dqft]) eng = MainEngine( backend=Simulator(), engine_list=[ AutoReplacer(rule_set), ], ) N = 150 results = np.array([]) for i in range(N): autovector = eng.allocate_qureg(1) X | autovector H | autovector unit = X ancillas = eng.allocate_qureg(1) QPE(unit) | (ancillas, autovector) All(Measure) | ancillas fasebinlist = [int(q) for q in ancillas] fasebin = ''.join(str(j) for j in fasebinlist) faseint = int(fasebin, 2) phase = faseint / (2.0**(len(ancillas))) results = np.append(results, phase) All(Measure) | autovector eng.flush() num_phase = (results == 0.5).sum() assert num_phase / N >= 0.35, "Statistics phase calculation are not correct (%f vs. %f)" % ( num_phase / N, 0.35, )
def test_toffoli_size_of_bimultiplication(): rec = DummyEngine(save_commands=True) eng = MainEngine(backend=rec, engine_list=[ AutoReplacerEx( DecompositionRuleSet(modules=[ swap2cnot, multi_not_rules, addition_rules, increment_rules, modular_addition_rules, modular_bimultiplication_rules, modular_scaled_addition_rules, pivot_flip_rules, offset_rules, modular_double_rules, rotate_bits_rules, reverse_bits_rules, modular_negate_rules, comparison_rules, ])), LimitedCapabilityEngine(allow_toffoli=True), ]) t1 = eng.allocate_qureg(5) t2 = eng.allocate_qureg(5) controls = eng.allocate_qureg(1) modulus = 29 factor = 17 ModularBimultiplicationGate(factor, modulus) & controls | (t1, t2) assert 5000 < len(rec.received_commands) < 10000
def test_decomposition(angle): for basis_state in ([1, 0], [0, 1]): correct_dummy_eng = DummyEngine(save_commands=True) correct_eng = MainEngine(backend=Simulator(), engine_list=[correct_dummy_eng]) rule_set = DecompositionRuleSet(modules=[rx2rz]) test_dummy_eng = DummyEngine(save_commands=True) test_eng = MainEngine( backend=Simulator(), engine_list=[ AutoReplacer(rule_set), InstructionFilter(rx_decomp_gates), test_dummy_eng, ], ) correct_qb = correct_eng.allocate_qubit() Rx(angle) | correct_qb correct_eng.flush() test_qb = test_eng.allocate_qubit() Rx(angle) | test_qb test_eng.flush() assert correct_dummy_eng.received_commands[1].gate == Rx(angle) assert test_dummy_eng.received_commands[1].gate != Rx(angle) for fstate in ['0', '1']: test = test_eng.backend.get_amplitude(fstate, test_qb) correct = correct_eng.backend.get_amplitude(fstate, correct_qb) assert correct == pytest.approx(test, rel=1e-12, abs=1e-12) Measure | test_qb Measure | correct_qb
def run(x=4, N=7, param="run"): """ :param a: a<N and must be invertible mod[N] :param N: :param x: :param param: :return: |1> --> |(a**x) mod N> """ # build compilation engine list resource_counter = ResourceCounter() rule_set = DecompositionRuleSet(modules=[projectq.libs.math, projectq.setups.decompositions]) compilerengines = [AutoReplacer(rule_set), TagRemover(), LocalOptimizer(3), AutoReplacer(rule_set), TagRemover(), LocalOptimizer(3), resource_counter] # create a main compiler engine if param == "latex": drawing_engine = CircuitDrawer() eng = MainEngine(drawing_engine) arcsinQ(eng, x, N) return drawing_engine if param == "count": eng = MainEngine(resource_counter) arcsinQ(eng, x, N) return resource_counter else: eng = MainEngine(Simulator(), compilerengines) return arcsinQ(eng, x, N)
def run(): # build compilation engine list resource_counter = ResourceCounter() rule_set = DecompositionRuleSet( modules=[projectq.libs.math, projectq.setups.decompositions]) compilerengines = [ AutoReplacer(rule_set), InstructionFilter(high_level_gates), TagRemover(), LocalOptimizer(3), AutoReplacer(rule_set), TagRemover(), LocalOptimizer(3), resource_counter ] # make the compiler and run the circuit on the simulator backend #eng = MainEngine(Simulator(), compilerengines) eng = MainEngine(resource_counter) # print welcome message and ask the user for the number to factor print( "\n\t\033[37mprojectq\033[0m\n\t--------\n\tImplementation of Shor" "\'s algorithm.", end="") N = int(input('\n\tNumber to factor: ')) print("\n\tFactoring N = {}: \033[0m".format(N), end="") # choose a base at random: a = N while not gcd(a, N) == 1: a = random.randint(2, N) print("\na is " + str(a)) if not gcd(a, N) == 1: print("\n\n\t\033[92mOoops, we were lucky: Chose non relative prime" " by accident :)") print("\tFactor: {}\033[0m".format(gcd(a, N))) else: # run the quantum subroutine r = run_shor(eng, N, a, True) print("\n\nr found : " + str(r)) # try to determine the factors if r % 2 != 0: r *= 2 apowrhalf = pow(a, r >> 1, N) f1 = gcd(apowrhalf + 1, N) f2 = gcd(apowrhalf - 1, N) print("f1 = {}, f2 = {}".format(f1, f2)) if ((not f1 * f2 == N) and f1 * f2 > 1 and int(1. * N / (f1 * f2)) * f1 * f2 == N): f1, f2 = f1 * f2, int(N / (f1 * f2)) if f1 * f2 == N and f1 > 1 and f2 > 1: print( "\n\n\t\033[92mFactors found :-) : {} * {} = {}\033[0m".format( f1, f2, N)) else: print("\n\n\t\033[91mBad luck: Found {} and {}\033[0m".format( f1, f2)) return resource_counter # print resource usage
def main(): x = 2 modulus = 2 for reg_size in range(2, 20): reg_max_val = 1 << reg_size while True: modulus = random.randint(reg_max_val // 2 + 1, reg_max_val - 1) x = random.randint(2, modulus - 1) if modulus % 2 != 0 and fractions.gcd(x, modulus) == 1: break cnt = ResourceCounter() eng = MainEngine( backend=DummyEngine(), engine_list=[ AutoReplacerEx(DecompositionRuleSet(modules=[decompositions])), LimitedCapabilityEngine(allow_toffoli=True, allow_single_qubit_gates=True, allow_classes=[]), cnt, ]) v1 = eng.allocate_qureg(reg_size) v2 = eng.allocate_qureg(reg_size) c = eng.allocate_qubit() gate = ModularBimultiplicationGate(x, modulus) gate & c | (v1, v2) print() print() print("Register Size: {}".format(reg_size)) print("Gate count for controlled {}".format(gate)) print("\t{}".format(cnt).replace('\n', '\n\t'))
def test_toffoli_size_of_modular_addition(): rec = DummyEngine(save_commands=True) eng = MainEngine(backend=rec, engine_list=[ AutoReplacerEx( DecompositionRuleSet(modules=[ pivot_flip_rules, offset_rules, addition_rules, swap2cnot, increment_rules, multi_not_rules, modular_addition_rules, comparison_rules, ])), LimitedCapabilityEngine(allow_toffoli=True), ]) controls = eng.allocate_qureg(15) target1 = eng.allocate_qureg(16) target2 = eng.allocate_qureg(16) modulus = 0xAEFD ModularAdditionGate(modulus) & controls | (target1, target2) assert 10000 < len(rec.received_commands) < 15000
def test_Ph_eigenvectors(): rule_set = DecompositionRuleSet(modules=[pe, dqft]) eng = MainEngine(backend=Simulator(), engine_list=[ AutoReplacer(rule_set), ]) results = np.array([]) for i in range(100): autovector = eng.allocate_qureg(1) theta = cmath.pi * 2. * 0.125 unit = Ph(theta) ancillas = eng.allocate_qureg(3) QPE(unit) | (ancillas, autovector) All(Measure) | ancillas fasebinlist = [int(q) for q in ancillas] fasebin = ''.join(str(j) for j in fasebinlist) faseint = int(fasebin, 2) phase = faseint / (2.**(len(ancillas))) results = np.append(results, phase) All(Measure) | autovector eng.flush() num_phase = (results == 0.125).sum() assert num_phase / 100. >= 0.35, "Statistics phase calculation are not correct (%f vs. %f)" % ( num_phase / 100., 0.35)
def run_adder(a=11, b=1, param="simulation"): # build compilation engine list resource_counter = ResourceCounter() rule_set = DecompositionRuleSet( modules=[projectq.libs.math, projectq.setups.decompositions]) compilerengines = [ AutoReplacer(rule_set), TagRemover(), LocalOptimizer(3), AutoReplacer(rule_set), TagRemover(), LocalOptimizer(3), resource_counter ] # create a main compiler engine if param == "latex": drawing_engine = CircuitDrawer() eng2 = MainEngine(drawing_engine) [xa, xb] = initialisation(eng2, a, b) adder(eng2, xa, xb) measure(eng2, xa, xb) print(drawing_engine.get_latex()) else: eng = MainEngine(Simulator(), compilerengines) [xa, xb] = initialisation(eng, a, b) adder(eng, xa, xb) print(measure(eng, xa, xb))
def test_x_gate_invalid(): sim = ClassicalSimulator() eng = MainEngine(sim, [AutoReplacer(DecompositionRuleSet())]) a = eng.allocate_qureg(2) with pytest.raises(ValueError): X | a
def simulate_sample_period(base, modulus): sim = Simulator() eng = MainEngine(backend=sim, engine_list=[ AutoReplacerEx( DecompositionRuleSet(modules=[decompositions])), LimitedCapabilityEngine( allow_arithmetic= not DECOMPOSE_INTO_TOFFOLIS_AND_GO_VERY_VERY_SLOW, allow_toffoli=True, allow_single_qubit_gates=True), ]) n = int(math.ceil(math.log(modulus, 2))) ancilla_qureg = eng.allocate_qureg(n) for q in ancilla_qureg[:-1]: if random.random() < 0.5: X | q before = ancilla_qureg.measure() result = shor_find_period(base=base, modulus=modulus, precision=n * 2, phase_qubit=eng.allocate_qubit(), work_qureg=eng.allocate_qureg(n), ancilla_qureg=ancilla_qureg) after = ancilla_qureg.measure() assert after == before return result
def ibm_default_engines(): rule_set = DecompositionRuleSet(modules=[projectq.setups.decompositions]) return [TagRemover(), LocalOptimizer(10), AutoReplacer(rule_set), TagRemover(), IBMCNOTMapper(), LocalOptimizer(10)]
def test_available_gates(): sim = ClassicalSimulator() eng = MainEngine(sim, [AutoReplacer(DecompositionRuleSet())]) a = eng.allocate_qubit() X | a NOT | a Measure | a eng.flush()
def test_decomposition(): for basis_state_index in range(0, 16): basis_state = [0] * 16 basis_state[basis_state_index] = 1.0 correct_dummy_eng = DummyEngine(save_commands=True) correct_eng = MainEngine(backend=Simulator(), engine_list=[correct_dummy_eng]) rule_set = DecompositionRuleSet(modules=[cnu2toffoliandcu]) test_dummy_eng = DummyEngine(save_commands=True) test_eng = MainEngine( backend=Simulator(), engine_list=[ AutoReplacer(rule_set), InstructionFilter(_decomp_gates), test_dummy_eng, ], ) test_sim = test_eng.backend correct_sim = correct_eng.backend correct_qb = correct_eng.allocate_qubit() correct_ctrl_qureg = correct_eng.allocate_qureg(3) correct_eng.flush() test_qb = test_eng.allocate_qubit() test_ctrl_qureg = test_eng.allocate_qureg(3) test_eng.flush() correct_sim.set_wavefunction(basis_state, correct_qb + correct_ctrl_qureg) test_sim.set_wavefunction(basis_state, test_qb + test_ctrl_qureg) with Control(test_eng, test_ctrl_qureg[:2]): Rx(0.4) | test_qb with Control(test_eng, test_ctrl_qureg): Ry(0.6) | test_qb with Control(test_eng, test_ctrl_qureg): X | test_qb with Control(correct_eng, correct_ctrl_qureg[:2]): Rx(0.4) | correct_qb with Control(correct_eng, correct_ctrl_qureg): Ry(0.6) | correct_qb with Control(correct_eng, correct_ctrl_qureg): X | correct_qb test_eng.flush() correct_eng.flush() assert len(correct_dummy_eng.received_commands) == 9 assert len(test_dummy_eng.received_commands) == 25 for fstate in range(16): binary_state = format(fstate, '04b') test = test_sim.get_amplitude(binary_state, test_qb + test_ctrl_qureg) correct = correct_sim.get_amplitude(binary_state, correct_qb + correct_ctrl_qureg) assert correct == pytest.approx(test, rel=1e-12, abs=1e-12) All(Measure) | test_qb + test_ctrl_qureg All(Measure) | correct_qb + correct_ctrl_qureg test_eng.flush(deallocate_qubits=True) correct_eng.flush(deallocate_qubits=True)
def test_wrong_number_of_angles(): rule_set = DecompositionRuleSet(modules=[ucr2cnot]) eng = MainEngine( backend=DummyEngine(), engine_list=[AutoReplacer(rule_set), InstructionFilter(_decomp_gates)]) qb = eng.allocate_qubit() with pytest.raises(ValueError): UniformlyControlledRy([0.1, 0.2]) | ([], qb)
def test_complex_aa(): rule_set = DecompositionRuleSet(modules=[aa]) eng = MainEngine( backend=Simulator(), engine_list=[ AutoReplacer(rule_set), ], ) system_qubits = eng.allocate_qureg(6) # Prepare the control qubit in the |-> state control = eng.allocate_qubit() X | control H | control # Creates the initial state form the Algorithm complex_algorithm(eng, system_qubits) # Get the probabilty of getting the marked state before the AA # to calculate the number of iterations eng.flush() prob000000 = eng.backend.get_probability('000000', system_qubits) prob111111 = eng.backend.get_probability('111111', system_qubits) total_amp_before = math.sqrt(prob000000 + prob111111) theta_before = math.asin(total_amp_before) # Apply Quantum Amplitude Amplification the correct number of times # Theta is calculated previously using get_probability # We calculate also the theoretical final probability # of getting the good state num_it = int(math.pi / (4.0 * theta_before) + 1) theoretical_prob = math.sin((2 * num_it + 1.0) * theta_before)**2 with Loop(eng, num_it): QAA(complex_algorithm, complex_oracle) | (system_qubits, control) # Get the probabilty of getting the marked state after the AA # to compare with the theoretical probability after the AA eng.flush() prob000000 = eng.backend.get_probability('000000', system_qubits) prob111111 = eng.backend.get_probability('111111', system_qubits) total_prob_after = prob000000 + prob111111 All(Measure) | system_qubits H | control Measure | control eng.flush() assert total_prob_after == pytest.approx( theoretical_prob, abs=1e-2 ), "The obtained probability is less than expected %f vs. %f" % ( total_prob_after, theoretical_prob, )
def get_engine_list(): rule_set = DecompositionRuleSet(modules=[projectq.setups.decompositions]) return [ TagRemover(), LocalOptimizer(10), AutoReplacer(rule_set), TagRemover(), LocalOptimizer(10) ]
def run_inv(a=11, b=1, param="simulation"): # build compilation engine list resource_counter = ResourceCounter() rule_set = DecompositionRuleSet(modules=[projectq.libs.math, projectq.setups.decompositions]) compilerengines = [AutoReplacer(rule_set), TagRemover(), LocalOptimizer(3), AutoReplacer(rule_set), TagRemover(), LocalOptimizer(3), resource_counter] # create a main compiler engine a1 = a b1 = b if a == 0: a1 = 1 if b == 0: b1 = 1 n = max(int(math.log(a1, 2)), int(math.log(b1, 2))) + 1 if param == "latex": drawing_engine = CircuitDrawer() eng2 = MainEngine(drawing_engine) xa = initialisation_n(eng2, a, n + 1) xb = initialisation_n(eng2, b, n + 1) # b --> phi(b) QFT | xb phi_adder(eng2, xa, xb) with Dagger(eng2): QFT | xb All(Measure) | xa All(Measure) | xb eng2.flush() print(drawing_engine.get_latex()) else: eng = MainEngine(Simulator(), compilerengines) xa = initialisation_n(eng, a, n + 1) xb = initialisation_n(eng, b, n + 1) # b --> phi(b) QFT | xb with Dagger(eng): phi_adder(eng, xa, xb) with Dagger(eng): QFT | xb All(Measure) | xa All(Measure) | xb eng.flush() n = n+1 measurements_a = [0] * n measurements_b = [0] * n for k in range(n): measurements_a[k] = int(xa[k]) measurements_b[k] = int(xb[k]) return [measurements_a, meas2int(measurements_b), measurements_b]
def test_no_control_qubits(): rule_set = DecompositionRuleSet(modules=[ucr2cnot]) eng = MainEngine( backend=DummyEngine(), engine_list=[AutoReplacer(rule_set), InstructionFilter(_decomp_gates)]) qb = eng.allocate_qubit() with pytest.raises(TypeError): UniformlyControlledRy([0.1]) | qb
def test_chooser_Ry_reducer_synthetic(): backend = DummyEngine(save_commands=True) rule_set = DecompositionRuleSet( modules=[projectq.libs.math, projectq.setups.decompositions]) engine_list = [ AutoReplacer(rule_set, chooser_Ry_reducer), TagRemover(), InstructionFilter(filter_gates), ] eng = MainEngine(backend=backend, engine_list=engine_list) control = eng.allocate_qubit() target = eng.allocate_qubit() CNOT | (control, target) CNOT | (control, target) eng.flush() idx0 = len(backend.received_commands) - 2 idx1 = len(backend.received_commands) CNOT | (control, target) eng.flush() assert isinstance(backend.received_commands[idx0].gate, Ry) assert isinstance(backend.received_commands[idx1].gate, Ry) assert (backend.received_commands[idx0].gate.get_inverse() == backend.received_commands[idx1].gate) eng = MainEngine(backend=backend, engine_list=engine_list) control = eng.allocate_qubit() target = eng.allocate_qubit() H | target eng.flush() idx0 = len(backend.received_commands) - 2 idx1 = len(backend.received_commands) H | target eng.flush() assert isinstance(backend.received_commands[idx0].gate, Ry) assert isinstance(backend.received_commands[idx1].gate, Ry) assert (backend.received_commands[idx0].gate.get_inverse() == backend.received_commands[idx1].gate) eng = MainEngine(backend=backend, engine_list=engine_list) control = eng.allocate_qubit() target = eng.allocate_qubit() Rz(1.23456) | target eng.flush() idx0 = len(backend.received_commands) - 2 idx1 = len(backend.received_commands) Rz(1.23456) | target eng.flush() assert isinstance(backend.received_commands[idx0].gate, Ry) assert isinstance(backend.received_commands[idx1].gate, Ry) assert (backend.received_commands[idx0].gate.get_inverse() == backend.received_commands[idx1].gate)
def test_ibm_backend_functional_test(monkeypatch): correct_info = ('{"name": "ProjectQ Experiment", "qasm": "\\ninclude \\"' 'qelib1.inc\\";\\nqreg q[5];\\ncreg c[5];\\nh q[0];\\ncx' ' q[0], q[2];\\ncx q[0], q[1];\\ntdg q[0];\\nsdg q[0];\\' 'nmeasure q[0] -> c[0];\\nmeasure q[2] -> c[2];\\nmeasure' ' q[1] -> c[1];", "codeType": "QASM2"}') # patch send def mock_send(*args, **kwargs): assert json.loads(args[0]) == json.loads(correct_info) return {'date': '2017-01-19T14:28:47.622Z', 'data': {'time': 14.429004907608032, 'serialNumberDevice': 'Real5Qv1', 'p': {'labels': ['00000', '00001', '00010', '00011', '00100', '00101', '00110', '00111'], 'values': [0.4521484375, 0.0419921875, 0.0185546875, 0.0146484375, 0.005859375, 0.0263671875, 0.0537109375, 0.38671875], 'qubits': [0, 1, 2]}, 'qasm': ('...')}} monkeypatch.setattr(_ibm, "send", mock_send) backend = _ibm.IBMBackend(verbose=True) # no circuit has been executed -> raises exception with pytest.raises(RuntimeError): backend.get_probabilities([]) rule_set = DecompositionRuleSet(modules=[projectq.setups.decompositions]) engine_list = [TagRemover(), LocalOptimizer(10), AutoReplacer(rule_set), TagRemover(), IBMCNOTMapper(), LocalOptimizer(10)] eng = MainEngine(backend=backend, engine_list=engine_list) unused_qubit = eng.allocate_qubit() qureg = eng.allocate_qureg(3) # entangle the qureg Entangle | qureg Tdag | qureg[0] Sdag | qureg[0] # measure; should be all-0 or all-1 Measure | qureg # run the circuit eng.flush() prob_dict = eng.backend.get_probabilities([qureg[0], qureg[2], qureg[1]]) assert prob_dict['111'] == pytest.approx(0.38671875) assert prob_dict['101'] == pytest.approx(0.0263671875) with pytest.raises(RuntimeError): eng.backend.get_probabilities(eng.allocate_qubit())
def test_decomposition_errors(gate_matrix): test_gate = BasicGate() test_gate.matrix = np.matrix(gate_matrix) rule_set = DecompositionRuleSet(modules=[arb1q]) eng = MainEngine(backend=DummyEngine(), engine_list=[AutoReplacer(rule_set), InstructionFilter(z_y_decomp_gates)]) qb = eng.allocate_qubit() with pytest.raises(Exception): test_gate | qb
def get_engine_list(): """Return the default list of compiler engine.""" rule_set = DecompositionRuleSet(modules=[projectq.setups.decompositions]) return [ TagRemover(), LocalOptimizer(10), AutoReplacer(rule_set), TagRemover(), LocalOptimizer(10) ]
def test_decomposition(angle): """ Test that this decomposition of Rz produces correct amplitudes Note that this function tests each DecompositionRule in rz2rx.all_defined_decomposition_rules """ decomposition_rule_list = rz2rx.all_defined_decomposition_rules for rule in decomposition_rule_list: for basis_state in ([1, 0], [0, 1]): correct_dummy_eng = DummyEngine(save_commands=True) correct_eng = MainEngine(backend=Simulator(), engine_list=[correct_dummy_eng]) rule_set = DecompositionRuleSet(rules=[rule]) test_dummy_eng = DummyEngine(save_commands=True) test_eng = MainEngine(backend=Simulator(), engine_list=[ AutoReplacer(rule_set), InstructionFilter(rz_decomp_gates), test_dummy_eng ]) correct_qb = correct_eng.allocate_qubit() Rz(angle) | correct_qb correct_eng.flush() test_qb = test_eng.allocate_qubit() Rz(angle) | test_qb test_eng.flush() # Create empty vectors for the wave vectors for the correct and # test qubits correct_vector = np.zeros((2, 1), dtype=np.complex_) test_vector = np.zeros((2, 1), dtype=np.complex_) i = 0 for fstate in ['0', '1']: test = test_eng.backend.get_amplitude(fstate, test_qb) correct = correct_eng.backend.get_amplitude(fstate, correct_qb) correct_vector[i] = correct test_vector[i] = test i += 1 # Necessary to transpose vector to use matrix dot product test_vector = test_vector.transpose() # Remember that transposed vector should come first in product vector_dot_product = np.dot(test_vector, correct_vector) assert np.absolute(vector_dot_product) == pytest.approx(1, rel=1e-12, abs=1e-12) Measure | test_qb Measure | correct_qb
def test_decomposition(gate_matrix): # Create single qubit gate with gate_matrix test_gate = MatrixGate() test_gate.matrix = np.matrix(gate_matrix) for basis_state in ([1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]): correct_dummy_eng = DummyEngine(save_commands=True) correct_eng = MainEngine(backend=Simulator(), engine_list=[correct_dummy_eng]) rule_set = DecompositionRuleSet(modules=[carb1q]) test_dummy_eng = DummyEngine(save_commands=True) test_eng = MainEngine( backend=Simulator(), engine_list=[ AutoReplacer(rule_set), InstructionFilter(_decomp_gates), test_dummy_eng, ], ) test_sim = test_eng.backend correct_sim = correct_eng.backend correct_qb = correct_eng.allocate_qubit() correct_ctrl_qb = correct_eng.allocate_qubit() correct_eng.flush() test_qb = test_eng.allocate_qubit() test_ctrl_qb = test_eng.allocate_qubit() test_eng.flush() correct_sim.set_wavefunction(basis_state, correct_qb + correct_ctrl_qb) test_sim.set_wavefunction(basis_state, test_qb + test_ctrl_qb) with Control(test_eng, test_ctrl_qb): test_gate | test_qb with Control(correct_eng, correct_ctrl_qb): test_gate | correct_qb test_eng.flush() correct_eng.flush() assert correct_dummy_eng.received_commands[3].gate == test_gate assert test_dummy_eng.received_commands[3].gate != test_gate for fstate in ['00', '01', '10', '11']: test = test_sim.get_amplitude(fstate, test_qb + test_ctrl_qb) correct = correct_sim.get_amplitude(fstate, correct_qb + correct_ctrl_qb) assert correct == pytest.approx(test, rel=1e-12, abs=1e-12) All(Measure) | test_qb + test_ctrl_qb All(Measure) | correct_qb + correct_ctrl_qb test_eng.flush(deallocate_qubits=True) correct_eng.flush(deallocate_qubits=True)
def get_quantum_engine(): # Create a main compiler engine with a simulator backend: backend = projectq_simulator(gate_fusion=True) cache_depth = 10 rule_set = DecompositionRuleSet(modules=[projectq.setups.decompositions]) engines = [TagRemover(), LocalOptimizer(cache_depth), AutoReplacer(rule_set)] compiler_engine = MainEngine(backend=backend, engine_list=engines) return compiler_engine
def get_hiq_quantum_engine(): from hiq.projectq.backends import SimulatorMPI backend = SimulatorMPI(gate_fusion=True) cache_depth = 10 rule_set = DecompositionRuleSet(modules=[projectq.setups.decompositions]) engines = [TagRemover(), LocalOptimizer(cache_depth), AutoReplacer(rule_set)] compiler_engine = MainEngine(backend=backend, engine_list=engines) return compiler_engine return
def get_engine_list(): rule_set = DecompositionRuleSet(modules=[projectq.setups.decompositions]) return [ TagRemover(), LocalOptimizer(10), AutoReplacer(rule_set), TagRemover(), IBM5QubitMapper(), SwapAndCNOTFlipper(ibmqx4_connections), LocalOptimizer(10) ]