Beispiel #1
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))
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)
Beispiel #3
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)
Beispiel #4
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
def test_get_simple() -> None:
    """Testing simple get functions.

    getStateVectoratIndex/getAmp, getDensityMatrixatRowColumn/getDensityAmp,
    getAbsoluteValSquaredatIndex/getProbAmp, getRealAmp, getImagAmp
    """
    env = utils.createQuestEnv()()
    qureg = utils.createQureg()(2, env)
    cheat.initZeroState()(qureg)
    index = 1
    operator_matrix = np.array([[1, 0, 2, 0], [0, 1, 0, 2], [0, 2, 0, 1],
                                [2, 0, 1, 0]])

    with npt.assert_raises(RuntimeError):
        density_matrix = cheat.getDensityAmp()(qureg=qureg, row=1, column=1)
    state_vec = cheat.getAmp()(qureg=qureg, index=index)
    abs_val_state_vec = cheat.getProbAmp()(qureg=qureg, index=1)
    real_val_sate_vec = cheat.getRealAmp()(qureg=qureg, index=1)
    imag_val_sate_vec = cheat.getImagAmp()(qureg=qureg, index=1)
    num_amps = cheat.getNumAmps()(qureg=qureg)
    num_qubits = cheat.getNumQubits()(qureg=qureg)
    expec_val = cheat.getExpectationValue()(qureg=qureg,
                                            operator_matrix=operator_matrix)

    assert state_vec == 0
    assert abs_val_state_vec == 0
    assert real_val_sate_vec == 0
    assert imag_val_sate_vec == 0
    assert num_amps == 4
    assert num_qubits == 2
    assert expec_val == 1

    qureg = utils.createDensityQureg()(2, env)
    cheat.initZeroState()(qureg)

    with npt.assert_raises(RuntimeError):
        state_vec = cheat.getAmp()(qureg=qureg, index=index)
        abs_val_state_vec = cheat.getProbAmp()(qureg=qureg, index=1)
        real_val_sate_vec = cheat.getRealAmp()(qureg=qureg, index=1)
        imag_val_sate_vec = cheat.getImagAmp()(qureg=qureg, index=1)
    density_matrix = cheat.getDensityAmp()(qureg=qureg, row=1, column=1)
    num_amps = cheat.getNumAmps()(qureg=qureg)
    num_qubits = cheat.getNumQubits()(qureg=qureg)
    expec_val = cheat.getExpectationValue()(qureg=qureg,
                                            operator_matrix=operator_matrix)

    assert density_matrix == 0
    assert num_amps == 4
    assert num_qubits == 2
    assert expec_val == 1
def test_calc_simple() -> None:
    """Testing simple calc functions.
    
    calcPurity, calcFidelity, calcInnerProduct, calcProbofOutcome,
    calcTotalProb, calcDensityInnerProduct
    """
    env = utils.createQuestEnv()()
    qureg = utils.createQureg()(2, env)
    qureg_main = utils.createQureg()(2, env)
    cheat.initZeroState()(qureg)

    with npt.assert_raises(RuntimeError):
        purity = cheat.calcPurity()(qureg)
        density_inner_product = cheat.calcDensityInnerProduct()(
            qureg1=qureg, qureg2=qureg_main)
    fidelity = cheat.calcFidelity()(qureg=qureg_main, qureg_reference=qureg)
    inner_product = cheat.calcInnerProduct()(qureg1=qureg, qureg2=qureg_main)
    prob_of_outcome = cheat.calcProbOfOutcome()(qureg, 1, 0)
    total_prob = cheat.calcTotalProb()(qureg)

    assert fidelity == 1
    assert (inner_product.real == 1 and inner_product.imag == 0)
    assert prob_of_outcome == 1.0
    assert total_prob == 1

    qureg = utils.createDensityQureg()(2, env)
    cheat.initZeroState()(qureg)

    with npt.assert_raises(RuntimeError):
        fidelity = cheat.calcFidelity()(qureg=qureg_main,
                                        qureg_reference=qureg)
        inner_product_1 = cheat.calcInnerProduct()(qureg1=qureg,
                                                   qureg2=qureg_main)
        inner_product_2 = cheat.calcInnerProduct()(qureg1=qureg_main,
                                                   qureg2=qureg)
        inner_product_3 = cheat.calcInnerProduct()(qureg1=qureg, qureg2=qureg)
        density_inner_product_1 = cheat.calcDensityInnerProduct()(
            qureg1=qureg, qureg2=qureg_main)
        density_inner_product_2 = cheat.calcDensityInnerProduct()(
            qureg1=qureg_main, qureg2=qureg)
    density_inner_product_3 = cheat.calcDensityInnerProduct()(qureg1=qureg,
                                                              qureg2=qureg)
    purity = cheat.calcPurity()(qureg)
    prob_of_outcome = cheat.calcProbOfOutcome()(qureg, 1, 0)
    total_prob = cheat.calcTotalProb()(qureg)

    assert purity == 1
    assert prob_of_outcome == 1.0
    assert total_prob == 1
    assert density_inner_product_3 == 1
Beispiel #7
0
def test_apply_functions(applied) -> 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]])
    if positional_args[-1] == 'matrix':
        args = [qubits]
        args.extend(positional_args)
        args[-1] = matrix
    else:
        args = [qubits]
        args.extend(positional_args)

    op(*args)
    if positional_args[-1] == 'matrix':
        npt.assert_array_equal(matrix, op.matrix(matrix=matrix))
def test_get_complicated() -> None:
    """Test less simple get functions

    getDensityMatrix, getStateVector, getOccupationProbability, getRepeatedMeasurement
    """
    env = utils.createQuestEnv()()
    qureg_statevec = utils.createQureg()(2, env)
    qureg_dens = utils.createDensityQureg()(2, env)
    cheat.initZeroState()(qureg_statevec)
    cheat.initZeroState()(qureg_dens)

    dens_mat = cheat.getDensityMatrix()(qureg=qureg_dens)
    state_vec = cheat.getStateVector()(qureg=qureg_statevec)

    occupation_proba_dens = cheat.getOccupationProbability()(qureg=qureg_dens)
    occupation_proba_statevec = cheat.getOccupationProbability()(
        qureg=qureg_statevec)

    repeated_meas_dens = cheat.getRepeatedMeasurement()(
        qureg=qureg_dens,
        number_measurements=5,
        qubits_to_readout_index_dict={
            0: 0,
            1: 1
        })
    repeated_meas_statevec = cheat.getRepeatedMeasurement()(
        qureg=qureg_statevec,
        number_measurements=5,
        qubits_to_readout_index_dict={
            0: 0,
            1: 1
        })

    assert np.all(dens_mat == np.array([[1, 0, 0, 0], [0, 0, 0, 0],
                                        [0, 0, 0, 0], [0, 0, 0, 0]]))
    assert np.all(state_vec == np.array([1, 0, 0, 0]))
    assert np.all(occupation_proba_dens == np.array([1, 0, 0, 0]))
    assert np.all(occupation_proba_statevec == np.array([1, 0, 0, 0]))
    assert np.all(repeated_meas_dens == np.array([[0., 0.]] * 5))
    assert np.all(repeated_meas_statevec == np.array([[0., 0.]] * 5))
def run_example_interactive():
    """Example function

    Running the exact same Example QuEST provides in the QuEST git repository
    with the interactive python interface of PyQuEST-cffi
    """
    print('PyQuEST-cffi tutorial based on QuEST tutorial')
    print('     Basic 3 qubit circuit')

    # creating environment
    env = utils.createQuestEnv()()
    # allocating qubit register
    qureg = utils.createQureg()(3, env=env)
    cheat.initZeroState()(qureg=qureg)

    # Using the report function to print system status
    print('This is the environment:')
    reporting.reportQuESTEnv()(env=env)
    print('This is the qubit register:')
    reporting.reportQuregParams()(qureg=qureg)
    print('This we can easily do in interactive python:')
    print('Result of qureg.isDensityMatrix: ', qureg.isDensityMatrix)

    # Apply circuit

    ops.hadamard()(qureg=qureg, qubit=0)
    ops.controlledNot()(qureg=qureg, control=0, qubit=1)
    ops.rotateY()(qureg=qureg, qubit=2, theta=0.1)

    ops.multiControlledPhaseFlip()(qureg=qureg,
                                   controls=[0, 1, 2],
                                   number_controls=3)

    u = np.zeros((2, 2), dtype=complex)
    u[0, 0] = 0.5 * (1 + 1j)
    u[0, 1] = 0.5 * (1 - 1j)
    u[1, 0] = 0.5 * (1 - 1j)
    u[1, 1] = 0.5 * (1 + 1j)
    ops.unitary()(qureg=qureg, qubit=0, matrix=u)

    a = 0.5 + 0.5 * 1j
    b = 0.5 - 0.5 * 1j
    ops.compactUnitary()(qureg=qureg, qubit=1, alpha=a, beta=b)

    v = np.array([1, 0, 0])
    ops.rotateAroundAxis()(qureg=qureg, qubit=2, theta=np.pi / 2, vector=v)

    ops.controlledCompactUnitary()(qureg=qureg,
                                   control=0,
                                   qubit=1,
                                   alpha=a,
                                   beta=b)

    ops.multiControlledUnitary()(qureg=qureg,
                                 controls=[0, 1],
                                 number_controls=2,
                                 qubit=2,
                                 matrix=u)

    # cheated results

    print('Circuit output')

    print('Probability amplitude of |111> by knowing the index: ',
          cheat.getProbAmp()(qureg=qureg, index=7))
    print('Probability amplitude of |111> by referencing basis state: ',
          cheat.getProbAmp()(qureg=qureg, index=[1, 1, 1]))

    # measuring:
    measurement = ops.measure()(qureg=qureg, qubit=0)
    print('Qubit 0 was measured as: ', measurement)
Beispiel #10
0
def test_QuReg() -> None:
    """Testing the creation, cloning, destruction and reporting of a QuReg"""
    env = utils.createQuestEnv()()
    wave_qureg = utils.createQureg()(num_qubits=2, env=env)
    cheat.initZeroState()(qureg=wave_qureg)
    density_qureg = utils.createDensityQureg()(num_qubits=2, env=env)
    cheat.initZeroState()(qureg=density_qureg)
    cloned_qureg = utils.createCloneQureg()(qureg=density_qureg, env=env)
    cheat.initZeroState()(qureg=cloned_qureg)

    try:
        [wave_string, density_string, cloned_string] = ['', '', '']
        cheat.getEnvironmentString()(env=env,
                                     qureg=wave_qureg,
                                     string=wave_string)
        cheat.getEnvironmentString()(env=env,
                                     qureg=density_qureg,
                                     string=density_string)
        cheat.getEnvironmentString()(env=env,
                                     qureg=cloned_qureg,
                                     string=cloned_string)
        assert cloned_string == density_string
        cheat.getEnvironmentString()(env=env,
                                     qureg=cloned_qureg,
                                     string=cloned_string)
        assert cloned_string == wave_string
    except NotImplementedError:
        pass  # getEnvironmentString unittest not implemented

    assert wave_qureg.isDensityMatrix == False
    assert density_qureg.isDensityMatrix == True
    assert cloned_qureg.isDensityMatrix == True
    assert np.all(cheat.getDensityMatrix()(
        qureg=density_qureg) == cheat.getDensityMatrix()(qureg=cloned_qureg))
    assert not np.all(cheat.getStateVector()(
        qureg=wave_qureg) == cheat.getDensityMatrix()(qureg=cloned_qureg))

    npt.assert_raises(TypeError, utils.cloneQureg(), cloned_qureg, wave_qureg)

    to_be_cloned = utils.createDensityQureg()(num_qubits=3, env=env)
    cheat.initZeroState()(qureg=to_be_cloned)
    clone_into = utils.createDensityQureg()(num_qubits=3, env=env)
    cheat.initZeroState()(qureg=clone_into)
    utils.cloneQureg()(clone_into, to_be_cloned)
    assert clone_into.isDensityMatrix == True

    result_type_list = ['', '', '']
    argument_type_list = [[''], [''], ['']]
    for qureg in [wave_qureg, density_qureg, cloned_qureg]:
        utils.reportQuregParams()(qureg=qureg)
        utils.reportState()(qureg=qureg)
        utils.reportStateToScreen()(qureg=qureg, env=env)
        result_type_list[0] = utils.reportQuregParams().restype
        argument_type_list[0] = utils.reportQuregParams().argtype
        result_type_list[1] = utils.reportState().restype
        argument_type_list[1] = utils.reportState().argtype
        result_type_list[2] = utils.reportStateToScreen().restype
        argument_type_list[2] = utils.reportStateToScreen().argtype

    npt.assert_array_equal(result_type_list, ["void", "void", "void"])
    npt.assert_equal(argument_type_list,
                     [["Qureg"], ["Qureg"], ["Qureg", "QuESTEnv", "int"]])

    for qureg in [wave_qureg, density_qureg, cloned_qureg]:
        utils.destroyQureg()(env=env, qubits=qureg)
Beispiel #11
0
    def call_interactive(self, qureg: tqureg, reals: Union[np.ndarray,
                                                           List[float]],
                         imags: Union[np.ndarray, List[float]]) -> None:
        r"""Interactive call of PyQuest-cffi

        Args:
            qureg: the quantum register
            reals: The real parts of the statevector
            imags: The imaginary parts of the statevector

        Raises:
            RuntimeError: Size of reals and imags needs to match
            RuntimeError: Shape of reals and imags for wavefunction should be: (1, 2**qubits)
            RuntimeError: Shape of reals and imags for density matrix should be:
                (2**qubits, 2**qubits) OR (4**qubits, 1)
            RuntimeError: Shape of reals and imags for density matrix should be:
                (2**qubits, 2**qubits) OR (4**qubits, 1)
            RuntimeError: Need to set real and imaginary amplitudes for each qubit:
                2**qubits for wavefunction qureg, 4**qubits for density matrix qureg
        """
        reals = list(reals)
        imags = list(imags)
        assert len(reals) == np.max(np.shape(reals))
        assert len(imags) == np.max(np.shape(imags))
        size_amps = np.size(np.array(reals))
        if not size_amps == np.size(np.array(imags)):
            raise RuntimeError("Size of reals and imags needs to match")
        num_qubits = cheat.getNumQubits()(qureg=qureg)

        if size_amps == 2**num_qubits:
            if qureg.isDensityMatrix:
                raise RuntimeError(
                    "Shape of reals and imags for wavefunction should be: " +
                    "(1, 2**qubits)")
            pointer_reals = ffi_quest.new("{}[{}]".format(qreal, len(reals)))
            for co, c in enumerate(reals):
                pointer_reals[co] = c
            pointer_imags = ffi_quest.new("{}[{}]".format(qreal, len(imags)))
            for co, c in enumerate(imags):
                pointer_imags[co] = c
            quest.initStateFromAmps(qureg, pointer_reals, pointer_imags)
        elif size_amps == 4**num_qubits:
            if not qureg.isDensityMatrix:
                raise RuntimeError(
                    "Shape of reals and imags for density matrix should be:" +
                    "(2**qubits, 2**qubits) OR (4**qubits, 1)")
            size_amps_rows = np.size(np.array(reals), 0)
            size_amps_columns = np.size(np.array(reals), 1)
            if (not (size_amps_rows == np.size(np.array(imags), 0))
                    or not (size_amps_columns == np.size(np.array(imags), 1))):
                raise RuntimeError("Size of reals and imags needs to match")
            cheat.initZeroState()(qureg=qureg)
            if (size_amps_rows == size_amps_columns == 2**num_qubits):
                cheat.setDensityAmps()(qureg=qureg, reals=reals, imags=imags)
            elif size_amps_rows == 4**num_qubits:
                reals = np.array(reals).reshape((2**num_qubits, 2**num_qubits))
                imags = np.array(imags).reshape((2**num_qubits, 2**num_qubits))
                cheat.setDensityAmps()(qureg=qureg, reals=reals, imags=imags)
            else:
                raise RuntimeError(
                    "Shape of reals and imags should be (2**qubits, 2**qubits) OR "
                    + "(4**qubits, 1)")
        else:
            raise RuntimeError(
                "Need to set real and imaginary amplitudes for each qubit: " +
                "2**qubits for wavefunction, 4**qubits for density matrix")