def test_noise_operators(init, gate_time, rate):
    """Test PRAGMA operators applying noise with PyQuEST interface"""
    op = init[0]

    (Gate_time, Rate, q0) = ('gate_time',
                             'rate', 0)
    operation = op(qubit=q0, gate_time=Gate_time, rate=Rate)
    substitution_dict = {'gate_time': gate_time, 'rate': rate}
    operation = operation.substitute_parameters(substitution_dict)
    env = utils.createQuestEnv()()
    qureg = utils.createDensityQureg()(1, env)
    cheat.initPlusState()(qureg=qureg)
    init[2](qureg=qureg, probability=operation.probability().float(), qubit=0)
    density_matrix_ref = cheat.getDensityMatrix()(qureg)
    test_dict = {'ro': list()}

    cheat.initPlusState()(qureg)
    pyquest_call_operation(operation=operation.substitute_parameters(substitution_dict),
                           qureg=qureg,
                           classical_bit_registers=dict(),
                           classical_float_registers=dict(),
                           classical_complex_registers=test_dict,
                           output_bit_register_dict=dict(),
                           )

    density_matrix_test = cheat.getDensityMatrix()(qureg)

    npt.assert_array_almost_equal(density_matrix_ref, density_matrix_test)

    utils.destroyQureg().call_interactive(qureg, env)
    utils.destroyQuestEnv().call_interactive(env)

    operation = operation.substitute_parameters(substitution_dict)

    env = utils.createQuestEnv()()
    qureg = utils.createDensityQureg()(1, env)
    cheat.initPlusState()(qureg=qureg)
    init[2](qureg=qureg, probability=operation.probability().float(), qubit=0)
    density_matrix_ref = cheat.getDensityMatrix()(qureg)

    cheat.initPlusState()(qureg)
    pyquest_call_operation(operation=operation, qureg=qureg, classical_bit_registers=dict(),
                           classical_float_registers=dict(),
                           classical_complex_registers=test_dict,
                           output_bit_register_dict=dict(),)

    density_matrix_test = cheat.getDensityMatrix()(qureg)

    npt.assert_array_almost_equal(density_matrix_ref, density_matrix_test)

    utils.destroyQureg().call_interactive(qureg, env)
    utils.destroyQuestEnv().call_interactive(env)
def test_random_noise_operator(gate_time, depolarisation_rate, dephasing_rate):
    """Test PRAGMA operators applying random noise (stochastic unravelling) with PyQuEST interface"""
    op = ops.PragmaRandomNoise
    test_dict = {'ro': list()}

    (Gate_time, depol_Rate, dephasing_Rate) = ('gate_time',
                                               'depolarisation_rate',
                                               'dephasing_rate',
                                               )
    operation = op(qubit=0, gate_time=Gate_time,
                   depolarising_rate=depol_Rate, dephasing_rate=dephasing_Rate)

    substitution_dict = {'gate_time': gate_time,
                         'depolarisation_rate': depolarisation_rate,
                         'dephasing_rate': dephasing_rate}
    env = utils.createQuestEnv()()
    qureg = utils.createQureg()(1, env)
    state_vec_ref = cheat.getStateVector()(qureg)
    pyquest_call_operation(operation=operation.substitute_parameters(substitution_dict),
                           qureg=qureg,
                           classical_bit_registers=dict(),
                           classical_float_registers=dict(),
                           classical_complex_registers=test_dict,
                           output_bit_register_dict=dict(),
                           )
    if gate_time == 0 or (dephasing_rate == 0 and depolarisation_rate == 0):
        state_vec = cheat.getStateVector()(qureg)
        npt.assert_array_almost_equal(state_vec_ref, state_vec)

    utils.destroyQureg().call_interactive(qureg, env)
    utils.destroyQuestEnv().call_interactive(env)

    operation.substitute_parameters(substitution_dict)

    env = utils.createQuestEnv()()
    qureg = utils.createQureg()(1, env)
    state_vec_ref = cheat.getStateVector()(qureg)
    pyquest_call_operation(operation=operation.substitute_parameters(substitution_dict),
                           qureg=qureg, classical_bit_registers=dict(),
                           classical_float_registers=dict(),
                           classical_complex_registers=test_dict,
                           output_bit_register_dict=dict(),)
    if gate_time == 0 or (dephasing_rate == 0 and depolarisation_rate == 0):
        state_vec = cheat.getStateVector()(qureg)
        npt.assert_array_almost_equal(state_vec_ref, state_vec)

    utils.destroyQureg().call_interactive(qureg, env)
    utils.destroyQuestEnv().call_interactive(env)
Ejemplo n.º 3
0
def test_apply_functions(applied: Tuple[Any, List]) -> None:
    """Test all non-deprecated apply functions"""
    env = utils.createQuestEnv()()
    qubits = utils.createQureg()(5, env)
    cheat.initZeroState()(qureg=qubits)
    op = applied[0]()
    positional_args = applied[1]
    matrix = np.array([[1, 0, 0, 1], [0, 2, 0, 2], [2, 0, 2, 0], [1, 0, 0, 1]])
    last_element: str = positional_args.pop()
    if last_element == 'matrix':
        args = [qubits]
        args.extend(positional_args)
        args.append(matrix)
    elif last_element == 'pauli':
        pauli_hamil = positional_args.pop(0)
        cheat.initPauliHamil()(pauli_hamil=pauli_hamil,
                               coeffs=[0.0, 0.0, 0.0, 0.0, 0.0],
                               codes=[[0, 0], [0, 0], [0, 0], [0, 0], [0, 0]])
        args = [qubits, pauli_hamil]
        args.extend(positional_args)
    else:
        args = [qubits]
        args.extend(positional_args)

    op(*args)
    if last_element == 'matrix':
        npt.assert_array_equal(matrix, op.matrix(matrix=matrix))
Ejemplo n.º 4
0
def test_one_qubit_errors(prob, gate_def) -> None:
    """Testing one qubit errors and the mixDensityMatrix error"""
    op = gate_def[0]
    prob = prob * gate_def[1]
    env = utils.createQuestEnv()()
    dm = utils.createDensityQureg()(1, env)
    state = np.random.random((2, 1)) + 1j * np.random.random((2, 1))
    state = state / np.linalg.norm(state)
    state_dm = state @ state.conjugate().T
    cheat.setDensityAmps()(dm,
                           reals=np.real(state_dm),
                           imags=np.imag(state_dm))
    if gate_def[1] == 1 / 4:
        dm_other = utils.createDensityQureg()(1, env)
        op()(qureg=dm, probability=prob, qureg_other=dm_other)
    else:
        op()(qureg=dm, qubit=0, probability=prob)
    try:
        superop = op().superoperator_matrix(probability=prob)
        state_dm = state_dm.reshape((4, 1))
        end_matrix = (superop @ state_dm).reshape((2, 2), order='F')
        matrix = cheat.getDensityMatrix()(dm)
        npt.assert_array_almost_equal(matrix, end_matrix.T)
    except NotImplementedError:
        pass
def test_active_reset():
    """Test ActiveReset PRAGMA with PyQuEST interface"""
    definition = ops.DefinitionBit(name='ro', length=2, is_output=True)
    circuit = Circuit()
    circuit += definition
    circuit += ops.PauliX(qubit=0)

    circuit_with = circuit + ops.PragmaActiveReset(qubit=0) + ops.PragmaActiveReset(qubit=1)
    circuit_without = circuit + ops.PauliX(qubit=0)
    circuit_list = [circuit, circuit_with, circuit_without]
    for circuit in circuit_list:
        circuit += ops.MeasureQubit(qubit=0, readout='ro', readout_index=0)
        circuit += ops.MeasureQubit(qubit=1, readout='ro', readout_index=1)

    test_dict = {'ro': [False, False]}
    env = utils.createQuestEnv()()
    qureg = utils.createQureg()(2, env)
    results_list_0 = []
    results_list_1 = []
    for circuit in circuit_list:
        pyquest_call_circuit(circuit=circuit, qureg=qureg, classical_bit_registers=test_dict,
                             classical_float_registers=dict(),
                             classical_complex_registers=dict(),
                             output_bit_register_dict=dict(),)
        results_list_0.append(test_dict['ro'][0])
        results_list_1.append(test_dict['ro'][1])

    assert results_list_0 == [True, False, False]
    assert results_list_1 == [False, False, False]
Ejemplo n.º 6
0
def build_two_qubit_matrix(operation) -> np.ndarray:
    """Return full process tomography on two qubit operation with PyQuEST interface"""
    matrix = np.zeros((4, 4), dtype=complex)
    for co, state in enumerate([np.array([1, 0, 0, 0]),
                                np.array([0, 1, 0, 0]),
                                np.array([0, 0, 1, 0]),
                                np.array([0, 0, 0, 1]), ]):
        env = utils.createQuestEnv()()
        qubits = utils.createQureg()(2, env)
        cheat.initStateFromAmps()(qubits, np.real(state), np.imag(state))
        circuit = Circuit()
        circuit += operation
        
        pyquest_call_circuit(circuit=circuit,
                             qureg=qubits,
                             classical_bit_registers=dict(),
                             classical_float_registers=dict(),
                             classical_complex_registers=dict(),
                             output_bit_register_dict=dict(),)
        for i in range(0, 4):
            out = cheat.getAmp()(qureg=qubits, index=i)
            matrix[i, co] = out
        utils.destroyQureg()(qubits, env=env)
        utils.destroyQuestEnv()(env)
    return matrix
Ejemplo n.º 7
0
def test_multi_controlled_PhaseShift() -> None:
    """Test multiControlledPhaseShift"""
    env = utils.createQuestEnv()()
    qubits = utils.createQureg()(3, env)
    ops.multiControlledPhaseShift()(qureg=qubits,
                                    controls=[0, 1],
                                    theta=0.3 * np.pi)
Ejemplo n.º 8
0
def test_mix_multi_qubit_kraus_map():
    """Test Kraus operator error acting on multiple qubits"""
    env = utils.createQuestEnv()()
    dm = utils.createDensityQureg()(2, env)
    operators = [
        np.array([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]]),
    ]
    ops.mixMultiQubitKrausMap()(dm, qubits=[0, 1], operators=operators)
Ejemplo n.º 9
0
def test_mix_kraus_map():
    """Test Kraus operator error"""
    env = utils.createQuestEnv()()
    dm = utils.createDensityQureg()(1, env)
    operators = [
        np.array([[1, 0], [0, 1]]),
    ]
    ops.mixKrausMap()(dm, qubit=0, operators=operators)
Ejemplo n.º 10
0
def test_multi_controlled_PhaseFlip() -> None:
    """Test multiControlledPhaseFlip"""
    env = utils.createQuestEnv()()
    qubits = utils.createQureg()(3, env)
    ops.multiControlledPhaseFlip()(
        qureg=qubits,
        controls=[0, 1],
    )
Ejemplo n.º 11
0
def test_multiRotateZ() -> None:
    """Testing multiRotateZ"""
    env = utils.createQuestEnv()()
    qureg = utils.createQureg()(3, env=env)
    ops.multiRotateZ()(
        qureg=qureg,
        qubits=[0, 1, 2],
        angle=0.35)
Ejemplo n.º 12
0
def test_multi_controlled_multi_qubit_unitary(gate, theta) -> None:
    """Test multiControlledMultiQubitUnitary"""
    matrix_gate = gate().matrix(theta=theta)
    env = utils.createQuestEnv()()
    qubits = utils.createQureg()(4, env)
    ops.multiControlledMultiQubitUnitary()(qureg=qubits,
                                           controls=[0, 1],
                                           targets=[2, 3],
                                           matrix=matrix_gate)
def test_calc_Expec_Diagonal_Op() -> None:
    """Test calculating the expectation value of a DiagonalOp"""
    env = utils.createQuestEnv()()
    qubits = utils.createQureg()(4, env)
    a = cheat.calcExpecDiagonalOp()(
        qureg=qubits,
        operator=(4, env),
    )
    assert a == 0
Ejemplo n.º 14
0
def test_multi_controlled_unitary(gate, theta) -> None:
    """Test multiControlledUnitary"""
    matrix_gate = gate().matrix(theta=theta)
    env = utils.createQuestEnv()()
    qubits = utils.createQureg()(3, env)
    ops.multiControlledUnitary()(qureg=qubits,
                                 controls=[0, 1],
                                 qubit=2,
                                 matrix=matrix_gate)
def test_set_amps_qureg() -> None:
    """Testing set functions

    setAmps, setDensityAmps, setWeightedQureg
    """
    env = utils.createQuestEnv()()
    qureg_statevec = utils.createQureg()(2, env)
    qureg_dens = utils.createDensityQureg()(2, env)
    cheat.initZeroState()(qureg_statevec)
    cheat.initZeroState()(qureg_dens)

    cheat.setAmps()(qureg=qureg_statevec,
                    startind=0,
                    reals=[1, 2, 0, 1],
                    imags=[0, 3, 4, 3],
                    numamps=4)
    state_vec = cheat.getStateVector()(qureg=qureg_statevec)
    state_array = np.array([1 + 0j, 2 + 3j, 0 + 4j, 1 + 3j])
    assert np.all(state_vec == state_array)

    cheat.setDensityAmps()(
        qureg=qureg_dens,
        reals=[[1, 2, 1, 2], [0, 1, 0, 1], [1, 0, 1, 0], [2, 1, 2, 1]],
        imags=[[4, 3, 4, 3], [3, 2, 3, 2], [2, 3, 2, 3], [3, 4, 3, 4]],
    )
    dens_mat = cheat.getDensityMatrix()(qureg=qureg_dens)
    dens_array = np.array([[1 + 4j, 2 + 3j, 1 + 4j, 2 + 3j],
                           [3j, 1 + 2j, 3j, 1 + 2j], [1 + 2j, 3j, 1 + 2j, 3j],
                           [2 + 3j, 1 + 4j, 2 + 3j, 1 + 4j]])
    assert np.all(dens_mat == dens_array)

    # for a wavefunction qureg:
    quregout = utils.createQureg()(2, env)
    cheat.setWeightedQureg()(fac1=2.5,
                             qureg1=qureg_statevec,
                             fac2=3.5j,
                             qureg2=qureg_statevec,
                             facout=1,
                             quregout=quregout)
    state_vec_combined = cheat.getStateVector()(qureg=quregout)
    comparison_array = 2.5 * state_array + 3.5j * state_array + 1 * np.array(
        [1, 0, 0, 0])
    assert np.all(state_vec_combined == comparison_array)

    # for a density matrix qureg:
    quregout = utils.createDensityQureg()(2, env)
    cheat.setWeightedQureg()(fac1=2.5,
                             qureg1=qureg_dens,
                             fac2=3.5j,
                             qureg2=qureg_dens,
                             facout=0.5,
                             quregout=quregout)
    dens_mat_combined = cheat.getDensityMatrix()(qureg=quregout)
    comparison_array = 2.5 * dens_array + 3.5j * dens_array + 0.5 * np.array(
        [[1, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]])
    assert np.all(dens_mat_combined == comparison_array)
def test_calc_Hilbert_Schmidt_distance() -> None:
    """Test calculating the Hilbert Schmidt distance"""
    env = utils.createQuestEnv()()
    qureg1 = utils.createDensityQureg()(4, env)
    qureg2 = utils.createDensityQureg()(4, env)
    a = cheat.calcHilbertSchmidtDistance()(
        qureg1=qureg1,
        qureg2=qureg2,
    )
    assert a == 0.0
Ejemplo n.º 17
0
def test_calc_density_inner_product():
    """Test calculating the inner product for density matrices"""
    env = utils.createQuestEnv()()
    qureg1 = utils.createDensityQureg()(4, env)
    qureg2 = utils.createDensityQureg()(4, env)
    a = cheat.calcDensityInnerProduct()(
        qureg1=qureg1,
        qureg2=qureg2,
    )
    print(a)
Ejemplo n.º 18
0
def test_multi_controlled_two_qubit_unitary(gate, theta):
    """Test multiControlledTwoQubitUnitary"""
    matrix_gate = gate().matrix(theta=theta)
    env = utils.createQuestEnv()()
    qubits = utils.createQureg()(4, env)
    ops.multiControlledTwoQubitUnitary()(
        qureg=qubits,
        controls=[0, 1],
        target_qubit_1=2,
        target_qubit_2=3,
        matrix=matrix_gate)
Ejemplo n.º 19
0
def test_apply_Pauli_sum():
    """Test applyPauliSum"""
    env = utils.createQuestEnv()()
    qubits = utils.createQureg()(4, env)
    qubits_out = utils.createQureg()(4, env)
    ops.applyPauliSum()(
        qureg=qubits,
        paulis=[[0, 1, 2, 3], [3, 2, 1, 0]],
        coefficients=[0.4, 0.3],
        qureg_out=qubits_out,
    )
Ejemplo n.º 20
0
def test_mix_two_qubit_kraus_map():
    """Test Kraus operator error acting on two qubits"""
    env = utils.createQuestEnv()()
    dm = utils.createDensityQureg()(2, env)
    operators = [
        np.array([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]]),
    ]
    ops.mixTwoQubitKrausMap()(dm,
                              target_qubit_1=0,
                              target_qubit_2=1,
                              operators=operators)
def test_calc_Expec_Pauli_Prod() -> None:
    """Test calculating the expectation value of a PauliProduct"""
    env = utils.createQuestEnv()()
    qubits = utils.createQureg()(4, env)
    workspace = utils.createQureg()(4, env)
    a = cheat.calcExpecPauliProd()(
        qureg=qubits,
        qubits=[0, 1, 2, 3],
        paulis=[0, 1, 3, 2],
        workspace=workspace,
    )
    assert a == 0.0
def test_calc_Expec_Pauli_Sum() -> None:
    """Test calculating the expectation value of a PauliSum"""
    env = utils.createQuestEnv()()
    qubits = utils.createQureg()(4, env)
    workspace = utils.createQureg()(4, env)
    a = cheat.calcExpecPauliSum()(
        qureg=qubits,
        paulis=[[0, 1, 2, 3], [3, 2, 1, 0]],
        coefficients=[0.4, 0.3],
        workspace=workspace,
    )
    assert a == 0.0
Ejemplo n.º 23
0
def test_QuestEnv() -> None:
    """Testing the creation, destruction and reporting of a QuestEnv"""
    env = utils.createQuestEnv()()
    dm = utils.createDensityQureg()(1, env)
    utils.reportQuESTEnv()(env=env)
    result_type = utils.reportQuESTEnv().restype
    argument_type = utils.reportQuESTEnv().argtype

    assert result_type == 'void'
    assert argument_type == ['QuESTEnv']

    utils.destroyQuestEnv()(env=env)
Ejemplo n.º 24
0
def build_one_qubit_matrix(gate, gate_args) -> np.ndarray:
    """Build one qubit matrix for tests"""
    matrix = np.zeros((2, 2), dtype=complex)
    for co, state in enumerate([np.array([1, 0]), np.array([0, 1])]):
        env = utils.createQuestEnv()()
        qubits = utils.createQureg()(1, env)
        cheat.initStateFromAmps()(qubits, np.real(state), np.imag(state))
        gate()(qureg=qubits, qubit=0, **gate_args)
        for i in range(0, 2):
            cComplex = cheat.getAmp()(qureg=qubits, index=i)
            matrix[i, co] = cComplex.real + 1j * cComplex.imag
    return matrix
Ejemplo n.º 25
0
def test_calcPurity():
    """Testing calcPurity"""
    env = utils.createQuestEnv()()
    qureg = utils.createQureg()(2, env)
    cheat.initZeroState()(qureg)
    with npt.assert_warns(RuntimeWarning):
        purity = cheat.measurement.calcPurity()(qureg)
    assert(purity is None)
    qureg = utils.createDensityQureg()(2, env)
    cheat.initZeroState()(qureg)
    purity = cheat.measurement.calcPurity()(qureg)
    npt.assert_equal(purity, 1)
def test_calc_Expec_Pauli_Hamil() -> None:
    """Test calculating the expectation value of a PauliHamil"""
    env = utils.createQuestEnv()()
    qubits = utils.createQureg()(4, env)
    pauli_hamil = utils.createPauliHamil()(number_qubits=4,
                                           number_pauliprods=1)
    workspace = utils.createQureg()(4, env)
    a = cheat.calcExpecPauliHamil()(
        qureg=qubits,
        pauli_hamil=pauli_hamil,
        workspace=workspace,
    )
    npt.assert_almost_equal(a, 0.0)
Ejemplo n.º 27
0
def test_measure() -> None:
    """Test measuring functions: measure, measureWithStats and collapseToOutcome"""
    env = utils.createQuestEnv()()
    qureg = utils.createQureg()(3, env)
    cheat.initZeroState()(qureg=qureg)

    qubit_0 = ops.measure()(qureg=qureg, qubit=0)
    qubit_1 = ops.measureWithStats()(qureg=qureg, qubit=1, outcome_proba=0.5)
    proba_qubit_2 = ops.collapseToOutcome()(qureg=qureg, qubit=2, outcome=0)

    assert qubit_0 == 0
    assert qubit_1 == 0
    assert proba_qubit_2 == 1
Ejemplo n.º 28
0
def build_two_qubit_matrix_target(gate, gate_args, control=None) -> np.ndarray:
    """Build two qubit matrix with target for tests"""
    matrix = np.zeros((4, 4), dtype=complex)
    for co, state in enumerate([
            np.array([1, 0, 0, 0]),
            np.array([0, 1, 0, 0]),
            np.array([0, 0, 1, 0]),
            np.array([0, 0, 0, 1]),
    ]):
        env = utils.createQuestEnv()()
        if control is None:
            qubits = utils.createQureg()(2, env)
            cheat.initStateFromAmps()(qubits, np.real(state), np.imag(state))
            gate()(qureg=qubits,
                   target_qubit_1=0,
                   target_qubit_2=1,
                   **gate_args)
        elif control is True:
            qubits = utils.createQureg()(3, env)
            control_array = np.array([0, 1])
            cheat.initStateFromAmps()(qubits,
                                      np.real(np.kron(control_array, state)),
                                      np.imag(np.kron(control_array, state)))
            gate()(qureg=qubits,
                   target_qubit_1=0,
                   target_qubit_2=1,
                   control=2,
                   **gate_args)
        else:
            qubits = utils.createQureg()(3, env)
            control_array = np.array([1, 0])
            cheat.initStateFromAmps()(qubits,
                                      np.real(np.kron(control_array, state)),
                                      np.imag(np.kron(control_array, state)))
            gate()(qureg=qubits,
                   target_qubit_1=0,
                   target_qubit_2=1,
                   control=2,
                   **gate_args)
        for i in range(0, 4):
            if control is None:
                cComplex = cheat.getAmp()(qureg=qubits, index=i)
                matrix[i, co] = cComplex.real + 1j * cComplex.imag
            elif control is True:
                cComplex = cheat.getAmp()(qureg=qubits, index=i + 4)
                matrix[i, co] = cComplex.real + 1j * cComplex.imag
            else:
                cComplex = cheat.getAmp()(qureg=qubits, index=i)
                matrix[i, co] = cComplex.real + 1j * cComplex.imag
    return matrix
Ejemplo n.º 29
0
def test_two_qubit_errors(prob, gate_def) -> None:
    """Testing two qubit errors"""
    op = gate_def[0]
    prob = prob * gate_def[1]
    env = utils.createQuestEnv()()
    dm = utils.createDensityQureg()(2, env)
    state = np.random.random((4, 1)) + 1j * np.random.random((4, 1))
    state = state / np.linalg.norm(state)
    state_dm = state @ state.conjugate().T
    state_dm = state_dm.reshape((16, 1))
    cheat.initStateFromAmps()(dm,
                              reals=np.real(state_dm),
                              imags=np.imag(state_dm))
    op()(qureg=dm, qubit1=0, qubit2=1, probability=prob)