Exemplo n.º 1
0
 def test_1000_qubit_gate_chain_creation(self):
     # qubits 0 and 1 is not connected
     hw = hardware_by_name({
         "hardware": {
             "gate_set": ["Cnot"],
             "num_qubits": 1000,
             "adj_matrix": np.ones((1000, 1000)).tolist(),
         }
     })
     gate_chain = GateChain(hw)
     cnot = gate_by_name("Cnot")()
     gate_chain.add_gate(cnot, [0, 1])  # Apply CNOT gate to qubits 0 and 1
     gate_chain.add_gate(cnot, [1, 0])  # Apply CNOT gate to qubits 1 and 0
Exemplo n.º 2
0
    def next(self):
        self.id += 1
        chain = GateChain(self._quantum_hardware)

        if "chain_length" in self._cfg:
            chain_length = self._cfg["chain_length"]
        elif "chain_length_max" in self._cfg:
            max_length = self._cfg["chain_length_max"]
            min_length = 0
            if "chain_length_max" in self._cfg:
                min_length = self._cfg["chain_length_min"]
            chain_length = self.np_random.randint(min_length, max_length + 1)
        else:
            raise Exception("No chain_length specified")

        two_qubit_pos = []
        if self.two_qubit_gate_num_upper_bound is not None:
            two_qubit_number = self.np_random.randint(
                self.two_qubit_gate_num_lower_bound,
                self.two_qubit_gate_num_upper_bound + 1)
            two_qubit_pos = self.np_random.choice(range(chain_length),
                                                  two_qubit_number,
                                                  replace=False)

        for i in range(chain_length):
            if self.depth_limit is not None and chain.get_depth(
            ) >= self.depth_limit:
                break

            if i in two_qubit_pos:
                action = self.np_random.choice(
                    range(len(self.two_qubit_actions)))
                action_name, gate_class, appy_to_qubits = self.two_qubit_actions[
                    action]
            else:
                action = self.np_random.choice(range(len(self._actions)),
                                               p=self._actions_probabilities)
                action_name, gate_class, appy_to_qubits = self._actions[action]
            if gate_class == U3:
                angles = self.np_random.uniform(low=0, high=2 * np.pi, size=3)
                gate = gate_class(*angles)
            else:
                gate = gate_class()
            chain.add_gate(gate, appy_to_qubits)

        return chain, self.id
Exemplo n.º 3
0
 def test_matrix_calculation_5q(self):
     basepath = path.dirname(__file__)
     #f = path.abspath(path.join(basepath, "matrix_test_5q.qasm"))
     f = path.abspath(
         path.join(basepath, "..", "qasm_files", "general", "5q.qasm"))
     gate_chain = GateChain.from_qasm(f)
     qiskit_circ = QuantumCircuit.from_qasm_file(f)
     qiskit_matrix = Operator(qiskit_circ).data
     np.testing.assert_almost_equal(gate_chain.matrix, qiskit_matrix)
Exemplo n.º 4
0
    def test_2q_qasm_parser(self):
        basepath = path.dirname(__file__)
        input_dir = path.abspath(
            path.join(basepath, "..", "qasm_files", "general", "2q.qasm"))
        test_dir = path.dirname(path.abspath(__file__))
        output_dir = path.join(test_dir, "2q_result.qasm")
        gate_chain = GateChain.from_qasm(input_dir)
        gate_chain.save_to_qasm(output_dir, qreg_name="q")

        file = open(input_dir, mode="r", encoding="utf-8-sig")
        lines_ref = file.readlines()
        file.close()
        file = open(output_dir, mode="r", encoding="utf-8-sig")
        lines_res = file.readlines()
        file.close()
        np.testing.assert_equal(lines_res, lines_ref)
Exemplo n.º 5
0
    def run(self, target, run_analyser=True):
        with tempfile.TemporaryDirectory() as tmpdirname:
            fname = os.path.join(tmpdirname, "target.qasm")
            target.save_to_qasm(fname, qreg_name="q")
            with open(fname) as file:
                qasm_data = file.read()
        original_circuit = circuit_from_qasm(qasm_data)
        start_time = timer()
        # only 'greedy' routing is implemented in Cirq
        swap_networks: List[ccr.SwapNetwork] = []
        routing_attempts = 1
        with suppress(KeyError):
            routing_attempts = self._cfg["routing_attempts"]
        for _ in range(routing_attempts):
            swap_network = ccr.route_circuit(original_circuit,
                                             self.cirq_hardware,
                                             router=None,
                                             algo_name="greedy")
            swap_networks.append(swap_network)
        assert len(swap_networks) > 0, "Unable to get routing for circuit"
        # Sort by the least number of qubits first (as routing sometimes adds extra ancilla qubits),
        # and then the length of the circuit second.
        swap_networks.sort(key=lambda swap_network: (len(
            swap_network.circuit.all_qubits()), len(swap_network.circuit)))
        routed_circuit = swap_networks[0].circuit

        qubit_order = {
            LineQubit(n): NamedQubit(f"q_{n}")
            for n in range(self.quantum_hardware.num_qubits)
        }

        # decompose composite gates
        no_decomp = lambda op: isinstance(op.gate, CNotPowGate)
        opt = ExpandComposite(no_decomp=no_decomp)
        opt.optimize_circuit(routed_circuit)

        self.execution_time = timer() - start_time

        qasm_data = routed_circuit.to_qasm(qubit_order=qubit_order)
        lines = qasm_data.split("\n")
        gate_chain = GateChain.from_qasm_list_of_lines(lines,
                                                       quantum_hardware=None)
        if run_analyser:
            self.analyse(target, gate_chain)
            self.analyser_report["Execution Time"] = self.execution_time
        return gate_chain
Exemplo n.º 6
0
def compare_matrix_to_qiskit(num_qubits, qasm_gate_name, args, qubits):

    if args is not None:
        args_str = "({})".format(", ".join([str(a) for a in args]))
    else:
        args_str = ""

    conn_str = ", ".join(["q[{}]".format(q) for q in qubits])

    qasm = ("OPENQASM 2.0;\n"
            'include "qelib1.inc";\n'
            f"qreg q[{num_qubits}];\n"
            f"{qasm_gate_name}{args_str} {conn_str};\n")

    gate_chain = GateChain.from_qasm_string(qasm)
    qiskit_circ = QuantumCircuit.from_qasm_str(qasm)
    qiskit_matrix = Operator(qiskit_circ).data
    np.testing.assert_almost_equal(fidelity(qiskit_matrix, gate_chain.matrix),
                                   1)
Exemplo n.º 7
0
 def test_add_2qubit_gate_unconnected_force(self):
     # qubits 0 and 1 is not connected
     hw = hardware_by_name({
         "hardware": {
             "gate_set": ["Cnot"],
             "num_qubits": 2,
             "adj_matrix": [[0, 0], [0, 0]]
         }
     })
     gate_chain = GateChain(hw)
     cnot = gate_by_name("Cnot")()
     gate_chain.add_gate(
         cnot, [0, 1],
         force_connection=True)  # Apply CNOT gate to qubits 0 and 1
     gate_chain.add_gate(
         cnot, [1, 0],
         force_connection=True)  # Apply CNOT gate to qubits 1 and 0
Exemplo n.º 8
0
    def run(self, target, run_analyser=True):
        with tempfile.TemporaryDirectory() as tmpdirname:
            fname = os.path.join(tmpdirname, "target.qasm")
            target.save_to_qasm(fname, qreg_name="q")
            with open(fname) as file:
                qasm_data = file.read()
        optimised_circuit = circuit_from_qasm(qasm_data)

        start_time = timer()
        # Push Z gates toward the end of the circuit
        eject_z = cirq.optimizers.EjectZ()
        eject_z.optimize_circuit(optimised_circuit)
        # Push X, Y, and PhasedXPow gates toward the end of the circuit
        eject_paulis = cirq.optimizers.EjectPhasedPaulis()
        eject_paulis.optimize_circuit(optimised_circuit)
        # Merge single qubit gates into PhasedX and PhasedZ gates
        cirq.merge_single_qubit_gates_into_phased_x_z(optimised_circuit)
        # drop negligible gates
        drop_neg = cirq.optimizers.DropNegligible()
        drop_neg.optimize_circuit(optimised_circuit)
        # drop empty moments
        drop_empty = cirq.optimizers.DropEmptyMoments()
        drop_empty.optimize_circuit(optimised_circuit)
        self.execution_time = timer() - start_time
        qubit_order = {
            NamedQubit(f'q_{n}'): NamedQubit(f'q_{n}')
            for n in range(target.quantum_hardware.num_qubits)
        }
        qasm_data = optimised_circuit.to_qasm(qubit_order=qubit_order)
        lines = qasm_data.split("\n")
        gate_chain = GateChain.from_qasm_list_of_lines(lines,
                                                       quantum_hardware=None)
        if run_analyser:
            self.analyse(target, gate_chain)
            self.analyser_report["Execution Time"] = self.execution_time
        return gate_chain
Exemplo n.º 9
0
    def run(self, target, run_analyser=True):
        with tempfile.TemporaryDirectory() as tmpdirname:
            fname = os.path.join(tmpdirname, "target.qasm")
            target.save_to_qasm(fname, qreg_name="q")
            original_circuit = QuantumCircuit.from_qasm_file(fname)

        start_time = timer()
        optimised_circuit = transpile(
            original_circuit,
            backend=self.qiskit_hardware,
            seed_transpiler=self._cfg["seed_transpiler"],
            optimization_level=0,
            routing_method=self._cfg["routing_method"],
        )
        self.execution_time = timer() - start_time

        qasm_data = optimised_circuit.qasm()
        lines = qasm_data.split("\n")
        gate_chain = GateChain.from_qasm_list_of_lines(lines,
                                                       quantum_hardware=None)
        if run_analyser:
            self.analyse(target, gate_chain)
            self.analyser_report["Execution Time"] = self.execution_time
        return gate_chain
Exemplo n.º 10
0
 def test_add_2qubit_gate_unconnected(self):
     # qubits 0 and 1 is not connected
     hw = hardware_by_name({
         "hardware": {
             "gate_set": ["Cnot"],
             "num_qubits": 2,
             "adj_matrix": [[0, 0], [0, 0]]
         }
     })
     gate_chain = GateChain(hw)
     cnot = gate_by_name("Cnot")()
     with self.assertRaises(NoQubitConnectionError):
         gate_chain.add_gate(
             cnot, [0, 1]
         )  # Apply CNOT gate to unconnected qubits 0 and 1, must be an error
     with self.assertRaises(NoQubitConnectionError):
         gate_chain.add_gate(
             cnot, [1, 0]
         )  # Apply CNOT gate to unconnected qubits 1 and 0, must be an error
Exemplo n.º 11
0
 def next(self):
     qasm_f = self.qasm_list[self.qasm_number]
     chain = GateChain.from_qasm(qasm_f, None)
     self.qasm_number += 1
     return chain, splitext(basename(qasm_f))[0]
Exemplo n.º 12
0
    def test_reverse_matrix_building_order(self):
        hw = hardware_by_name({
            "hardware": {
                "gate_set": ["Cnot"],
                "num_qubits": 2,
                "adj_matrix": [[0, 1], [1, 0]]
            }
        })
        gate_chain = GateChain(hw)
        cnot = gate_by_name("Cnot")()
        rx30 = gate_by_name("Rx(30)")()
        rz30 = gate_by_name("Rz(30)")()

        gate_chain.add_gate_left(cnot, [0, 1])
        gate_chain.matrix
        gate_chain.add_gate_left(rx30, [0])
        gate_chain.matrix
        gate_chain.add_gate_left(rz30, [0])
        gate_chain.matrix
        gate_chain.add_gate_left(rx30, [0])
        gate_chain.matrix
        gate_chain.add_gate_left(rz30, [1])
        gate_chain.matrix
        gate_chain.add_gate_left(rx30, [1])
        gate_chain.matrix
        gate_chain.add_gate_left(rz30, [1])

        np.testing.assert_almost_equal(gate_chain.matrix,
                                       gate_chain._calculate_matrix())

        gate_chain.add_gate_left(cnot, [0, 1])
        gate_chain.add_gate_left(rx30, [0])
        gate_chain.add_gate_left(rz30, [0])
        gate_chain.add_gate_left(rx30, [0])
        gate_chain.add_gate_left(rz30, [1])
        gate_chain.add_gate_left(rx30, [1])
        gate_chain.add_gate_left(rz30, [1])

        np.testing.assert_almost_equal(gate_chain.matrix,
                                       gate_chain._calculate_matrix())
Exemplo n.º 13
0
    def test_add_2qubit_gate(self):
        # qubits 0 and 1 is connected
        hw = hardware_by_name({
            "hardware": {
                "gate_set": ["Cnot"],
                "num_qubits": 2,
                "adj_matrix": [[0, 1], [1, 0]]
            }
        })
        gate_chain = GateChain(hw)
        angle = 2 * np.pi / 30
        cnot = gate_by_name("Cnot")()
        rx30 = gate_by_name(f"Rx({angle})")()
        rz30 = gate_by_name(f"Rz({angle})")()

        gate_chain.add_gate(cnot, [0, 1])
        gate_chain.matrix
        gate_chain.add_gate(rx30, [0])
        gate_chain.matrix
        gate_chain.add_gate(rz30, [0])
        gate_chain.matrix
        gate_chain.add_gate(rx30, [0])
        gate_chain.matrix
        gate_chain.add_gate(rz30, [1])
        gate_chain.matrix
        gate_chain.add_gate(rx30, [1])
        gate_chain.matrix
        gate_chain.add_gate(rz30, [1])

        qiskit_circ = QuantumCircuit(2)
        qiskit_circ.cx(0, 1)

        qiskit_circ.rx(2 * np.pi / 30, 0)
        qiskit_circ.rz(2 * np.pi / 30, 0)
        qiskit_circ.rx(2 * np.pi / 30, 0)
        qiskit_circ.rz(2 * np.pi / 30, 1)
        qiskit_circ.rx(2 * np.pi / 30, 1)
        qiskit_circ.rz(2 * np.pi / 30, 1)

        qiskit_matrix = Operator(qiskit_circ).data
        np.testing.assert_almost_equal(gate_chain.matrix, qiskit_matrix)

        gate_chain.add_gate(cnot, [1, 0])
        gate_chain.add_gate(rx30, [0])
        gate_chain.add_gate(rz30, [1])

        qiskit_circ.cx(1, 0)
        qiskit_circ.rx(angle, 0)
        qiskit_circ.rz(angle, 1)

        qiskit_matrix = Operator(qiskit_circ).data
        np.testing.assert_almost_equal(gate_chain.matrix, qiskit_matrix)