Example #1
0
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)
Example #2
0
def test_decomposition_errors(gate_matrix):
    test_gate = MatrixGate()
    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
Example #3
0
def test_unitary_is_available():
    sim = UnitarySimulator()
    qb0 = WeakQubitRef(engine=None, idx=0)
    qb1 = WeakQubitRef(engine=None, idx=1)
    qb2 = WeakQubitRef(engine=None, idx=2)
    qb3 = WeakQubitRef(engine=None, idx=2)
    qb4 = WeakQubitRef(engine=None, idx=2)
    qb5 = WeakQubitRef(engine=None, idx=2)
    qb6 = WeakQubitRef(engine=None, idx=2)

    assert sim.is_available(Command(None, Allocate, qubits=([qb0], )))
    assert sim.is_available(Command(None, Deallocate, qubits=([qb0], )))
    assert sim.is_available(Command(None, Measure, qubits=([qb0], )))
    assert sim.is_available(Command(None, X, qubits=([qb0], )))
    assert sim.is_available(Command(None, Rx(1.2), qubits=([qb0], )))
    assert sim.is_available(Command(None, Rxx(1.2), qubits=([qb0, qb1], )))
    assert sim.is_available(Command(None, X, qubits=([qb0], ), controls=[qb1]))
    assert sim.is_available(
        Command(None, X, qubits=([qb0], ), controls=[qb1], control_state='1'))

    assert not sim.is_available(Command(None, BasicGate(), qubits=([qb0], )))
    assert not sim.is_available(
        Command(None, X, qubits=([qb0], ), controls=[qb1], control_state='0'))

    with pytest.warns(UserWarning):
        assert sim.is_available(
            Command(
                None,
                MatrixGate(np.identity(2**7)),
                qubits=([qb0, qb1, qb2, qb3, qb4, qb5, qb6], ),
            ))
Example #4
0
def test_recognize_incorrect_gates():
    saving_backend = DummyEngine(save_commands=True)
    eng = MainEngine(backend=saving_backend)
    qubit = eng.allocate_qubit()
    # Does not have matrix attribute:
    BasicGate() | qubit
    # Two qubit gate:
    two_qubit_gate = MatrixGate()
    two_qubit_gate.matrix = [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0],
                             [0, 0, 0, 1]]
    two_qubit_gate | qubit
    # Controlled single qubit gate:
    ctrl_qubit = eng.allocate_qubit()
    with Control(eng, ctrl_qubit):
        Rz(0.1) | qubit
    eng.flush(deallocate_qubits=True)
    for cmd in saving_backend.received_commands:
        assert not arb1q._recognize_arb1qubit(cmd)
Example #5
0
def test_decomposition(gate_matrix):
    for basis_state in ([1, 0], [0, 1]):
        # Create single qubit gate with gate_matrix
        test_gate = MatrixGate()
        test_gate.matrix = np.matrix(gate_matrix)

        correct_dummy_eng = DummyEngine(save_commands=True)
        correct_eng = MainEngine(backend=Simulator(),
                                 engine_list=[correct_dummy_eng])

        rule_set = DecompositionRuleSet(modules=[arb1q])
        test_dummy_eng = DummyEngine(save_commands=True)
        test_eng = MainEngine(backend=Simulator(),
                              engine_list=[
                                  AutoReplacer(rule_set),
                                  InstructionFilter(z_y_decomp_gates),
                                  test_dummy_eng
                              ])

        correct_qb = correct_eng.allocate_qubit()
        correct_eng.flush()
        test_qb = test_eng.allocate_qubit()
        test_eng.flush()

        correct_eng.backend.set_wavefunction(basis_state, correct_qb)
        test_eng.backend.set_wavefunction(basis_state, test_qb)

        test_gate | test_qb
        test_gate | correct_qb

        test_eng.flush()
        correct_eng.flush()

        assert correct_dummy_eng.received_commands[2].gate == test_gate
        assert test_dummy_eng.received_commands[2].gate != test_gate

        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 test_recognize_incorrect_gates():
    saving_backend = DummyEngine(save_commands=True)
    eng = MainEngine(backend=saving_backend)
    qubit = eng.allocate_qubit()
    ctrl_qubit = eng.allocate_qubit()
    ctrl_qureg = eng.allocate_qureg(2)
    eng.flush()
    with Control(eng, ctrl_qubit):
        # Does not have matrix attribute:
        BasicGate() | qubit
        # Two qubit gate:
        two_qubit_gate = MatrixGate()
        two_qubit_gate.matrix = np.matrix([[1, 0, 0, 0], [0, 1, 0, 0],
                                           [0, 0, 1, 0], [0, 0, 0, 1]])
        two_qubit_gate | qubit
    with Control(eng, ctrl_qureg):
        # Too many Control qubits:
        Rx(0.3) | qubit
    eng.flush(deallocate_qubits=True)
    for cmd in saving_backend.received_commands:
        assert not carb1q._recognize_carb1qubit(cmd)
Example #7
0
    def apply_gates(eng, qureg):
        MatrixGate(mat1) | qureg[0]
        MatrixGate(mat2) | qureg[1:]
        MatrixGate(mat3) | qureg

        with Control(eng, qureg[1]):
            MatrixGate(mat2) | (qureg[0], qureg[2])
            MatrixGate(mat4) | qureg[0]

        with Control(eng, qureg[1], ctrl_state='0'):
            MatrixGate(mat1) | qureg[0]
            with Control(eng, qureg[2], ctrl_state='0'):
                MatrixGate(mat1) | qureg[0]
Example #8
0
    def _calculate_probs(kraus_ops):

        probs = []
        kraus_ops_rescaled = []

        for kraus_op in kraus_ops:
            kr_op_mtx = kraus_op.matrix
            kr_op_dagg = np.conjugate(np.transpose(kr_op_mtx))
            prob = abs(max(np.diag(kr_op_dagg @ kr_op_mtx)))
            if prob > 0:
                prob_sqrt = np.sqrt(prob)
                kraus_op_rescaled = np.array(kr_op_mtx) / prob_sqrt

                kraus_ops_rescaled.append(MatrixGate(kraus_op_rescaled))
                probs.append(prob)

        # normalize probabilities
        sum_of_probs = sum(probs)
        probs_rescaled = [p / sum_of_probs for p in probs]

        return kraus_ops_rescaled, probs_rescaled
Example #9
0
def circuit(param=0, M=1):

    Instruction_Set = Ansatz(param)
    Instruction_Set_Conjugated = AnsatzConj(param)

    n_qubits = len(Instruction_Set)

    Engine = MainEngine()

    mat = np.diag([1] * 2 * n_qubits)
    mat[0, 0] = mat[0, 0] - 2
    Grover_Reflection = MatrixGate(mat)

    control = Engine.allocate_qubit()
    qubits = Engine.allocate_qureg(n_qubits)

    # Out-of-phase |+> state in control qubit
    H | control
    # R(- M * theta ) | control

    # State Preparation
    for idx, individual_instructions in enumerate(Instruction_Set):
        for gate_command in individual_instructions:
            L = len(gate_command)
            if L == 1:
                gate_command[0] | qubits[idx]
            elif L == 2:
                C(gate_command[0]) | (qubits[gate_command[1]], qubits[idx])
            else:
                raise Exception(
                    'Instruction set on qubit %s has incorrect list length.' %
                    idx)

    # Controlled - U implementation
    # [R * c-Pi * R^\dag * P * R * c-Pi * R^\dag * P]
    for _ in range(M):
        for idx, P in enumerate(Pauli):
            P | qubits[idx]

        # R^\dag
        for idx, individual_instructions in enumerate(
                Instruction_Set_Conjugated):
            for gate_command in individual_instructions:
                L = len(gate_command)
                if L == 1:
                    gate_command[0] | qubits[idx]
                elif L == 2:
                    C(gate_command[0]) | (qubits[gate_command[1]], qubits[idx])
        # c-Pi
        C(Grover_Reflection) | (control, qubits)

        # R
        for idx, individual_instructions in enumerate(Instruction_Set):
            for gate_command in individual_instructions:
                L = len(gate_command)
                if L == 1:
                    gate_command[0] | qubits[idx]
                elif L == 2:
                    C(gate_command[0]) | (qubits[gate_command[1]], qubits[idx])

        for idx, P in enumerate(Pauli):
            P | qubits[idx]

    # R^\dag
        for idx, individual_instructions in enumerate(
                Instruction_Set_Conjugated):
            for gate_command in individual_instructions:
                L = len(gate_command)
                if L == 1:
                    gate_command[0] | qubits[idx]
                elif L == 2:
                    C(gate_command[0]) | (qubits[gate_command[1]], qubits[idx])
        # c-Pi
        C(Grover_Reflection) | (control, qubits)

        # R

        for idx, individual_instructions in enumerate(Instruction_Set):
            for gate_command in individual_instructions:
                L = len(gate_command)
                if L == 1:
                    gate_command[0] | qubits[idx]
                elif L == 2:
                    C(gate_command[0]) | (qubits[gate_command[1]], qubits[idx])

    H | control

    Measure | control
    All(Measure) | qubits

    Engine.flush()

    return (int(control))
Example #10
0
def circuit_no_ancilla(param=0, M=1):

    Instruction_Set = Ansatz(param)
    Instruction_Set_Conjugated = AnsatzConj(param)

    n_qubits = len(Instruction_Set)

    Engine = MainEngine()

    mat = np.diag([1] * 2 * n_qubits)
    mat[0, 0] = mat[0, 0] - 2
    Grover_Reflection = MatrixGate(mat)

    qubits = Engine.allocate_qureg(n_qubits)

    # State Preparation
    for idx, individual_instructions in enumerate(Instruction_Set):
        for gate_command in individual_instructions:
            L = len(gate_command)
            if L == 1:
                gate_command[0] | qubits[idx]
            elif L == 2:
                C(gate_command[0]) | (qubits[gate_command[1]], qubits[idx])
            else:
                raise Exception(
                    'Instruction set on qubit %s has incorrect list length.' %
                    idx)

    # Controlled - U implementation
    # [R * c-Pi * R^\dag * P * R * c-Pi * R^\dag * P]
    for _ in range(M):
        for idx, P in enumerate(Pauli):
            P | qubits[idx]

        # R^\dag
        for idx, individual_instructions in enumerate(
                Instruction_Set_Conjugated):
            for gate_command in individual_instructions:
                L = len(gate_command)
                if L == 1:
                    gate_command[0] | qubits[idx]
                elif L == 2:
                    C(gate_command[0]) | (qubits[gate_command[1]], qubits[idx])
        # c-Pi
        Grover_Reflection | qubits

        # R
        for idx, individual_instructions in enumerate(Instruction_Set):
            for gate_command in individual_instructions:
                L = len(gate_command)
                if L == 1:
                    gate_command[0] | qubits[idx]
                elif L == 2:
                    C(gate_command[0]) | (qubits[gate_command[1]], qubits[idx])

        for idx, P in enumerate(Pauli):
            P | qubits[idx]

    # R^\dag
        for idx, individual_instructions in enumerate(
                Instruction_Set_Conjugated):
            for gate_command in individual_instructions:
                L = len(gate_command)
                if L == 1:
                    gate_command[0] | qubits[idx]
                elif L == 2:
                    C(gate_command[0]) | (qubits[gate_command[1]], qubits[idx])
        # c-Pi
        Grover_Reflection | qubits

        # R

        for idx, individual_instructions in enumerate(Instruction_Set):
            for gate_command in individual_instructions:
                L = len(gate_command)
                if L == 1:
                    gate_command[0] | qubits[idx]
                elif L == 2:
                    C(gate_command[0]) | (qubits[gate_command[1]], qubits[idx])

    # R^\dag
    for idx, individual_instructions in enumerate(Instruction_Set_Conjugated):
        for gate_command in individual_instructions:
            L = len(gate_command)
            if L == 1:
                gate_command[0] | qubits[idx]
            elif L == 2:
                C(gate_command[0]) | (qubits[gate_command[1]], qubits[idx])

    All(Measure) | qubits

    Engine.flush()

    results = []
    for q in qubits:
        results.append(int(q))

    return (results)
Example #11
0
import numpy as np
from projectq.ops import MatrixGate, X, Y, Z
from .._noiseoperator import NoiseKraus, NoiseKrausError

Id = MatrixGate(np.eye(2, dtype=complex))
I = Id


class DepolarizingChannel(NoiseKraus):

    def __init__(self, p):
        probs = []
        probs = [p/4] * 3
        probs.append(1 - 0.75 * p)
        NoiseKraus.__init__(self, kraus_ops=[X, Y, Z, Id], probs=probs)
        self._parameter = p

    @property
    def parameter(self):
        return self._parameter

    @parameter.setter
    def parameter(self, p):
        probs = []
        probs = [p/4] * 3
        probs.append(1 - 0.75 * p)
        NoiseKraus(kraus_ops=[X, Y, Z, Id])
        self._parameter = p
Example #12
0
 def __init__(self):
     MatrixGate.__init__(self)
     self.cnt = 0