def reset_error(prob0, prob1=0): r""" Return a single qubit reset quantum error channel. The error channel returned is given by the map .. math:: E(ρ) = (1 - p_0 - p_1) ρ + \text{Tr}[ρ] \left( p_0 |0 \rangle\langle 0| + p_1 |1 \rangle\langle 1| \right) where the probability of no reset is given by :math:`1 - p_0 - p_1`. Args: prob0 (double): reset probability to :math:`|0\rangle`. prob1 (double): reset probability to :math:`|1\rangle`. Returns: QuantumError: the quantum error object. Raises: NoiseError: If noise parameters are invalid. """ if prob0 < 0 or prob1 < 0 or prob0 > 1 or prob1 > 1 or (prob0 + prob1) > 1: raise NoiseError("Invalid reset probabilities.") noise_ops = [([(IGate(), [0])], 1 - prob0 - prob1), ([(Reset(), [0])], prob0), ([(Reset(), [0]), (XGate(), [0])], prob1)] return QuantumError(noise_ops)
def definition(self) -> List: """Return definition in terms of other basic gates. If the gate has open controls, as determined from `self.ctrl_state`, the returned definition is conjugated with X without changing the internal `_definition`. """ if self._open_ctrl: closed_gate = self.copy() closed_gate.ctrl_state = None # pylint: disable=cyclic-import from qiskit.circuit.library.standard_gates import XGate bit_ctrl_state = bin(self.ctrl_state)[2:].zfill( self.num_ctrl_qubits) qreg = QuantumRegister(self.num_qubits, 'q') definition = [(closed_gate, qreg, [])] open_rules = [] for qind, val in enumerate(bit_ctrl_state[::-1]): if val == '0': open_rules.append([XGate(), [qreg[qind]], []]) if open_rules: return open_rules + definition + open_rules else: return self._definition else: return super().definition
def to_instruction(self): """Convert to Pauli circuit instruction.""" from math import pi pauli, phase = self._to_label(self.z, self.x, self._phase[0], full_group=False, return_phase=True) if len(pauli) == 1: gate = { "I": IGate(), "X": XGate(), "Y": YGate(), "Z": ZGate() }[pauli] else: gate = PauliGate(pauli) if not phase: return gate # Add global phase circuit = QuantumCircuit(self.num_qubits, name=str(self)) circuit.global_phase = -phase * pi / 2 circuit.append(gate, range(self.num_qubits)) return circuit.to_instruction()
def diffuser(list_values: list, circuit_type: str): n = len(list_values[0]) assert n >= 2, 'Length of input should be greater or equal to 2.' if (circuit_type == 'noancilla' or n == 2): q1 = QuantumRegister(n, "q") a1 = QuantumCircuit(q1) a1.h(q1[[*range(n)]]) a1.x(q1[[*range(n)]]) a1.h(q1[n - 1]) gate = XGate().control(n - 1) a1.append(gate, q1) elif circuit_type == 'ancilla': r = 0 pn = r + 2 jn = r kn = r + 1 q1 = QuantumRegister(n * 2, "q") a1 = QuantumCircuit(q1) ######### Apply Hadamard and X gates. a1.h(q1[[*range(n)]]) a1.x(q1[[*range(n)]]) a1.h(q1[n - 1]) # Apply Hadamrd gate on the left of the target qubit n. ######### a1.ccx(q1[r], q1[r + 1], q1[r + n]) for i in range(n - 3): a1.ccx(q1[pn], q1[n + jn], q1[n + kn]) if i < n - 4: pn += 1 jn += 1 kn += 1 ##a1.barrier() a1.cx(q1[(n * 2) - 3], q1[(n - 1)]) ##a1.barrier() for i in range(n - 3): a1.ccx(q1[pn], q1[n + jn], q1[n + kn]) if i < n - 4: pn += -1 jn += -1 kn += -1 a1.ccx(q1[r], q1[r + 1], q1[r + n]) ######### Apply Hadamard and X gates. a1.h(q1[n - 1]) # Apply Hadamrd gate on the right of the target qubit n. a1.x(q1[[*range(n)]]) a1.h(q1[[*range(n)]]) ######### return a1
def setUp(self): super().setUp() self.ops = { 'X': XGate(), 'Y': YGate(), 'Z': ZGate(), 'H': HGate(), 'S': SGate() }
def test_grover_oracle(self): """grover_oracle.decomposition""" oracle = compile_classical_function(examples.grover_oracle) quantum_circuit = QuantumCircuit(5) quantum_circuit.append(oracle, [2, 1, 0, 3, 4]) expected = QuantumCircuit(5) expected.append(XGate().control(4, ctrl_state="1010"), [2, 1, 0, 3, 4]) self.assertEqual(quantum_circuit.decompose(), expected)
def test_grover_oracle(self): """Synthesis of grover_oracle example""" oracle = compile_classical_function(examples.grover_oracle) quantum_circuit = oracle.synth() expected = QuantumCircuit(5) expected.append(XGate().control(4, ctrl_state="1010"), [0, 1, 2, 3, 4]) self.assertEqual(quantum_circuit.name, "grover_oracle") self.assertEqual(quantum_circuit, expected)
def _echo_rzx_dag(theta): """Return the following circuit .. parsed-literal:: ┌───────────────┐┌───┐┌────────────────┐┌───┐ q_0: ┤0 ├┤ X ├┤0 ├┤ X ├ │ Rzx(theta/2) │└───┘│ Rzx(-theta/2) │└───┘ q_1: ┤1 ├─────┤1 ├───── └───────────────┘ └────────────────┘ """ rzx_dag = DAGCircuit() qr = QuantumRegister(2) rzx_dag.add_qreg(qr) rzx_dag.apply_operation_back(RZXGate(theta / 2), [qr[0], qr[1]], []) rzx_dag.apply_operation_back(XGate(), [qr[0]], []) rzx_dag.apply_operation_back(RZXGate(-theta / 2), [qr[0], qr[1]], []) rzx_dag.apply_operation_back(XGate(), [qr[0]], []) return rzx_dag
def from_label(cls, label): """Return a tensor product of single-qubit operators. Args: label (string): single-qubit operator string. Returns: Operator: The N-qubit operator. Raises: QiskitError: if the label contains invalid characters, or the length of the label is larger than an explicitly specified num_qubits. Additional Information: The labels correspond to the single-qubit matrices: 'I': [[1, 0], [0, 1]] 'X': [[0, 1], [1, 0]] 'Y': [[0, -1j], [1j, 0]] 'Z': [[1, 0], [0, -1]] 'H': [[1, 1], [1, -1]] / sqrt(2) 'S': [[1, 0], [0 , 1j]] 'T': [[1, 0], [0, (1+1j) / sqrt(2)]] '0': [[1, 0], [0, 0]] '1': [[0, 0], [0, 1]] '+': [[0.5, 0.5], [0.5 , 0.5]] '-': [[0.5, -0.5], [-0.5 , 0.5]] 'r': [[0.5, -0.5j], [0.5j , 0.5]] 'l': [[0.5, 0.5j], [-0.5j , 0.5]] """ # Check label is valid label_mats = { 'I': IGate().to_matrix(), 'X': XGate().to_matrix(), 'Y': YGate().to_matrix(), 'Z': ZGate().to_matrix(), 'H': HGate().to_matrix(), 'S': SGate().to_matrix(), 'T': TGate().to_matrix(), '0': np.array([[1, 0], [0, 0]], dtype=complex), '1': np.array([[0, 0], [0, 1]], dtype=complex), '+': np.array([[0.5, 0.5], [0.5, 0.5]], dtype=complex), '-': np.array([[0.5, -0.5], [-0.5, 0.5]], dtype=complex), 'r': np.array([[0.5, -0.5j], [0.5j, 0.5]], dtype=complex), 'l': np.array([[0.5, 0.5j], [-0.5j, 0.5]], dtype=complex), } if re.match(r'^[IXYZHST01rl\-+]+$', label) is None: raise QiskitError('Label contains invalid characters.') # Initialize an identity matrix and apply each gate num_qubits = len(label) op = Operator(np.eye(2 ** num_qubits, dtype=complex)) for qubit, char in enumerate(reversed(label)): if char != 'I': op = op.compose(label_mats[char], qargs=[qubit]) return op
def from_label(label): """Return a tensor product of single-qubit Clifford gates. Args: label (string): single-qubit operator string. Returns: Clifford: The N-qubit Clifford operator. Raises: QiskitError: if the label contains invalid characters. Additional Information: The labels correspond to the single-qubit Cliffords are * - Label - Stabilizer - Destabilizer * - ``"I"`` - +Z - +X * - ``"X"`` - -Z - +X * - ``"Y"`` - -Z - -X * - ``"Z"`` - +Z - -X * - ``"H"`` - +X - +Z * - ``"S"`` - +Z - +Y """ # Check label is valid label_gates = { 'I': IGate(), 'X': XGate(), 'Y': YGate(), 'Z': ZGate(), 'H': HGate(), 'S': SGate() } if re.match(r'^[IXYZHS\-+]+$', label) is None: raise QiskitError('Label contains invalid characters.') # Initialize an identity matrix and apply each gate num_qubits = len(label) op = Clifford(np.eye(2 * num_qubits, dtype=np.bool)) for qubit, char in enumerate(reversed(label)): _append_circuit(op, label_gates[char], qargs=[qubit]) return op
def qor(n=2): q = QuantumRegister(n) a = QuantumRegister(1) qc = QuantumCircuit(q, a, name="Or(%i)" % n) qc.x(q) qc.append(XGate().control(n), q[:] + [a]) qc.x(q) qc.x(a) return qc
def _define(self): definition = [] qr = QuantumRegister(self.num_ctrl_qubits + 1) ctrl_qr = qr[:self.num_ctrl_qubits] target_qubit = qr[self.num_ctrl_qubits] if self.qubit_values: for qubit_index, qubit_value in enumerate(self.qubit_values): if not qubit_value: definition.append((XGate(), [ctrl_qr[qubit_index]], [])) definition.append((MCXGate(self.num_ctrl_qubits), list(ctrl_qr) + [target_qubit], [])) if self.qubit_values: for qubit_index, qubit_value in enumerate(self.qubit_values): if not qubit_value: definition.append((XGate(), [ctrl_qr[qubit_index]], [])) self.definition = definition
def to_instruction(self): """Convert to Pauli circuit instruction.""" from qiskit.circuit import QuantumCircuit, QuantumRegister from qiskit.circuit.library.standard_gates import IGate, XGate, YGate, ZGate gates = {'I': IGate(), 'X': XGate(), 'Y': YGate(), 'Z': ZGate()} label = self.to_label() num_qubits = self.num_qubits qreg = QuantumRegister(num_qubits) circuit = QuantumCircuit(qreg, name='Pauli:{}'.format(label)) for i, pauli in enumerate(reversed(label)): circuit.append(gates[pauli], [qreg[i]]) return circuit.to_instruction()
def test_pauli_error_1q_gate_from_string(self): """Test single-qubit pauli error as gate qobj from string label""" paulis = ['I', 'X', 'Y', 'Z'] probs = [0.4, 0.3, 0.2, 0.1] actual = pauli_error(zip(paulis, probs)) expected = QuantumError([(IGate(), 0.4), (XGate(), 0.3), (YGate(), 0.2), (ZGate(), 0.1)]) for i in range(actual.size): circ, prob = actual.error_term(i) expected_circ, expected_prob = expected.error_term(i) self.assertEqual(circ, expected_circ, msg=f"Incorrect {i}-th circuit") self.assertAlmostEqual(prob, expected_prob, msg=f"Incorrect {i}-th probability")
def test_cx_1_0(self): """CX(1, 0)""" tweedledum_circuit = {'num_qubits': 2, 'gates': [{'gate': 'X', 'qubits': [0], 'control_qubits': [1], 'control_state': '1'}]} circuit = tweedledum2qiskit(tweedledum_circuit) expected = QuantumCircuit(2) expected.append(XGate().control(1, ctrl_state='1'), [1, 0]) self.assertEqual(expected, circuit)
def test_thermal_relaxation_error_t1_equal_t2_1state(self): """Test qobj instructions return for t1=t2""" actual = thermal_relaxation_error(1, 1, 1, 1) expected = QuantumError([ (IGate(), np.exp(-1)), ([(Reset(), [0]), (XGate(), [0])], 1 - np.exp(-1)), ]) for i in range(actual.size): circ, prob = actual.error_term(i) expected_circ, expected_prob = expected.error_term(i) self.assertEqual(circ, expected_circ, msg=f"Incorrect {i}-th circuit") self.assertAlmostEqual(prob, expected_prob, msg=f"Incorrect {i}-th probability")
def test_cx_qreg(self): """CX(0, 1) with qregs parameter""" qr = QuantumRegister(2, 'qr') tweedledum_circuit = {'num_qubits': 2, 'gates': [{'gate': 'X', 'qubits': [0], 'control_qubits': [1], 'control_state': '1'}]} circuit = tweedledum2qiskit(tweedledum_circuit, qregs=[qr]) expected = QuantumCircuit(qr) expected.append(XGate().control(1, ctrl_state='1'), [qr[1], qr[0]]) self.assertEqual(expected, circuit)
def judge(new_qc, gate, bitstrings): target_qubit = gate[1][-1] """ gate[0] : gate class gate[1] : qregs gate[2] : cregs """ # Toffoli gates if gate[0].name in ['ccx', 'rccx']: if '11' in bitstrings: if len(bitstrings) == 1: new_qc.append(XGate(label=None), [target_qubit], gate[2]) elif '10' not in bitstrings: new_qc.append(XGate(label=None).control(1), [gate[1][1], target_qubit], gate[2]) elif '01' not in bitstrings: new_qc.append(XGate(label=None).control(1), [gate[1][0], target_qubit], gate[2]) else: #11と00の時だけようにもう一つ作る?(Qubit connectionを一つ減らせる) new_qc.append(gate[0],gate[1],gate[2]) else: pass # Delete CCX # Two-qubit gates else: if '1' in bitstrings: if '0' not in bitstrings: new_qc.append(gate[0].base_gate, [target_qubit], gate[2]) else: new_qc.append(gate[0],gate[1],gate[2]) else: pass # Delete CU return new_qc
def test_cx_1_0(self): """CX(1, 0)""" tweedledum_circuit = Circuit() qubits = list() qubits.append(tweedledum_circuit.create_qubit()) qubits.append(tweedledum_circuit.create_qubit()) tweedledum_circuit.apply_operator(X(), [qubits[1], qubits[0]]) circuit = tweedledum2qiskit(tweedledum_circuit) expected = QuantumCircuit(2) expected.append(XGate().control(1, ctrl_state="1"), [1, 0]) self.assertEqual(expected, circuit)
def test_cx_0_1(self): """CX(0, 1)""" tweedledum_circuit = Circuit() qubits = list() qubits.append(tweedledum_circuit.create_qubit()) qubits.append(tweedledum_circuit.create_qubit()) tweedledum_circuit.apply_operator(X(), [qubits[0], qubits[1]]) circuit = tweedledum2qiskit(tweedledum_circuit) expected = QuantumCircuit(2) expected.append(XGate().control(1, ctrl_state='1'), [0, 1]) self.assertEqual(circuit, expected)
def _reverse_echo_rzx_dag(theta): """Return the following circuit .. parsed-literal:: ┌───┐┌───────────────┐ ┌────────────────┐┌───┐ q_0: ┤ H ├┤1 ├─────┤1 ├┤ H ├───── ├───┤│ Rzx(theta/2) │┌───┐│ Rzx(-theta/2) │├───┤┌───┐ q_1: ┤ H ├┤0 ├┤ X ├┤0 ├┤ X ├┤ H ├ └───┘└───────────────┘└───┘└────────────────┘└───┘└───┘ """ reverse_rzx_dag = DAGCircuit() qr = QuantumRegister(2) reverse_rzx_dag.add_qreg(qr) reverse_rzx_dag.apply_operation_back(HGate(), [qr[0]], []) reverse_rzx_dag.apply_operation_back(HGate(), [qr[1]], []) reverse_rzx_dag.apply_operation_back(RZXGate(theta / 2), [qr[1], qr[0]], []) reverse_rzx_dag.apply_operation_back(XGate(), [qr[1]], []) reverse_rzx_dag.apply_operation_back(RZXGate(-theta / 2), [qr[1], qr[0]], []) reverse_rzx_dag.apply_operation_back(XGate(), [qr[1]], []) reverse_rzx_dag.apply_operation_back(HGate(), [qr[0]], []) reverse_rzx_dag.apply_operation_back(HGate(), [qr[1]], []) return reverse_rzx_dag
def build_encode_circuit(num, qubits, register_size): """ Create the registery conversion circuit. Assume the last qubits are the register. qubits [int]: Total number of qubits in the global circuit register_size [int]: Total number of qubits allocated for the register. num [int]: target encoding """ # generate the X-gate configuration CGates, XGates = encode_X(num, qubits, register_size) # create a quantum circuit acting on the registers conv_register = MCMT(XGate(), len(CGates), len(XGates)) XRange = [*CGates, *XGates] return conv_register, XRange
def test_cx_qreg(self): """CX(0, 1) with qregs parameter""" tweedledum_circuit = Circuit() qubits = list() qubits.append(tweedledum_circuit.create_qubit()) qubits.append(tweedledum_circuit.create_qubit()) tweedledum_circuit.apply_operator(X(), [qubits[1], qubits[0]]) qr = QuantumRegister(2, "qr") circuit = tweedledum2qiskit(tweedledum_circuit, qregs=[qr]) expected = QuantumCircuit(qr) expected.append(XGate().control(1, ctrl_state="1"), [qr[1], qr[0]]) self.assertEqual(expected, circuit)
def __init__(self): super().__init__( None, name="FakeSimpleV2", description="A fake simple BackendV2 example", online_date=datetime.datetime.utcnow(), backend_version="0.0.1", ) self._lam = Parameter("lambda") self._target = Target(num_qubits=20) self._target.add_instruction(SXGate()) self._target.add_instruction(XGate()) self._target.add_instruction(RZGate(self._lam)) self._target.add_instruction(CXGate()) self._target.add_instruction(Measure()) self._runner = QasmSimulatorPy()
def test_depolarizing_error_1q_gate(self): """Test 1-qubit depolarizing error as gate qobj""" p_depol = 0.3 actual = depolarizing_error(p_depol, 1) expected = QuantumError([ (IGate(), 1 - p_depol*3/4), (XGate(), p_depol/4), (YGate(), p_depol/4), (ZGate(), p_depol/4) ]) for i in range(actual.size): circ, prob = actual.error_term(i) expected_circ, expected_prob = expected.error_term(i) self.assertEqual(circ, expected_circ, msg=f"Incorrect {i}-th circuit") self.assertAlmostEqual(prob, expected_prob, msg=f"Incorrect {i}-th probability")
def test_grover_oracle_arg_regs(self): """Synthesis of grover_oracle example with arg_regs""" oracle = compile_classical_function(examples.grover_oracle) quantum_circuit = oracle.synth(registerless=False) qr_a = QuantumRegister(1, 'a') qr_b = QuantumRegister(1, 'b') qr_c = QuantumRegister(1, 'c') qr_d = QuantumRegister(1, 'd') qr_return = QuantumRegister(1, 'return') expected = QuantumCircuit(qr_d, qr_c, qr_b, qr_a, qr_return) expected.append(XGate().control(4, ctrl_state='0101'), [qr_d[0], qr_c[0], qr_b[0], qr_a[0], qr_return[0]]) self.assertEqual(quantum_circuit.name, 'grover_oracle') self.assertEqual(quantum_circuit, expected)
def test_from_dict(self): noise_ops_1q = [((IGate(), [0]), 0.9), ((XGate(), [0]), 0.1)] noise_ops_2q = [((PauliGate('II'), [0, 1]), 0.9), ((PauliGate('IX'), [0, 1]), 0.045), ((PauliGate('XI'), [0, 1]), 0.045), ((PauliGate('XX'), [0, 1]), 0.01)] noise_model = NoiseModel() with self.assertWarns(DeprecationWarning): noise_model.add_quantum_error(QuantumError(noise_ops_1q, 1), 'h', [0]) noise_model.add_quantum_error(QuantumError(noise_ops_1q, 1), 'h', [1]) noise_model.add_quantum_error(QuantumError(noise_ops_2q, 2), 'cx', [0, 1]) noise_model.add_quantum_error(QuantumError(noise_ops_2q, 2), 'cx', [1, 0]) deserialized = NoiseModel.from_dict(noise_model.to_dict()) self.assertEqual(noise_model, deserialized)
def test_thermal_relaxation_error_gate(self): """Test qobj instructions return for t2 < t1""" t1, t2, time, p1 = (2, 1, 1, 0.3) actual = thermal_relaxation_error(t1, t2, time, p1) p_z = 0.5 * np.exp(-1 / t1) * (1 - np.exp(-(1 / t2 - 1 / t1) * time)) p_reset0 = (1 - p1) * (1 - np.exp(-1 / t1)) p_reset1 = p1 * (1 - np.exp(-1 / t1)) expected = QuantumError([ (IGate(), 1 - p_z - p_reset0 - p_reset1), (ZGate(), p_z), (Reset(), p_reset0), ([(Reset(), [0]), (XGate(), [0])], p_reset1), ]) for i in range(actual.size): circ, prob = actual.error_term(i) expected_circ, expected_prob = expected.error_term(i) self.assertEqual(circ, expected_circ, msg=f"Incorrect {i}-th circuit") self.assertAlmostEqual(prob, expected_prob, msg=f"Incorrect {i}-th probability")
def convert_to_target(conf_dict: dict, props_dict: dict = None, defs_dict: dict = None) -> Target: """Uses configuration, properties and pulse defaults dicts to construct and return Target class. """ name_mapping = { "id": IGate(), "sx": SXGate(), "x": XGate(), "cx": CXGate(), "rz": RZGate(Parameter("λ")), "reset": Reset(), } custom_gates = {} qubit_props = None if props_dict: qubit_props = qubit_props_from_props(props_dict) target = Target(qubit_properties=qubit_props) # Parse from properties if it exsits if props_dict is not None: # Parse instructions gates = {} for gate in props_dict["gates"]: name = gate["gate"] if name in name_mapping: if name not in gates: gates[name] = {} elif name not in custom_gates: custom_gate = Gate(name, len(gate["qubits"]), []) custom_gates[name] = custom_gate gates[name] = {} qubits = tuple(gate["qubits"]) gate_props = {} for param in gate["parameters"]: if param["name"] == "gate_error": gate_props["error"] = param["value"] if param["name"] == "gate_length": gate_props["duration"] = apply_prefix( param["value"], param["unit"]) gates[name][qubits] = InstructionProperties(**gate_props) for gate, props in gates.items(): if gate in name_mapping: inst = name_mapping.get(gate) else: inst = custom_gates[gate] target.add_instruction(inst, props) # Create measurement instructions: measure_props = {} count = 0 for qubit in props_dict["qubits"]: qubit_prop = {} for prop in qubit: if prop["name"] == "readout_length": qubit_prop["duration"] = apply_prefix( prop["value"], prop["unit"]) if prop["name"] == "readout_error": qubit_prop["error"] = prop["value"] measure_props[(count, )] = InstructionProperties(**qubit_prop) count += 1 target.add_instruction(Measure(), measure_props) # Parse from configuration because properties doesn't exist else: for gate in conf_dict["gates"]: name = gate["name"] gate_props = {tuple(x): None for x in gate["coupling_map"]} if name in name_mapping: target.add_instruction(name_mapping[name], gate_props) else: custom_gate = Gate(name, len(gate["coupling_map"][0]), []) target.add_instruction(custom_gate, gate_props) measure_props = {(n, ): None for n in range(conf_dict["n_qubits"])} target.add_instruction(Measure(), measure_props) # parse global configuration properties dt = conf_dict.get("dt") if dt: target.dt = dt * 1e-9 if "timing_constraints" in conf_dict: target.granularity = conf_dict["timing_constraints"].get("granularity") target.min_length = conf_dict["timing_constraints"].get("min_length") target.pulse_alignment = conf_dict["timing_constraints"].get( "pulse_alignment") target.aquire_alignment = conf_dict["timing_constraints"].get( "acquire_alignment") # If pulse defaults exists use that as the source of truth if defs_dict is not None: # TODO remove the usage of PulseDefaults as it will be deprecated in the future pulse_defs = PulseDefaults.from_dict(defs_dict) inst_map = pulse_defs.instruction_schedule_map for inst in inst_map.instructions: for qarg in inst_map.qubits_with_instruction(inst): sched = inst_map.get(inst, qarg) if inst in target: try: qarg = tuple(qarg) except TypeError: qarg = (qarg, ) if inst == "measure": for qubit in qarg: target[inst][(qubit, )].calibration = sched else: target[inst][qarg].calibration = sched target.add_instruction(Delay(Parameter("t")), {(bit, ): None for bit in range(target.num_qubits)}) return target
def oracle(list_values: list, circuit_type: str): n = len(list_values[0]) # Number of elements in one string. assert n >= 2, 'Length of input should be greater or equal to 2.' assert len(set(map(len, list_values)) ) == 1, 'The values on your list should have the same length.' if (circuit_type == 'noancilla' or n == 2): q1 = QuantumRegister(n + 1, "q") a1 = QuantumCircuit(q1) ##a1.barrier() for element in list_values: ############ If an element in string equal 0 then apply X Gate on the left of the control dot. for i in range(n): if element[::-1][i] == '0': a1.x(q1[i]) ############ # Apply n-1 qubits control Toffoli gate. gate = XGate().control(n) a1.append(gate, q1) ############ If an element in string equal 0 then apply X Gate on the right of the control dot. for i in range(n): if element[::-1][i] == '0': a1.x(q1[i]) ############ ##a1.barrier() elif circuit_type == 'ancilla': r = 0 pn = r + 2 jn = r kn = r + 1 q1 = QuantumRegister(n * 2, "q") a1 = QuantumCircuit(q1) ##a1.barrier() for element in list_values: ############ for i in range(n): if element[::-1][i] == '0': a1.x(q1[i]) ############ # Apply n-1 qubits control Toffoli gate using 2-qubits control Toffoli gates. a1.ccx(q1[r], q1[r + 1], q1[r + n]) for i in range(n - 2): a1.ccx(q1[pn], q1[n + jn], q1[n + kn]) if i < n - 3: pn += 1 jn += 1 kn += 1 a1.cx(q1[(n * 2) - 2], q1[(n * 2) - 1]) for i in range(n - 2): a1.ccx(q1[pn], q1[n + jn], q1[n + kn]) if i < n - 3: pn += -1 jn += -1 kn += -1 a1.ccx(q1[r], q1[r + 1], q1[r + n]) ############ for i in range(n): if element[::-1][i] == '0': a1.x(q1[i]) ############ ##a1.barrier() return a1