Beispiel #1
0
def test_wrong_final_state():
    qb0 = WeakQubitRef(engine=None, idx=0)
    qb1 = WeakQubitRef(engine=None, idx=1)
    cmd = Command(None, StatePreparation([0, 1j]), qubits=([qb0, qb1], ))
    with pytest.raises(ValueError):
        stateprep2cnot._decompose_state_preparation(cmd)
    cmd2 = Command(None, StatePreparation([0, 0.999j]), qubits=([qb0], ))
    with pytest.raises(ValueError):
        stateprep2cnot._decompose_state_preparation(cmd2)
Beispiel #2
0
def test_state_preparation(n_qubits, zeros):
    engine_list = restrictedgateset.get_engine_list(one_qubit_gates=(Ry, Rz,
                                                                     Ph))
    eng = projectq.MainEngine(engine_list=engine_list)
    qureg = eng.allocate_qureg(n_qubits)
    eng.flush()

    f_state = [
        0.2 + 0.1 * x * cmath.exp(0.1j + 0.2j * x) for x in range(2**n_qubits)
    ]
    if zeros:
        for i in range(2**(n_qubits - 1)):
            f_state[i] = 0
    norm = 0
    for amplitude in f_state:
        norm += abs(amplitude)**2
    f_state = [x / math.sqrt(norm) for x in f_state]

    StatePreparation(f_state) | qureg
    eng.flush()

    wavefunction = deepcopy(eng.backend.cheat()[1])
    # Test that simulator hasn't reordered wavefunction
    mapping = eng.backend.cheat()[0]
    for key in mapping:
        assert mapping[key] == key
    All(Measure) | qureg
    eng.flush()
    assert np.allclose(wavefunction, f_state, rtol=1e-10, atol=1e-10)
Beispiel #3
0
def circuit_generator(eng, target_state, mapper):
    """
    circuit_generator makes use of the above functions and reutrn
    a projectq circuit in string form

    Args:
        eng:
        target_state: The final state of the algorithm. 
                      It is a list or array with 2^n complex numbers
        mapper: A string representing the connected qubits in the device.
                E.g. "5\n0,1\n1,2\n1,3\n2,3\n2,4\n3,4"
    Returns:
        The quantum circuit prepare the targets_state that can be
        implemented directly on the device restricted by mapper
    """
    n, directed_mapper = read_mapper(mapper)
    connections = set([(j, i) for i, j in directed_mapper] + directed_mapper)

    LocalOptimizer.receive = my_receive
    LocalOptimizer.add_swap = add_swap
    LocalOptimizer.graph = Graph(connections)
    LocalOptimizer.connections = connections

    n = int(np.log2(len(target_state)))
    LocalOptimizer.qureg = qureg

    eng.flush()
    with Capturing() as output:
        StatePreparation(target_state) | qureg
        eng.flush()
        # mappting, wave_func = deepcopy(eng.backend.cheat())
    # print(sum(wave_func.conj() * target_state))
    circuit = "; ".join(output)
    return circuit.replace("Qureg", "qubit")
def test_X_no_eigenvectors():
    rule_set = DecompositionRuleSet(
        modules=[pe, dqft, stateprep2cnot, ucr2cnot])
    eng = MainEngine(
        backend=Simulator(),
        engine_list=[
            AutoReplacer(rule_set),
        ],
    )
    N = 100
    results = np.array([])
    results_plus = np.array([])
    results_minus = np.array([])
    for i in range(N):
        autovector = eng.allocate_qureg(1)
        amplitude0 = (np.sqrt(2) + np.sqrt(6)) / 4.0
        amplitude1 = (np.sqrt(2) - np.sqrt(6)) / 4.0
        StatePreparation([amplitude0, amplitude1]) | autovector
        unit = X
        ancillas = eng.allocate_qureg(1)
        QPE(unit) | (ancillas, autovector)
        All(Measure) | ancillas
        fasebinlist = [int(q) for q in ancillas]
        fasebin = ''.join(str(j) for j in fasebinlist)
        faseint = int(fasebin, 2)
        phase = faseint / (2.0**(len(ancillas)))
        results = np.append(results, phase)
        Tensor(H) | autovector
        if np.allclose(phase, 0.0, rtol=1e-1):
            results_plus = np.append(results_plus, phase)
            All(Measure) | autovector
            autovector_result = int(autovector)
            assert autovector_result == 0
        elif np.allclose(phase, 0.5, rtol=1e-1):
            results_minus = np.append(results_minus, phase)
            All(Measure) | autovector
            autovector_result = int(autovector)
            assert autovector_result == 1
        eng.flush()

    total = len(results_plus) + len(results_minus)
    plus_probability = len(results_plus) / N
    assert total == pytest.approx(N, abs=5)
    assert plus_probability == pytest.approx(
        1.0 / 4.0, abs=1e-1
    ), "Statistics on |+> probability are not correct (%f vs. %f)" % (
        plus_probability,
        1.0 / 4.0,
    )
Beispiel #5
0
def W(eng, individual_terms, initial_wavefunction, ancilla_qubits,
      system_qubits):
    """
    Applies the W operator as defined in arXiv:1711.11025.

    Args:
        eng(MainEngine): compiler engine
        individual_terms(list<QubitOperator>): list of individual unitary
                                               QubitOperators. It applies
                                               individual_terms[0] if ancilla
                                               qubits are in state |0> where
                                               ancilla_qubits[0] is the least
                                               significant bit.
        initial_wavefunction: Initial wavefunction of the ancilla qubits
        ancilla_qubits(Qureg): ancilla quantum register in state |0>
        system_qubits(Qureg): system quantum register
    """
    # Apply V:
    for ancilla_state in range(len(individual_terms)):
        with Compute(eng):
            for bit_pos in range(len(ancilla_qubits)):
                if not (ancilla_state >> bit_pos) & 1:
                    X | ancilla_qubits[bit_pos]
        with Control(eng, ancilla_qubits):
            individual_terms[ancilla_state] | system_qubits
        Uncompute(eng)
    # Apply S: 1) Apply B^dagger
    with Compute(eng):
        with Dagger(eng):
            StatePreparation(initial_wavefunction) | ancilla_qubits
    # Apply S: 2) Apply I-2|0><0|
    with Compute(eng):
        All(X) | ancilla_qubits
    with Control(eng, ancilla_qubits[:-1]):
        Z | ancilla_qubits[-1]
    Uncompute(eng)
    # Apply S: 3) Apply B
    Uncompute(eng)
    # Could also be omitted and added when calculating the eigenvalues:
    Ph(math.pi) | system_qubits[0]
def test_invalid_arguments():
    qb0 = WeakQubitRef(engine=None, idx=0)
    qb1 = WeakQubitRef(engine=None, idx=1)
    cmd = Command(None, StatePreparation([0, 1j]), qubits=([qb0], [qb1]))
    with pytest.raises(ValueError):
        stateprep2cnot._decompose_state_preparation(cmd)
Beispiel #7
0

eng = projectq.MainEngine()
system_qubits = eng.allocate_qureg(num_qubits)

# Create a normalized equal superposition of the two eigenstates for numerical testing:
initial_state_norm = 0.
initial_state = [i + j for i, j in zip(eigenvectors[0], eigenvectors[1])]
for amplitude in initial_state:
    initial_state_norm += abs(amplitude)**2
normalized_initial_state = [
    amp / math.sqrt(initial_state_norm) for amp in initial_state
]

#initialize system qubits in this state:
StatePreparation(normalized_initial_state) | system_qubits

individual_terms = []
initial_ancilla_wavefunction = []
for term in normalized_hamiltonian.terms:
    coefficient = normalized_hamiltonian.terms[term]
    initial_ancilla_wavefunction.append(math.sqrt(abs(coefficient)))
    if coefficient < 0:
        individual_terms.append(QubitOperator(term, -1))
    else:
        individual_terms.append(QubitOperator(term))

# Calculate the number of ancilla qubits required and pad
# the ancilla wavefunction with zeros:
num_ancilla_qubits = int(math.ceil(math.log(len(individual_terms), 2)))
required_padding = 2**num_ancilla_qubits - len(initial_ancilla_wavefunction)
Beispiel #8
0
#Intialization
ME = MainEngine()


#Input
x,y = map(complex,input("enter the state: ").split())

#Normalization
norm = np.sqrt(np.abs(x**2) + np.abs(y**2))
x /= norm
y /= norm

#Qubit allocation , define a state for the qubit,and  measure it.
qubit = ME.allocate_qubit()
StatePreparation([x,y]) | qubit
Measure | qubit
read = int(qubit)


#Measuring output
ME.flush()
print(read)


#State vector to sphereical coordinates
phi = np.angle(y) - np.angle(x)
theta = 2 * np.arccos(np.abs(x))
vec = [np.sin(theta) * np.cos(phi), np.sin(theta) * np.sin(phi), np.cos(theta)]

#Visualization