How to use the cirq.LineQubit.range function in cirq

To help you get started, we’ve selected a few cirq examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github quantumlib / OpenFermion-Cirq / openfermioncirq / testing / example_classes.py View on Github external
def _generate_qubits(self) -> Sequence[cirq.Qid]:
        return cirq.LineQubit.range(2)
github quantumlib / Cirq / examples / place_on_bristlecone.py View on Github external
def main():
    print("Length 10 line on Bristlecone:")
    line = cirq.google.line_on_device(cirq.google.Bristlecone, length=10)
    print(line)

    print("Initial circuit:")
    n = 10
    depth = 2
    circuit = cirq.Circuit.from_ops(
        cirq.SWAP(cirq.LineQubit(j), cirq.LineQubit(j + 1))
        for i in range(depth)
        for j in range(i % 2, n - 1, 2)
    )
    circuit.append(cirq.measure(*cirq.LineQubit.range(n), key='all'))
    print(circuit)

    print()
    print("Xmon circuit:")
    translated = cirq.google.optimized_for_xmon(
        circuit=circuit,
        new_device=cirq.google.Bristlecone,
        qubit_map=lambda q: line[q.x])
    print(translated)
github JackHidary / quantumcomputingbook / chapter09 / cirq / qpe.py View on Github external
# Print it to the console
print("Unitary:")
print(unitary)

# Diagonalize it classically
evals, evecs = np.linalg.eig(unitary)

# =============================================================================
# Building the circuit for QPE
# =============================================================================

# Number of qubits in the readout/answer register (# bits of precision)
n = 8

# Readout register
regA = cirq.LineQubit.range(n)

# Register for the eigenstate
regB = cirq.LineQubit.range(n, n + m)

# Get a circuit
circ = cirq.Circuit()

# Hadamard all qubits in the readout register
circ.append(cirq.H.on_each(regA))

# Hadamard all qubits in the second register
#circ.append(cirq.H.on_each(regB))

# Get a Cirq gate for the unitary matrix
ugate = cirq.ops.matrix_gates.TwoQubitMatrixGate(unitary)
github JackHidary / quantumcomputingbook / chapter07 / cirq / teleportation-cirq.py View on Github external
def make_quantum_teleportation_circuit(ranX, ranY):
    """Returns a quantum teleportation circuit."""
    circuit = cirq.Circuit()
    msg, alice, bob = cirq.LineQubit.range(3)

    # Creates Bell state to be shared between Alice and Bob
    circuit.append([cirq.H(alice), cirq.CNOT(alice, bob)])

    # Creates a random state for the Message
    circuit.append([cirq.X(msg)**ranX, cirq.Y(msg)**ranY])

    # Bell measurement of the Message and Alice's entangled qubit
    circuit.append([cirq.CNOT(msg, alice), cirq.H(msg)])
    circuit.append(cirq.measure(msg, alice))

    # Uses the two classical bits from the Bell measurement to recover the
    # original quantum Message on Bob's entangled qubit
    circuit.append([cirq.CNOT(alice, bob), cirq.CZ(msg, bob)])

    return msg, circuit
github quantumlib / Cirq / examples / swap_networks.py View on Github external
Returns:
        A circuit implementing a single round of QAOA with the specified
        angles.

    """

    assert all(set(edge) <= set(vertices) for edge in edges)
    assert all(len(edge) == 2 for edge in edges)
    n_vertices = len(vertices)

    # G_{i,j} ∝ exp(i gamma (|01><01| + |10><10|))
    phase_sep_gates = {edge: cirq.ZZ**gamma for edge in edges
                      }  # type: LogicalMapping

    # Physical qubits
    qubits = cirq.LineQubit.range(n_vertices)

    # Mapping from qubits to vertices.
    initial_mapping = {q: i for i, q in enumerate(qubits)
                      }  # type: LogicalMapping

    if use_logical_qubits:
        initial_mapping = {
            q: cirq.LineQubit(i) for q, i in initial_mapping.items()
        }
        phase_sep_gates = {
            tuple(cirq.LineQubit(i)
                  for i in e): g
            for e, g in phase_sep_gates.items()
        }

    phase_sep_circuit = get_phase_sep_circuit(phase_sep_gates, qubits,
github JackHidary / quantumcomputingbook / chapter10-methods / cirq / qpe-simple.py View on Github external
# Diagonalize it classically
evals, _ = np.linalg.eig(unitary)

# =============================================================================
# Building the circuit for QPE
# =============================================================================

# Number of qubits in the readout/answer register (# bits of precision)
n = 2

# Readout register
regA = cirq.LineQubit.range(n)

# Register for the eigenstate
regB = cirq.LineQubit.range(n, n + m)

# Get a circuit
circ = cirq.Circuit()

# Hadamard all qubits in the readout register
circ.append(cirq.H.on_each(regA))

# Get a Cirq gate for the unitary matrix
ugate = cirq.ops.matrix_gates.TwoQubitMatrixGate(unitary)

# Controlled version of the gate
cugate = cirq.ops.ControlledGate(ugate)

# Do the controlled U^{2^k} operations
for k in range(n):
    circ.append(cugate(regA[k], *regB)**(2**k))
github JackHidary / quantumcomputingbook / chapter10 / cirq / qaoa-cirq.py View on Github external
"""Measures the QAOA circuit in the computational basis to get bit strings."""
    circ = qaoa(gammas, betas)
    circ.append(cirq.measure(*[qubit for row in qreg for qubit in row], key='m'))
    
    # Simulate the circuit
    sim = cirq.Simulator()
    res = sim.run(circ, repetitions=nreps)
    
    return res

if __name__ == "__main__":
    # =================================================
    # Make sure the ZZ circuit gives the correct matrix
    # =================================================
    
    qreg = cirq.LineQubit.range(2)
    zzcirc = ZZ(qreg[0], qreg[1], 0.5)
    print("Circuit for ZZ gate:", zzcirc, sep="\n")
    print("\nUnitary of circuit:", zzcirc.to_unitary_matrix().round(2), sep="\n")
    
    # ==========================
    # Grid of qubits for problem
    # ==========================
    
    ncols = 3
    nrows = 3
    nsites = nrows * ncols
    qreg = [[cirq.GridQubit(i,j) for j in range(ncols)] for i in range(nrows)]
    
    # =======================================
    # Do a grid search over many param values
    # =======================================
github quantumlib / Cirq / examples / qaoa.py View on Github external
def main(repetitions=1000, maxiter=50):
    # Set problem parameters
    n = 6
    p = 2

    # Generate a random 3-regular graph on n nodes
    graph = networkx.random_regular_graph(3, n)

    # Make qubits
    qubits = cirq.LineQubit.range(n)

    # Print an example circuit
    betas = np.random.uniform(-np.pi, np.pi, size=p)
    gammas = np.random.uniform(-np.pi, np.pi, size=p)
    circuit = qaoa_max_cut_circuit(qubits, betas, gammas, graph)
    print('Example QAOA circuit:')
    print(circuit.to_text_diagram(transpose=True))

    # Create variables to store the largest cut and cut value found
    largest_cut_found = None
    largest_cut_value_found = 0

    # Initialize simulator
    simulator = cirq.Simulator()

    # Define objective function (we'll use the negative expected cut value)
github quantumlib / Cirq / examples / quantum_teleportation.py View on Github external
def make_quantum_teleportation_circuit(ranX, ranY):
    circuit = cirq.Circuit()
    msg, alice, bob = cirq.LineQubit.range(3)

    # Creates Bell state to be shared between Alice and Bob
    circuit.append([cirq.H(alice), cirq.CNOT(alice, bob)])
    # Creates a random state for the Message
    circuit.append([cirq.X(msg)**ranX, cirq.Y(msg)**ranY])
    # Bell measurement of the Message and Alice's entangled qubit
    circuit.append([cirq.CNOT(msg, alice), cirq.H(msg)])
    circuit.append(cirq.measure(msg, alice))
    # Uses the two classical bits from the Bell measurement to recover the
    # original quantum Message on Bob's entangled qubit
    circuit.append([cirq.CNOT(alice, bob), cirq.CZ(msg, bob)])

    return circuit