Beispiel #1
0
def grover(n, s):
    p = Program()  # create program

    ##################
    ## Define Gates ##
    ##################
    uf = build_uf(n, s)  # build Uf
    p.defgate("Uf", uf)  # define Uf

    ug = build_ug(n)  # build Ug
    p.defgate("Ug", ug)  # define Ug

    gate_string = build_gate_string(n)  # useful for applying gates

    ####################
    ## Create Program ##
    ####################
    hadamard_n(n, p)  # apply Hadamard to first N registers
    p.inst(X(n), H(n))  # apply X and N to last register to get minus

    for i in range(int(
        (np.pi * (2**(n / 2))) / 4)):  # repeat (pi*2^(n/2))/4 times
        p.inst(("Uf" + gate_string))  # apply Uf to all registers
        hadamard_n(n, p)  # apply Hadamard to first N
        p.inst(("Ug" + gate_string[:-2]))  # apply Ug to first N
        hadamard_n(n, p)  # apply Hadamard to first N

    for i in range(n):
        p.measure(i, i)  # measure first N qubits, store in same registers

    return p
def main(n, s):
    p = Program()

    #make all the gates
    g = make_gate(n)
    Uf = make_UF_gate(n, s)
    p.defgate("RACL", g)
    p.defgate("UF", Uf)

    apply_Hn(p)  #applying the first series of H gates to the first n qubits
    p.inst(X(n), H(n))  #get the |-> qubit into our system

    r = int((math.pi * (2**(n / 2)) / 4))  #r is the number of iteration
    for i in range(r):
        p.inst(("UF", *range(n)))  #apply Uf
        apply_Hn(
            p)  #applying the second series of H gates to the first n qubits

        p.inst(("RACL", *range(n)))  #applying the unitary 2(|0><0|)^n - I^n
        apply_Hn(
            p)  #applying the third series of H gates to the first n qubits

    #Make the Measurement
    classical_regs = [*range(n)]
    for i in range(n):
        p.measure(i, i)
    result = qvm.run(p, classical_regs)
    #print (result)

    #convert the result from binary to decimal
    t = 0
    for i in range(n):
        t += (2**i) * result[0][n - 1 - i]
    print("the answer is ", t)
def test_basic_compile_defgate():
    p = Program()
    p.inst(RX(pi, 0))
    p.defgate("test", [[0, 1], [1, 0]])
    p.inst(("test", 2))
    p.inst(RZ(pi / 2, 0))

    assert p == basic_compile(p)
Beispiel #4
0
def test_prog_merge():
    prog_0 = Program(X(0))
    prog_1 = Program(Y(0))
    assert merge_programs([prog_0, prog_1]).out() == (prog_0 + prog_1).out()
    prog_0.defgate("test", np.eye(2))
    prog_0.inst(("test", 0))
    prog_1.defgate("test", np.eye(2))
    prog_1.inst(("test", 0))
    assert merge_programs([prog_0, prog_1]).out() == """DEFGATE test:
 def add_damping_dephasing_noise(prog, T1, T2, gate_time):
     p = Program()
     p.defgate("noise", np.eye(2))
     p.define_noisy_gate("noise", [0],
                         damping_after_dephasing(T1, T2, gate_time))
     for elem in prog:
         p.inst(elem)
         if isinstance(elem, Measurement):
             continue  # skip measurement
         p.inst(("noise", 0))
     return p
Beispiel #6
0
def _create_expected_program():
    expected_prog = Program()
    expected_prog.defgate("SIMON_ORACLE", EXPECTED_SIMON_ORACLE)
    expected_prog.inst("H 0")
    expected_prog.inst("H 1")
    expected_prog.inst("H 2")

    expected_prog.inst("SIMON_ORACLE 5 4 3 2 1 0")

    expected_prog.inst("H 0")
    expected_prog.inst("H 1")
    expected_prog.inst("H 2")
    return expected_prog
def grover(marked_element):
    # Determine number of qubits needed
    n = len(marked_element)
    N = 2**n
    no_marked = int(marked_element, 2)

    # Determine number of times to iterate
    T = int(round(np.pi * np.sqrt(N) / 4 - 0.5))
    print('Number of iterations T =', T)

    # Invoking and renaming Program and Connection
    qvm = QVMConnection()
    p = Program()

    # Step 1: Start with qubits in equal superposition
    for i in range(n):
        p.inst(H(i))

    # Defining Oracle matrices: U_0 and U_f
    U_0 = np.eye(N)
    U_0[0][0] = -1
    U_f = np.eye(N)
    U_f[no_marked][no_marked] = -1

    # Defining Oracle gates
    p.defgate("U0", U_0)
    p.defgate("Uf", U_f)

    # Step 2: Repeat applications of U_f and D
    for i in range(T):
        # Apply U_f
        p.inst(("Uf", ) + tuple(range(n)))

        # Apply D
        for j in range(n):
            p.inst(H(j))

        p.inst(("U0", ) + tuple(range(n)))

        for j in range(n):
            p.inst(H(j))

    # Step 3: Measure all the qubits and output result
    for i in range(n):
        p.measure(i)

    # Run the program
    results = qvm.run(p, list(range(n)), 1)

    print('Element found =', results[0])
    return results[0]
def setup(n, s):
    """ function to set up program Uf and special unitary """
    p = Program()  # initializes program

    Uf = np.identity(2**(n + 1))  # starts Uf as identity with size 2^ (n + 1)
    Uf[:, [2 * s, 2 * s + 1]] = Uf[:,
                                   [2 * s + 1, 2 * s
                                    ]]  # switch the columns of the s^th qubit
    p.defgate("Uf", Uf)  # defines array as unitary Uf

    special = -1 * np.identity(
        2**n)  # starts special as negative identity with size 2^n
    special[0, 0] = 1  # makes the very first entry positive
    p.defgate("special", special)  # defines array as unitary special

    return p
Beispiel #9
0
def test_unitary_errors(qvm_unitary):
    # do we properly throw errors when non-gates are thrown into a unitary?

    # try measuring
    prog = Program()
    prog.inst([H(0), H(1)])
    prog.measure(0, [0])
    with pytest.raises(TypeError):
        qvm_unitary.unitary(prog)

    # try an undefined DefGate
    prog = Program()
    prog.defgate("hello", np.array([[0, 1], [1, 0]]))
    prog.inst(("hello2", 0))
    with pytest.raises(TypeError):
        qvm_unitary.unitary(prog)
Beispiel #10
0
def test_if_then_inherits_defined_gates():
    p1 = Program()
    p1.inst(H(0))
    p1.measure(0, 0)

    p2 = Program()
    p2.defgate("A", np.array([[1., 0.], [0., 1.]]))
    p2.inst(("A", 0))

    p3 = Program()
    p3.defgate("B", np.array([[0., 1.], [1., 0.]]))
    p3.inst(("B", 0))

    p1.if_then(0, p2, p3)
    assert p2.defined_gates[0] in p1.defined_gates
    assert p3.defined_gates[0] in p1.defined_gates
Beispiel #11
0
def test_if_then_inherits_defined_gates():
    p1 = Program()
    p1.inst(H(0))
    p1.measure(0, MemoryReference("ro", 0))

    p2 = Program()
    p2.defgate("A", np.array([[1.0, 0.0], [0.0, 1.0]]))
    p2.inst(("A", 0))

    p3 = Program()
    p3.defgate("B", np.array([[0.0, 1.0], [1.0, 0.0]]))
    p3.inst(("B", 0))

    p1.if_then(MemoryReference("ro", 0), p2, p3)
    assert p2.defined_gates[0] in p1.defined_gates
    assert p3.defined_gates[0] in p1.defined_gates
Beispiel #12
0
def _modified_noise_model_program_header(noise_model: NoiseModel) -> "Program":
    """
    Generate the header for a pyquil Program that uses ``noise_model`` to overload noisy gates.
    The program header consists of 3 sections:

        - The ``DEFGATE`` statements that define the meaning of the newly introduced "noisy" gate
          names.
        - The ``PRAGMA ADD-KRAUS`` statements to overload these noisy gates on specific qubit
          targets with their noisy implementation.
        - THe ``PRAGMA READOUT-POVM`` statements that define the noisy readout per qubit.

    :param noise_model: The assumed noise model.
    :return: A quil Program with the noise pragmas.
    """
    from pyquil.quil import Program

    p = Program()
    defgates: Set[str] = set()
    for k in noise_model.gates:

        # obtain ideal gate matrix and new, noisy name by looking it up in the NOISY_GATES dict
        try:
            ideal_gate, new_name = get_modified_noisy_gate(
                k.gate, tuple(k.params))

            # if ideal version of gate has not yet been DEFGATE'd, do this
            if new_name not in defgates:
                p.defgate(new_name, ideal_gate)
                defgates.add(new_name)
        except NoisyGateUndefined:
            print(
                "WARNING: Could not find ideal gate definition for gate {}".
                format(k.gate),
                file=sys.stderr,
            )
            new_name = k.gate

        # define noisy version of gate on specific targets
        p.define_noisy_gate(new_name, k.targets, k.kraus_ops)

    # define noisy readouts
    for q, ap in noise_model.assignment_probs.items():
        p.define_noisy_readout(q, p00=ap[0, 0], p11=ap[1, 1])
    return p
Beispiel #13
0
def deutsch_jozsa(f):
    # Determine number of qubits needed
    N = len(f)
    n = int(np.log2(N))

    # Invoking and renaming
    qvm = QVMConnection()
    p = Program()

    # Applying first round of n Hadamards
    for i in range(n):
        p.inst(H(i))

    # Defining the Oracle matrix
    U_f = np.eye(N)
    for i in range(N):
        if f[i] == '1':
            U_f[i][i] = -1
    # Adding the Oracle matrix as a gate
    p.defgate("Uf", U_f)
    # Applying Oracle gate
    p.inst(("Uf", ) + tuple(range(n)))

    # Applying second run of n Hadamards
    for i in range(n):
        p.inst(H(i))

    # Measure all the qubits and output result
    for i in range(n):
        p.measure(i, i)

    # Run the program
    classical_reg = list(range(n))
    results = qvm.run(p, classical_reg, 1)

    y = 0
    for i in range(n):
        y = y + 2**i * int(results[0][i])

    if y == 0:
        print('Function is constant.')
    else:
        print('Function is balanced.')
Beispiel #14
0
def runAlg(cf):
    qvm = api.QVMConnection()
    p = Program()
    p.defgate('cF', cf)

    p.inst(
        # Prepare 0 as a superposition |0> + |1>
        # Prepare 1 as the Fourier Transform of |0> - |1>
        H(0),
        X(1),
        H(1),
        # one application of cF gate
        ('cF', 0, 1),
        # project and measure
        H(0),
        MEASURE(0, 0))
    print(p)
    result = qvm.run(p, [0])
    print(result)
    parseResult(result)
Beispiel #15
0
def _remove_reset_from_program(program: Program) -> Program:
    """
    Trim the RESET from a program because in measure_observables it is re-added.

    :param program: Program to remove RESET(s) from.
    :return: Trimmed Program.
    """
    definitions = [gate for gate in program.defined_gates]

    p = Program(*[inst for inst in program if not isinstance(inst, Reset)])

    for definition in definitions:
        if isinstance(definition, DefPermutationGate):
            p.inst(
                DefPermutationGate(definition.name,
                                   list(definition.permutation)))
        else:
            p.defgate(definition.name, definition.matrix,
                      definition.parameters)
    return p
def runGame(choice):
    qvm = api.QVMConnection()
    yourChoiceRegister = 0
    buddyChoiceRegister = 1

    p = Program()

    j = np.array([[1.0 / math.sqrt(2), 0, 0, 1.0j / math.sqrt(2)],
                  [0, 1.0 / math.sqrt(2), 1.0j / math.sqrt(2), 0],
                  [0, 1.0j / math.sqrt(2), 1.0 / math.sqrt(2), 0],
                  [1.0j / math.sqrt(2), 0, 0, 1.0 / math.sqrt(2)]])
    p.defgate('J', j)

    jt = np.array([[1.0 / math.sqrt(2), 0, 0, -1.0j / math.sqrt(2)],
                   [0, 1.0 / math.sqrt(2), -1.0j / math.sqrt(2), 0],
                   [0, -1.0j / math.sqrt(2), 1.0 / math.sqrt(2), 0],
                   [-1.0j / math.sqrt(2), 0, 0, 1.0 / math.sqrt(2)]])
    p.defgate('Jt', jt)

    if choice == 'snitch':
        yourAction = X(yourChoiceRegister)
    elif choice == 'silent':
        yourAction = I(yourChoiceRegister)

    print('your buddy will play the miracle move:')
    miracleMove = np.array([[1.0j / math.sqrt(2), 1.0 / math.sqrt(2)],
                            [-1.0 / math.sqrt(2), -1.0j / math.sqrt(2)]])
    p.defgate('MIRACLE', miracleMove)
    buddyAction = (('MIRACLE', buddyChoiceRegister))

    p.inst(('J', 0, 1), yourAction, buddyAction, ('Jt', 0, 1), MEASURE(1, 1),
           MEASURE(0, 0))
    print(p)
    result = qvm.run(p, [0, 1], 90)
    print(result)

    parseResult(result)
Beispiel #17
0
def add_noise_to_program(prog,
                         T1=30e-6,
                         T2=None,
                         gate_time_1q=50e-9,
                         gate_time_2q=150e-09):
    """
    Add generic damping and dephasing noise to a program.

    This high-level function is provided as a convenience to investigate the effects of a
    generic noise model on a program. For more fine-grained control, please investigate
    the other methods available in the ``pyquil.kraus`` module.

    In an attempt to closely model the QPU, noisy versions of RX(+-pi/2) and CZ are provided;
    I and parametric RZ are noiseless, and other gates are not allowed. To use this function,
    you need to compile your program to this native gate set.

    The default noise parameters

    - T1 = 30 us
    - T2 = T1 / 2
    - 1q gate time = 50 ns
    - 2q gate time = 150 ns

    are currently typical for near-term devices.

    This function will define new gates and add Kraus noise to these gates. It will translate
    the input program to use the noisy version of the gates.

    :param prog: A pyquil program consisting of I, RZ, CZ, and RX(+-pi/2) instructions
    :param T1: The T1 amplitude damping time. By default, this is 30 us
    :param T2: The T2 dephasing time. By default, this is one-half of the T1 time.
    :param gate_time_1q: The duration of the one-qubit gates, namely RX(+pi/2) and RX(-pi/2).
        By default, this is 50 ns.
    :param gate_time_2q: The duration of the two-qubit gates, namely CZ.
        By default, this is 150 ns.
    :return: A new program with noisy operators.
    """

    if T2 is None:
        T2 = T1 / 2.0

    from pyquil.quil import Program  # Avoid circular dependency
    qubits, edges = _get_program_topology(prog)
    new_prog = Program()

    # Define noisy 1q gates
    for name, matrix in SINGLE_Q.items():
        new_prog.defgate(name, matrix)
        k_ops = append_kraus_to_gate(damping_after_dephasing(
            T1=T1, T2=T2, gate_time=gate_time_1q),
                                     gate_matrix=matrix)
        for qubit in qubits:
            new_prog.define_noisy_gate(name, (qubit, ), k_ops)

    # Define noisy 2q gates
    for name, matrix in TWO_Q.items():
        new_prog.defgate(name, matrix)
        k1q = damping_after_dephasing(T1=T1, T2=T2, gate_time=gate_time_2q)
        k_total = append_kraus_to_gate(tensor_kraus_maps(k1q, k1q),
                                       gate_matrix=matrix)
        for q1, q2 in edges:
            # Note! q1 must be less than q2. This is done in _get_program_topology
            assert q1 < q2
            new_prog.define_noisy_gate(name, (q1, q2), k_total)

    # Translate noiseless gates to noisy gates.
    new_instrs = [_noisy_instruction(instruction) for instruction in prog]
    new_prog.inst(new_instrs)

    return new_prog
Beispiel #18
0
d_prog.inst(I(qubits[0]), I(qubits[1]))
#print(qvm.wavefunction(d_prog))

# \psi_1: Put ancilla qubit into 1
d_prog.inst(X(qubits[1]))
#print(qvm.wavefunction(d_prog))

# \psi_2: Apply Hadamard gates
d_prog.inst(H(qubits[0]), H(qubits[1]))
#print(qvm.wavefunction(d_prog))

# \psi_3:  Apply Quantum Oracle
# Quantum oracle
ORACLE_GATE_NAME = "DEUTSCH_JOZSA_ORACLE"
oracle = np.array([[0, 1, 0, 0], [1, 0, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]])
d_prog.defgate(ORACLE_GATE_NAME, oracle)
d_prog.inst((ORACLE_GATE_NAME, qubits[0], qubits[1]))
#print(qvm.wavefunction(d_prog))

# \psi_4: Apply Hadamard gate
d_prog.inst(H(qubits[0]))
#print(qvm.wavefunction(d_prog))

# \psi_5: Measure
d_prog.measure(qubit_index=qubits[0], classical_reg=0)

# Run
ret = qvm.run(d_prog, classical_addresses=[0])
if ret[0][0] == 0:
    print("The function is constant")
else:
def counterpoint():
    pitch_index = int(request.args['pitch_index'])
    #print("pitch_index: ", pitch_index)
    if (pitch_index >= NUM_PITCHES):
        pitch_index %= (NUM_PITCHES - 1)

    melodic_degrees = request.args['melodic_degrees'].split(",")
    #print("melodic_degrees: ", melodic_degrees)

    harmonic_degrees = request.args['harmonic_degrees'].split(",")
    #print("harmonic_degrees: ", harmonic_degrees)

    if (len(melodic_degrees) == DEGREES_OF_FREEDOM
            and len(harmonic_degrees) == DEGREES_OF_FREEDOM
            and 0 <= pitch_index < NUM_PITCHES):

        melodic_gate_matrix = compute_matrix(melodic_degrees)
        harmonic_gate_matrix = compute_matrix(harmonic_degrees)

        qvm = api.QVMConnection()
        p = Program()

        p.defgate("MELODIC_GATE", melodic_gate_matrix)
        p.defgate("HARMONIC_GATE", harmonic_gate_matrix)

        # Convert the pitch index to a binary string, and use it to create
        # the initial gates on the three wires of the quantum circuit,
        # least significant qubit on the lowest number wire.
        # Also, place initial pitch into Lead Note #1
        qubit_string = format(pitch_index, '03b')
        for idx, qubit_char in enumerate(qubit_string):
            if qubit_char == '0':
                p.inst(I(NUM_CIRCUIT_WIRES - 1 - idx))
                p.inst(FALSE(NUM_CIRCUIT_WIRES - 1 - idx))
            else:
                p.inst(X(NUM_CIRCUIT_WIRES - 1 - idx))
                p.inst(TRUE(NUM_CIRCUIT_WIRES - 1 - idx))

        p.inst(
            RawInstr("""
DEFCIRCUIT ACTIVE-RESET q scratch_bit:
    MEASURE q scratch_bit
    JUMP-UNLESS @END-ACTIVE-SET scratch_bit
    X q
    LABEL @END-ACTIVE-SET

DEFCIRCUIT ACTIVE-SET q scratch_bit:
    MEASURE q scratch_bit
    JUMP-WHEN @END-ACTIVE-RESET scratch_bit
    X q
    LABEL @END-ACTIVE-RESET

# == Produce melody ==
# ---- Produce pitch for Lead Note #2 and replicate measurement results into qubits ----
MELODIC_GATE 2 1 0

MEASURE 2 [5]
MEASURE 1 [4]
MEASURE 0 [3]

JUMP-UNLESS @RESET-Q5 [5]
ACTIVE-SET 2 [63]
JUMP @END-Q5
LABEL @RESET-Q5
ACTIVE-RESET 5 [63]
LABEL @END-Q5 

JUMP-UNLESS @RESET-Q4 [4]
ACTIVE-SET 1 [63]
JUMP @END-Q4
LABEL @RESET-Q4
ACTIVE-RESET 4 [63]
LABEL @END-Q4 

JUMP-UNLESS @RESET-Q3 [3]
ACTIVE-SET 0 [63]
JUMP @END-Q3
LABEL @RESET-Q3
ACTIVE-RESET 3 [63]
LABEL @END-Q3 

# ---- Produce pitch for Lead Note #3 and replicate measurement results into qubits ----
MELODIC_GATE 2 1 0

MEASURE 2 [8]
MEASURE 1 [7]
MEASURE 0 [6]

JUMP-UNLESS @RESET-Q8 [8]
ACTIVE-SET 2 [63]
JUMP @END-Q8
LABEL @RESET-Q8
ACTIVE-RESET 2 [63]
LABEL @END-Q8 

JUMP-UNLESS @RESET-Q7 [7]
ACTIVE-SET 1 [63]
JUMP @END-Q7
LABEL @RESET-Q7
ACTIVE-RESET 1 [63]
LABEL @END-Q7 

JUMP-UNLESS @RESET-Q6 [6]
ACTIVE-SET 0 [63]
JUMP @END-Q6
LABEL @RESET-Q6
ACTIVE-RESET 0 [63]
LABEL @END-Q6 

# ---- Produce pitch for Lead Note #4 and replicate measurement results into qubits ----
MELODIC_GATE 2 1 0

MEASURE 2 [11]
MEASURE 1 [10]
MEASURE 0 [9]

JUMP-UNLESS @RESET-Q11 [11]
ACTIVE-SET 2 [63]
JUMP @END-Q11
LABEL @RESET-Q11
ACTIVE-RESET 2 [63]
LABEL @END-Q11 

JUMP-UNLESS @RESET-Q10 [10]
ACTIVE-SET 1 [63]
JUMP @END-Q10
LABEL @RESET-Q10
ACTIVE-RESET 1 [63]
LABEL @END-Q10 

JUMP-UNLESS @RESET-Q9 [9]
ACTIVE-SET 0 [63]
JUMP @END-Q9
LABEL @RESET-Q9
ACTIVE-RESET 0 [63]
LABEL @END-Q9 

# ---- Produce pitch for Lead Note #5 and replicate measurement results into qubits ----
MELODIC_GATE 2 1 0

MEASURE 2 [14]
MEASURE 1 [13]
MEASURE 0 [12]

JUMP-UNLESS @RESET-Q14 [14]
ACTIVE-SET 2 [63]
JUMP @END-Q14
LABEL @RESET-Q14
ACTIVE-RESET 2 [63]
LABEL @END-Q14 

JUMP-UNLESS @RESET-Q13 [13]
ACTIVE-SET 1 [63]
JUMP @END-Q13
LABEL @RESET-Q13
ACTIVE-RESET 1 [63]
LABEL @END-Q13 

JUMP-UNLESS @RESET-Q12 [12]
ACTIVE-SET 0 [63]
JUMP @END-Q12
LABEL @RESET-Q12
ACTIVE-RESET 0 [63]
LABEL @END-Q12 

# ---- Produce pitch for Lead Note #6 and replicate measurement results into qubits ----
MELODIC_GATE 2 1 0

MEASURE 2 [17]
MEASURE 1 [16]
MEASURE 0 [15]

JUMP-UNLESS @RESET-Q17 [17]
ACTIVE-SET 2 [63]
JUMP @END-Q17
LABEL @RESET-Q17
ACTIVE-RESET 2 [63]
LABEL @END-Q17 

JUMP-UNLESS @RESET-Q16 [16]
ACTIVE-SET 1 [63]
JUMP @END-Q16
LABEL @RESET-Q16
ACTIVE-RESET 1 [63]
LABEL @END-Q16 

JUMP-UNLESS @RESET-Q15 [15]
ACTIVE-SET 0 [63]
JUMP @END-Q15
LABEL @RESET-Q15
ACTIVE-RESET 0 [63]
LABEL @END-Q15 

# ---- Produce pitch for Lead Note #7 and replicate measurement results into qubits ----
MELODIC_GATE 2 1 0

MEASURE 2 [20]
MEASURE 1 [19]
MEASURE 0 [18]

# == Produce harmony ==
# ---- Retrieve pitch for Lead Note #1, replicate it into qubits, and produce pitch for Harmony Note #1a ----
JUMP-UNLESS @RESET-Q2a [2]
ACTIVE-SET 2 [63]
JUMP @END-Q2a
LABEL @RESET-Q2a
ACTIVE-RESET 2 [63]
LABEL @END-Q2a 

JUMP-UNLESS @RESET-Q1a [1]
ACTIVE-SET 1 [63]
JUMP @END-Q1a
LABEL @RESET-Q1a
ACTIVE-RESET 1 [63]
LABEL @END-Q1a 

JUMP-UNLESS @RESET-Q0a [0]
ACTIVE-SET 0 [63]
JUMP @END-Q0a
LABEL @RESET-Q0a
ACTIVE-RESET 0 [63]
LABEL @END-Q0a 

HARMONIC_GATE 2 1 0

MEASURE 2 [23]
MEASURE 1 [22]
MEASURE 0 [21]

# ---- Replicate Harmony Note #1a into qubits, and produce pitch for Harmony Note #1b ----
JUMP-UNLESS @RESET-Q23 [23]
ACTIVE-SET 2 [63]
JUMP @END-Q23
LABEL @RESET-Q23
ACTIVE-RESET 2 [63]
LABEL @END-Q23 

JUMP-UNLESS @RESET-Q22 [22]
ACTIVE-SET 1 [63]
JUMP @END-Q22
LABEL @RESET-Q22
ACTIVE-RESET 1 [63]
LABEL @END-Q22 

JUMP-UNLESS @RESET-Q21 [21]
ACTIVE-SET 0 [63]
JUMP @END-Q21
LABEL @RESET-Q21
ACTIVE-RESET 0 [63]
LABEL @END-Q21 

MELODIC_GATE 2 1 0

MEASURE 2 [44]
MEASURE 1 [43]
MEASURE 0 [42]

# ---- Retrieve pitch for Lead Note #2, replicate it into qubits, and produce pitch for Harmony Note #2a ----
JUMP-UNLESS @RESET-Q5a [5]
ACTIVE-SET 2 [63]
JUMP @END-Q5a
LABEL @RESET-Q5a
ACTIVE-RESET 2 [63]
LABEL @END-Q5a 

JUMP-UNLESS @RESET-Q4a [4]
ACTIVE-SET 1 [63]
JUMP @END-Q4a
LABEL @RESET-Q4a
ACTIVE-RESET 1 [63]
LABEL @END-Q4a 

JUMP-UNLESS @RESET-Q3a [3]
ACTIVE-SET 0 [63]
JUMP @END-Q3a
LABEL @RESET-Q3a
ACTIVE-RESET 0 [63]
LABEL @END-Q3a 

HARMONIC_GATE 2 1 0

MEASURE 2 [26]
MEASURE 1 [25]
MEASURE 0 [24]

# ---- Replicate Harmony Note #2a into qubits, and produce pitch for Harmony Note #2b ----
JUMP-UNLESS @RESET-Q26 [26]
ACTIVE-SET 2 [63]
JUMP @END-Q26
LABEL @RESET-Q26
ACTIVE-RESET 2 [63]
LABEL @END-Q26 

JUMP-UNLESS @RESET-Q25 [25]
ACTIVE-SET 1 [63]
JUMP @END-Q25
LABEL @RESET-Q25
ACTIVE-RESET 1 [63]
LABEL @END-Q25 

JUMP-UNLESS @RESET-Q24 [24]
ACTIVE-SET 0 [63]
JUMP @END-Q24
LABEL @RESET-Q24
ACTIVE-RESET 0 [63]
LABEL @END-Q24 

MELODIC_GATE 2 1 0

MEASURE 2 [47]
MEASURE 1 [46]
MEASURE 0 [45]

# ---- Retrieve pitch for Lead Note #3, replicate it into qubits, and produce pitch for Harmony Note #3a ----
JUMP-UNLESS @RESET-Q8a [8]
ACTIVE-SET 2 [63]
JUMP @END-Q8a
LABEL @RESET-Q8a
ACTIVE-RESET 2 [63]
LABEL @END-Q8a 

JUMP-UNLESS @RESET-Q7a [7]
ACTIVE-SET 1 [63]
JUMP @END-Q7a
LABEL @RESET-Q7a
ACTIVE-RESET 1 [63]
LABEL @END-Q7a 

JUMP-UNLESS @RESET-Q6a [6]
ACTIVE-SET 0 [63]
JUMP @END-Q6a
LABEL @RESET-Q6a
ACTIVE-RESET 0 [63]
LABEL @END-Q6a 

HARMONIC_GATE 2 1 0

MEASURE 2 [29]
MEASURE 1 [28]
MEASURE 0 [27]

# ---- Replicate Harmony Note #3a into qubits, and produce pitch for Harmony Note #3b ----
JUMP-UNLESS @RESET-Q29 [29]
ACTIVE-SET 2 [63]
JUMP @END-Q29
LABEL @RESET-Q29
ACTIVE-RESET 2 [63]
LABEL @END-Q29 

JUMP-UNLESS @RESET-Q28 [28]
ACTIVE-SET 1 [63]
JUMP @END-Q28
LABEL @RESET-Q28
ACTIVE-RESET 1 [63]
LABEL @END-Q28 

JUMP-UNLESS @RESET-Q27 [27]
ACTIVE-SET 0 [63]
JUMP @END-Q27
LABEL @RESET-Q27
ACTIVE-RESET 0 [63]
LABEL @END-Q27 

MELODIC_GATE 2 1 0

MEASURE 2 [50]
MEASURE 1 [49]
MEASURE 0 [48]

# ---- Retrieve pitch for Lead Note #4, replicate it into qubits, and produce pitch for Harmony Note #4a ----
JUMP-UNLESS @RESET-Q11a [11]
ACTIVE-SET 2 [63]
JUMP @END-Q11a
LABEL @RESET-Q11a
ACTIVE-RESET 2 [63]
LABEL @END-Q11a 

JUMP-UNLESS @RESET-Q10a [10]
ACTIVE-SET 1 [63]
JUMP @END-Q10a
LABEL @RESET-Q10a
ACTIVE-RESET 1 [63]
LABEL @END-Q10a 

JUMP-UNLESS @RESET-Q9a [9]
ACTIVE-SET 0 [63]
JUMP @END-Q9a
LABEL @RESET-Q9a
ACTIVE-RESET 0 [63]
LABEL @END-Q9a 

HARMONIC_GATE 2 1 0

MEASURE 2 [32]
MEASURE 1 [31]
MEASURE 0 [30]

# ---- Replicate Harmony Note #4a into qubits, and produce pitch for Harmony Note #4b ----
JUMP-UNLESS @RESET-Q32 [32]
ACTIVE-SET 2 [63]
JUMP @END-Q32
LABEL @RESET-Q32
ACTIVE-RESET 2 [63]
LABEL @END-Q32 

JUMP-UNLESS @RESET-Q31 [31]
ACTIVE-SET 1 [63]
JUMP @END-Q31
LABEL @RESET-Q31
ACTIVE-RESET 1 [63]
LABEL @END-Q31 

JUMP-UNLESS @RESET-Q30 [30]
ACTIVE-SET 0 [63]
JUMP @END-Q30
LABEL @RESET-Q30
ACTIVE-RESET 0 [63]
LABEL @END-Q30 

MELODIC_GATE 2 1 0

MEASURE 2 [53]
MEASURE 1 [52]
MEASURE 0 [51]

# ---- Retrieve pitch for Lead Note #5, replicate it into qubits, and produce pitch for Harmony Note #5a ----
JUMP-UNLESS @RESET-Q14a [14]
ACTIVE-SET 2 [63]
JUMP @END-Q14a
LABEL @RESET-Q14a
ACTIVE-RESET 2 [63]
LABEL @END-Q14a 

JUMP-UNLESS @RESET-Q13a [13]
ACTIVE-SET 1 [63]
JUMP @END-Q13a
LABEL @RESET-Q13a
ACTIVE-RESET 1 [63]
LABEL @END-Q13a 

JUMP-UNLESS @RESET-Q12a [12]
ACTIVE-SET 0 [63]
JUMP @END-Q12a
LABEL @RESET-Q12a
ACTIVE-RESET 0 [63]
LABEL @END-Q12a 

HARMONIC_GATE 2 1 0

MEASURE 2 [35]
MEASURE 1 [34]
MEASURE 0 [33]

# ---- Replicate Harmony Note #5a into qubits, and produce pitch for Harmony Note #5b ----
JUMP-UNLESS @RESET-Q35 [35]
ACTIVE-SET 2 [63]
JUMP @END-Q35
LABEL @RESET-Q35
ACTIVE-RESET 2 [63]
LABEL @END-Q35 

JUMP-UNLESS @RESET-Q34 [34]
ACTIVE-SET 1 [63]
JUMP @END-Q34
LABEL @RESET-Q34
ACTIVE-RESET 1 [63]
LABEL @END-Q34 

JUMP-UNLESS @RESET-Q33 [33]
ACTIVE-SET 0 [63]
JUMP @END-Q33
LABEL @RESET-Q33
ACTIVE-RESET 0 [63]
LABEL @END-Q33 

MELODIC_GATE 2 1 0

MEASURE 2 [56]
MEASURE 1 [55]
MEASURE 0 [54]

# ---- Retrieve pitch for Lead Note #6, replicate it into qubits, and produce pitch for Harmony Note #6a ----
JUMP-UNLESS @RESET-Q17a [17]
ACTIVE-SET 2 [63]
JUMP @END-Q17a
LABEL @RESET-Q17a
ACTIVE-RESET 2 [63]
LABEL @END-Q17a 

JUMP-UNLESS @RESET-Q16a [16]
ACTIVE-SET 1 [63]
JUMP @END-Q16a
LABEL @RESET-Q16a
ACTIVE-RESET 1 [63]
LABEL @END-Q16a 

JUMP-UNLESS @RESET-Q15a [15]
ACTIVE-SET 0 [63]
JUMP @END-Q15a
LABEL @RESET-Q15a
ACTIVE-RESET 0 [63]
LABEL @END-Q15a 

HARMONIC_GATE 2 1 0

MEASURE 2 [38]
MEASURE 1 [37]
MEASURE 0 [36]

# ---- Replicate Harmony Note #6a into qubits, and produce pitch for Harmony Note #6b ----
JUMP-UNLESS @RESET-Q38 [38]
ACTIVE-SET 2 [63]
JUMP @END-Q38
LABEL @RESET-Q38
ACTIVE-RESET 2 [63]
LABEL @END-Q38 

JUMP-UNLESS @RESET-Q37 [37]
ACTIVE-SET 1 [63]
JUMP @END-Q37
LABEL @RESET-Q37
ACTIVE-RESET 1 [63]
LABEL @END-Q37 

JUMP-UNLESS @RESET-Q36 [36]
ACTIVE-SET 0 [63]
JUMP @END-Q36
LABEL @RESET-Q36
ACTIVE-RESET 0 [63]
LABEL @END-Q36 

MELODIC_GATE 2 1 0

MEASURE 2 [59]
MEASURE 1 [58]
MEASURE 0 [57]

# ---- Retrieve pitch for Lead Note #7, replicate it into qubits, and produce pitch for Harmony Note #7a ----
JUMP-UNLESS @RESET-Q20a [20]
ACTIVE-SET 2 [63]
JUMP @END-Q20a
LABEL @RESET-Q20a
ACTIVE-RESET 2 [63]
LABEL @END-Q20a 

JUMP-UNLESS @RESET-Q19a [19]
ACTIVE-SET 1 [63]
JUMP @END-Q19a
LABEL @RESET-Q19a
ACTIVE-RESET 1 [63]
LABEL @END-Q19a 

JUMP-UNLESS @RESET-Q18a [18]
ACTIVE-SET 0 [63]
JUMP @END-Q18a
LABEL @RESET-Q18a
ACTIVE-RESET 0 [63]
LABEL @END-Q18a 

HARMONIC_GATE 2 1 0

MEASURE 2 [41]
MEASURE 1 [40]
MEASURE 0 [39]

# ---- Replicate Harmony Note #7a into qubits, and produce pitch for Harmony Note #7b ----
JUMP-UNLESS @RESET-Q41 [41]
ACTIVE-SET 2 [63]
JUMP @END-Q41
LABEL @RESET-Q41
ACTIVE-RESET 2 [63]
LABEL @END-Q41 

JUMP-UNLESS @RESET-Q40 [40]
ACTIVE-SET 1 [63]
JUMP @END-Q40
LABEL @RESET-Q40
ACTIVE-RESET 1 [63]
LABEL @END-Q40 

JUMP-UNLESS @RESET-Q39 [39]
ACTIVE-SET 0 [63]
JUMP @END-Q39
LABEL @RESET-Q39
ACTIVE-RESET 0 [63]
LABEL @END-Q39 

MELODIC_GATE 2 1 0

MEASURE 2 [62]
MEASURE 1 [61]
MEASURE 0 [60]
"""))

    #print(p)

    use_simulator = True

    if use_simulator:
        num_runs = 1
        res = qvm.run(p, [
            2, 1, 0, 5, 4, 3, 8, 7, 6, 11, 10, 9, 14, 13, 12, 17, 16, 15, 20,
            19, 18, 23, 22, 21, 44, 43, 42, 26, 25, 24, 47, 46, 45, 29, 28, 27,
            50, 49, 48, 32, 31, 30, 53, 52, 51, 35, 34, 33, 56, 55, 54, 38, 37,
            36, 59, 58, 57, 41, 40, 39, 62, 61, 60
        ], num_runs)
        #print(res)

        all_note_nums = create_note_nums_array(res[0])
        melody_note_nums = all_note_nums[0:7]
        harmony_note_nums = all_note_nums[7:21]
    else:
        melody_note_nums = [0, 1, 2, 3, 4, 5, 6]
        harmony_note_nums = [2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 4, 3, 2]

    ret_dict = {
        "melody": melody_note_nums,
        "harmony": harmony_note_nums,
        "lilypond": create_lilypond(melody_note_nums, harmony_note_nums),
        "toy_piano": create_toy_piano(melody_note_nums, harmony_note_nums)
    }

    return jsonify(ret_dict)
def counterpoint_degraded():
    pitch_index = int(request.args['pitch_index'])
    if (pitch_index >= NUM_PITCHES):
        pitch_index %= (NUM_PITCHES - 1)
    #print("pitch_index: ", pitch_index)

    species = int(request.args['species'])
    #print("species: ", species)

    melodic_degrees = request.args['melodic_degrees'].split(",")
    #print("melodic_degrees: ", melodic_degrees)

    harmonic_degrees = request.args['harmonic_degrees'].split(",")
    #print("harmonic_degrees: ", harmonic_degrees)

    if (len(melodic_degrees) == DEGREES_OF_FREEDOM
            and len(harmonic_degrees) == DEGREES_OF_FREEDOM
            and 1 <= species <= 3 and 0 <= pitch_index < NUM_PITCHES):

        #TODO: Move/change this
        rot_melodic_circuit = compute_circuit(melodic_degrees)
        print("rot_melodic_circuit:")
        print(rot_melodic_circuit)
        rot_harmonic_circuit = compute_circuit(harmonic_degrees)

        melodic_gate_matrix = compute_matrix(melodic_degrees)
        harmonic_gate_matrix = compute_matrix(harmonic_degrees)

        harmony_notes_factor = 2**(
            species - 1)  # Number of harmony notes for each melody note
        num_composition_bits = TOTAL_MELODY_NOTES * (harmony_notes_factor +
                                                     1) * NUM_CIRCUIT_WIRES

        qvm = api.QVMConnection()

        composition_bits = [0] * num_composition_bits

        # Convert the pitch index to a binary string, and place into the
        # composition_bits array, least significant bits in lowest elements of array
        qubit_string = format(pitch_index, '03b')
        for idx, qubit_char in enumerate(qubit_string):
            if qubit_char == '0':
                composition_bits[idx] = 0
            else:
                composition_bits[idx] = 1

        num_runs = 1

        for melody_note_idx in range(0, TOTAL_MELODY_NOTES):
            #
            if (melody_note_idx < TOTAL_MELODY_NOTES - 1):
                p = Program()
                if USE_ROTATIONS_CIRCUITS:
                    nop = 0
                    #p.inst(copy.deepcopy(rot_melodic_circuit))
                else:
                    p.defgate("MELODIC_GATE", melodic_gate_matrix)

                for bit_idx in range(0, NUM_CIRCUIT_WIRES):
                    if (composition_bits[melody_note_idx * NUM_CIRCUIT_WIRES +
                                         bit_idx] == 0):
                        p.inst(I(NUM_CIRCUIT_WIRES - 1 - bit_idx))
                    else:
                        p.inst(X(NUM_CIRCUIT_WIRES - 1 - bit_idx))

                if USE_ROTATIONS_CIRCUITS:
                    p.inst(copy.deepcopy(rot_melodic_circuit))
                    p.inst().measure(0, 0).measure(1, 1) \
                        .measure(2, 2)
                    print("rot_melodic_circuit:")
                    #print(p)
                else:
                    p.inst(("MELODIC_GATE", 2, 1, 0)) \
                        .measure(0, 0).measure(1, 1) \
                        .measure(2, 2)
                    print("matrix_melodic_circuit:")
                    #print(p)

                result = qvm.run(p, [2, 1, 0], num_runs)
                bits = result[0]
                for bit_idx in range(0, NUM_CIRCUIT_WIRES):
                    composition_bits[(melody_note_idx + 1) * NUM_CIRCUIT_WIRES
                                     + bit_idx] = bits[bit_idx]

                #print(composition_bits)

                measured_pitch = bits[0] * 4 + bits[1] * 2 + bits[2]
                #print("melody melody_note_idx measured_pitch")
                #print(melody_note_idx)
                #print(measured_pitch)

            # Now compute a harmony note for the melody note
            print("Now compute a harmony note for the melody notev")
            p = Program()
            if USE_ROTATIONS_CIRCUITS:
                nop = 0
                #p = copy.deepcopy(rot_harmonic_circuit)
            else:
                p.defgate("HARMONIC_GATE", harmonic_gate_matrix)

            for bit_idx in range(0, NUM_CIRCUIT_WIRES):
                if composition_bits[melody_note_idx * NUM_CIRCUIT_WIRES +
                                    bit_idx] == 0:
                    p.inst(I(NUM_CIRCUIT_WIRES - 1 - bit_idx))
                else:
                    p.inst(X(NUM_CIRCUIT_WIRES - 1 - bit_idx))

            if USE_ROTATIONS_CIRCUITS:
                p.inst(copy.deepcopy(rot_harmonic_circuit))
                p.inst().measure(0, 0).measure(1, 1) \
                    .measure(2, 2)
                print("rot_harmonic_circuit:")
                #print(p)
            else:
                p.inst(("HARMONIC_GATE", 2, 1, 0)) \
                    .measure(0, 0).measure(1, 1) \
                    .measure(2, 2)
                print("matrix_harmonic_circuit:")
                #print(p)

            result = qvm.run(p, [2, 1, 0], num_runs)
            bits = result[0]
            for bit_idx in range(0, NUM_CIRCUIT_WIRES):
                composition_bits[(melody_note_idx * NUM_CIRCUIT_WIRES *
                                  harmony_notes_factor) +
                                 (TOTAL_MELODY_NOTES * NUM_CIRCUIT_WIRES) +
                                 bit_idx] = bits[bit_idx]

            #print(composition_bits)

            measured_pitch = bits[0] * 4 + bits[1] * 2 + bits[2]
            #print("harmony melody_note_idx measured_pitch")
            #print(melody_note_idx)
            #print(measured_pitch)

            # Now compute melody notes to follow the harmony note
            print("Now compute melody notes to follow the harmony note")
            for harmony_note_idx in range(1, harmony_notes_factor):
                p = Program()
                if USE_ROTATIONS_CIRCUITS:
                    nop = 0
                    #p = copy.deepcopy(rot_melodic_circuit)
                else:
                    p.defgate("MELODIC_GATE", melodic_gate_matrix)

                for bit_idx in range(0, NUM_CIRCUIT_WIRES):
                    if (composition_bits[
                        (melody_note_idx * NUM_CIRCUIT_WIRES *
                         harmony_notes_factor) +
                        ((harmony_note_idx - 1) * NUM_CIRCUIT_WIRES) +
                        (TOTAL_MELODY_NOTES * NUM_CIRCUIT_WIRES) +
                            bit_idx] == 0):
                        p.inst(I(NUM_CIRCUIT_WIRES - 1 - bit_idx))
                    else:
                        p.inst(X(NUM_CIRCUIT_WIRES - 1 - bit_idx))

                if USE_ROTATIONS_CIRCUITS:
                    p.inst(copy.deepcopy(rot_melodic_circuit))
                    p.inst().measure(0, 0).measure(1, 1) \
                        .measure(2, 2)
                    print("rot_melodic_circuit:")
                    #print(p)
                else:
                    p.inst(("MELODIC_GATE", 2, 1, 0)) \
                        .measure(0, 0).measure(1, 1) \
                        .measure(2, 2)
                    print("matrix_melodic_circuit:")
                    #print(p)

                result = qvm.run(p, [2, 1, 0], num_runs)
                bits = result[0]
                for bit_idx in range(0, NUM_CIRCUIT_WIRES):
                    composition_bits[(melody_note_idx * NUM_CIRCUIT_WIRES *
                                      harmony_notes_factor) +
                                     ((harmony_note_idx) * NUM_CIRCUIT_WIRES) +
                                     (TOTAL_MELODY_NOTES * NUM_CIRCUIT_WIRES) +
                                     bit_idx] = bits[bit_idx]

                #print(composition_bits)

                measured_pitch = bits[0] * 4 + bits[1] * 2 + bits[2]
                #print("melody after harmony melody_note_idx measured_pitch")
                #print(melody_note_idx)
                #print(measured_pitch)

        all_note_nums = create_note_nums_array(composition_bits)
        melody_note_nums = all_note_nums[0:TOTAL_MELODY_NOTES]
        harmony_note_nums = all_note_nums[7:num_composition_bits]

    ret_dict = {
        "melody": melody_note_nums,
        "harmony": harmony_note_nums,
        "lilypond": create_lilypond(melody_note_nums, harmony_note_nums),
        "toy_piano": create_toy_piano(melody_note_nums, harmony_note_nums)
    }

    return jsonify(ret_dict)
Beispiel #21
0
#==============================================================================
qvm = QVMConnection()
gr_prog = Program()
        
# \psi_0: Qubits initilization
qubits = list(reversed(range(N)))
gr_prog.inst([I(q) for q in qubits])
#print(qvm.wavefunction(gr_prog))

# \psi_1: Apply Hadamard gates
gr_prog.inst([H(q) for q in qubits])
#print(qvm.wavefunction(gr_prog))

# Define quantum oracle
ORACLE_GATE_NAME = "GROVER_ORACLE"
gr_prog.defgate(ORACLE_GATE_NAME, oracle)

# Define inversion around the mean
DIFFUSION_GATE_NAME = "DIFFUSION"
diffusion = 2.0 * np.full((2**N, 2**N), 1/(2**N)) - np.eye(2**N)
gr_prog.defgate(DIFFUSION_GATE_NAME, diffusion)

# Number of algorithm iterations
N_ITER = int(np.pi / 4 * np.sqrt(2**N))

# Loop
for i in range(N_ITER):
    
    # \psi_2^i:  Apply Quantum Oracle
    gr_prog.inst(tuple([ORACLE_GATE_NAME] + qubits))
    #print(qvm.wavefunction(gr_prog))
import numpy as np
from pyquil.quil import Program
from pyquil.api import QVMConnection
from pyquil.gates import X, Z, Y, H, I
from pyquilcompiler import compiletoquil
# Invoking and renaming
qvm = QVMConnection()
p = Program()
# Gate implementation
p.inst(H(0), H(1))
# Assuming the given function give the matrix
Ufma = np.diag([-1, 1, -1, 1])
p.defgate("Uf", Ufma)
p.inst(("Uf", 0, 1))
p.inst(H(0), H(1))
# Measurements
p.measure(0, 0)
p.measure(1, 1)

compiletoquil(p)
# Running the program
cr = []
results = qvm.run(p, cr, 4)
print(results)
Beispiel #23
0
 # make scren blue
 screen.fill(blue)
 # empty out results from dartboard_B
 if len(results_B) > 0:
     results_B.pop()
 # run the common parts of the program
 p = Program()
 if score < 10:
     a = np.sqrt(1 / 2.)
 elif (score >= 10) and (score < 20):
     a = np.sqrt(3 / 4.)
 else:
     a = np.sqrt(1.)
 b = np.sqrt(1 - np.square(a))
 Uf_ = np.array([[a, b], [b, -a]])
 p.defgate("Uf", Uf_)
 # set dartboard_A center, and calculate results_B in either case
 if results_A == [[0]]:
     dartboard_A_center = [size_x // 2, size_y // 2 - dartboard_offset]
     # run the program for this case
     p.inst(I(0))
     p.inst(("Uf", 0))
     p.measure(0, [0])
     results_B = cxn.run(p, [0])
 elif results_A == [[1]]:
     dartboard_A_center = [size_x // 2, size_y // 2 + dartboard_offset]
     # run the program for this case
     p.inst(X(0))
     p.inst(("Uf", 0))
     p.measure(0, [0])
     results_B = cxn.run(p, [0])
        # draw DESTRUCTION! log
        pygame.draw.rect(screen, (0, 0, 0), (0, dest_y, size_x, dest_width))
        ### Carry out program
        # initialize program
        qvm = api.QVMConnection()
        p = Program()

        ##### Q's 1st stochastic move
        # set the parameters for the random move
        prob = Q_prob1
        # create a dummy gate
        a = np.random.rand()
        b = np.sqrt(1 - np.square(a))
        Uf_ = U_(a, b)
        # perform the random move
        p.defgate("Uf_Q1", Uf_)
        p.inst(("Uf_Q1", 0))
        p.define_noisy_gate(
            "Uf_Q1", [0],
            [np.sqrt(prob) * X_, np.sqrt(1 - prob) * I_])

        ##### Picard's quantum move
        p.defgate("P1", U_(P_a1, P_b1))
        p.inst(("P1", 0))

        ##### Q's 2nd stochastic move
        # set the parameters for the random move
        prob = Q_prob2
        # create a dummy gate
        a = np.random.rand()
        b = np.sqrt(1 - np.square(a))
        # draw DESTRUCTION! log
        pygame.draw.rect(screen, (0, 0, 0), (0, dest_y, size_x, dest_width))
        ### Carry out program
        # initialize program
        qvm = api.QVMConnection()
        p = Program()

        ##### Q's 1st stochastic move
        # set the parameters for the random move
        prob = Q_prob1
        # create a dummy gate
        a = np.random.rand()
        b = np.sqrt(1 - np.square(a))
        Uf_ = U_(a, b)
        # perform the random move
        p.defgate("Uf_Q1", Uf_)
        p.inst(("Uf_Q1", 0))
        p.define_noisy_gate(
            "Uf_Q1", [0],
            [np.sqrt(prob) * X_, np.sqrt(1 - prob) * I_])

        ##### Picard's stochastic move
        # set the parameters for the random move
        prob = picard_prob
        # create a dummy gate
        a = np.random.rand()
        b = np.sqrt(1 - np.square(a))
        Uf_ = U_(a, b)
        # perform the random move
        p.defgate("Uf_P", Uf_)
        p.inst(("Uf_P", 0))
Beispiel #26
0
    # populate unitary matrix
    for k, v in d_bb.items():
        unitary_rep += np.kron(
            projection_op(k),
            np.eye(2) + v * (-np.eye(2) + np.array([[0, 1], [1, 0]])))

    return unitary_rep


p = Program()

# pick number of control qubits to be used
n = 5

# Define U_f
p.defgate("U_f", black_box(n, balanced=False))

# Prepare the starting state |0>^(\otimes n) x (1/sqrt[2])*(|0> - |1>)
for n_ in range(1, n + 1):
    p.inst(I(n_))
p.inst(X(0))
p.inst(H(0))

# Apply H^(\otimes n)
for n_ in range(1, n + 1):
    p.inst(H(n_))

# Apply U_f
p.inst(("U_f", ) + tuple(range(n + 1)[::-1]))

# Apply final H^(\otimes n)
Beispiel #27
0
print(qvm.wavefunction(grover_circuit))

# Step 2 of Grover's Algorithm - Define quantum oracle
print("\nStep 2 : Define quantum oracle")
print(printline1)
oracle = np.zeros(shape=(2**N, 2**N))
for b in range(2**N):
    if np.binary_repr(b, N) == queen_position_binary:
        oracle[b, b] = -1
    else:
        oracle[b, b] = 1

print("The corresponding ORACLE used is\n\n")
print(oracle)
ORACLE_GATE_NAME = "GROVER_ORACLE"
grover_circuit.defgate(ORACLE_GATE_NAME, oracle)

# Step 3 of Grover's Algorithm - Define inversion around the mean
# Grover's Diffusion operator : D = 2A - I
print("\nStep 3 : Define inversion around the mean")
print(printline1)
DIFFUSION_GATE_NAME = "DIFFUSION"
diffusion = 2.0 * np.full((2**N, 2**N), 1 / (2**N)) - np.eye(2**N)
print("Corresponding Grover's Diffusion Operator\n\n", diffusion)
grover_circuit.defgate(DIFFUSION_GATE_NAME, diffusion)

# Number of algorithm iterations
N_ITER = int(np.pi / 4 * np.sqrt(2**N))

# O(sqrt(number_of_cards)) : Apply ORACLE and DIFFUSION operator N_ITER times
count = 1
Beispiel #28
0
                                    (0, 0, 0))
        screen.blit(text_rect_Q_x, [size_x - 400, 50])
        text_size_ = font.render("|a|^2: " + str(np.square(Q_a2)), True,
                                 (0, 0, 0))
        screen.blit(text_size_, [size_x - 400, 20])
        # program is now ready to be run
        run_quantum_program = True

    if run_quantum_program:
        ### Carry out program
        # initialize program
        qvm = api.QVMConnection()
        p = Program()

        ##### Q's 1st move
        p.defgate("Q1", U_(Q_a1, Q_b1))
        p.inst(("Q1", 0))

        ##### Picard's 1st move
        p.defgate("P1", U_(P_a1, P_b1))
        p.inst(("P1", 0))

        ##### Q's 2nd move
        p.defgate("Q2", U_(Q_a2, Q_b2))
        p.inst(("Q2", 0))

        ##### Measurement
        p.inst(MEASURE(0, [0]))
        result = qvm.run(p, [0], trials=100)

        result_1s = (len([i for i in result if i == [1]]))
Beispiel #29
0
        text_size_ = font.render("|a|^2: " + str(np.square(a2)), True,
                                 (0, 0, 0))
        screen.blit(text_size_, [size_x - 400, 20])
        # program is now ready to be run
        run_quantum_program = True

    if run_quantum_program:
        # draw DESTRUCTION! log
        pygame.draw.rect(screen, (0, 0, 0), (0, dest_y, size_x, dest_width))
        ### Carry out program
        # initialize program
        qvm = api.QVMConnection()
        p = Program()

        ##### Q's 1st move
        p.defgate("Q1", U_(a1, b1))
        p.inst(("Q1", 0))

        ##### Picard's random move
        # set the parameters for the random move
        prob = picard_prob
        # create a dummy gate
        a = np.random.rand()
        b = np.sqrt(1 - np.square(a))
        Uf_ = U_(a, b)
        # perform the random move
        p.defgate("Uf", Uf_)
        p.inst(("Uf", 0))
        p.define_noisy_gate(
            "Uf", [0],
            [np.sqrt(prob) * X_, np.sqrt(1 - prob) * I_])
Beispiel #30
0
def shor(N):
    # Check if number is even
    if N % 2 == 0:
        print('Even number.')
        return 2

    # Step 1: Chose 1 < a < N uniformly at random
    a = np.random.randint(2, N - 1)
    a = 2
    # Step 2: Compute b = gcd(a,N). If b > 1, output b and stop
    b = gcd(a, N)
    if b > 1:
        print('Factor found by guessing:', b)
        return b

    # Step 3: Find the order r of a modulo N for f(x) = a^x mod N
    # Quantum Part: using approximate periodicity to find r

    m = int(np.ceil(np.log2(N**2)))  # Size of first register
    M = 2**m  # M is the smallest power of 2 greater than N^2
    n = int(np.ceil(
        np.log2(N -
                1)))  # Size of second register - need to represent 0 to N-1

    # Set up connection and program
    qvm = QVMConnection()
    p = Program()
    # Labels for register 1 and 2
    reg_1 = range(m)  # First m qubits
    reg_2 = range(m, m + n)  # Last n qubits
    reg_all = range(m + n)  # Label for both registers

    # Apply QFT to first register
    for i in reg_1:
        p.inst(H(i))

    # Apply the oracle to both registers - need superposition of |x>|f(x)>
    oracle_matrix = bit_oracle(a, N, m, n)
    p.defgate("oracle", oracle_matrix)
    p.inst(("oracle", ) + tuple(reg_all))

    # Measure the second register
    for i in reg_2:
        p.measure(i, i)

    # Apply the qft to the first register
    p.inst(qft(reg_1))

    # Measure the first register
    for i in reg_1:
        p.measure(i, i)

    # Run the approximate peridicity algorithm
    classical_addresses = list(reg_all)
    results = qvm.run(p, classical_addresses, trials=1)

    # Determine output y of algorithm
    y = 0
    for i in reg_1:
        y = y + 2**i * results[0][i]

    # Use continued fraction expansion of z = y/M to find r
    r = Fraction(y, M).limit_denominator(N).denominator

    # If r is odd the algorithm fails
    if r % 2 == 1:
        print('Order r found is odd: algorithm failed')
        return 0

    # Step 4: Find factor of N
    s = gcd(a**(r / 2) - 1, N)
    if s == 1 or s == N:
        print('Factor found is 1 or', N, ': algorithm failed')
        return N

    print('Factor found by Shor\'s algorithm is', s, 'using', m + n, 'qubits')
    return s