### Install Cirq and qsim Source: https://quantumai.google/cirq/simulate/qvm_basic_example Installs the necessary Cirq libraries and the qsimcirq simulator. This is a prerequisite for running the examples. ```python # @title Install `cirq_google` and `qsimcirq` try: import cirq import cirq_google except ImportError: print("installing cirq...") !pip install --quiet cirq-google print("installed cirq.") import cirq import cirq_google try: import qsimcirq except ImportError: print("installing qsimcirq...") !pip install --quiet qsimcirq print(f"installed qsimcirq.") import qsimcirq # Other modules used in this colab import matplotlib.pyplot as plt import time ``` -------------------------------- ### Install Unitary Library and Import Alpha Module Source: https://quantumai.google/cirq/experiments/unitary/unitary/tic_tac_toe Installs the Unitary library from GitHub and imports the alpha module for use in the tutorial. This is the initial setup step. ```python !pip install --quiet git+https://github.com/quantumlib/Unitary@main import unitary.alpha as alpha ``` -------------------------------- ### Install Unitary Library Source: https://quantumai.google/cirq/experiments/quantum_chess/concepts Installs the unitary library if it's not already present. This is a prerequisite for running the Quantum Chess examples. ```python try: import unitary except ImportError: !pip install --quiet git+https://github.com/quantumlib/unitary ``` -------------------------------- ### Setup Cirq and Cirq-Google Libraries Source: https://quantumai.google/cirq/simulate/virtual_engine_interface Installs and imports the necessary Cirq and Cirq-Google libraries. This setup is required before interacting with Cirq's simulation or hardware interfaces. ```python try: import cirq import cirq_google except ImportError: print("installing cirq...") !pip install --quiet cirq print("installed cirq.") import cirq import cirq_google import sympy ``` -------------------------------- ### Setup Cirq and Dependencies Source: https://quantumai.google/cirq/hardware/qubit_picking Imports the necessary Cirq library, Cirq Google extensions, NumPy, and Matplotlib. Includes a check to install Cirq if it's not already present. ```python # @title Setup try: import cirq except ImportError: print("installing cirq...") !pip install --quiet cirq print("installed cirq.") import cirq import cirq_google import numpy as np from matplotlib import pyplot as plt ``` -------------------------------- ### Install Cirq Source: https://quantumai.google/cirq/build/qudits Installs the Cirq library if it is not already present. This is a common setup step for Cirq projects. ```python try: import cirq except ImportError: print("installing cirq...") !pip install --quiet cirq print("installed cirq.") ``` -------------------------------- ### Install Unitary from Source Source: https://quantumai.google/cirq/experiments/unitary/unitary/getting_started Install the Unitary library using pip after cloning the repository and navigating to its directory. ```bash pip install . ``` -------------------------------- ### Install and Import Cirq Source: https://quantumai.google/cirq/start/basics Installs Cirq if not already present and imports the library along with cirq_google. This is a common setup for Cirq projects. ```python try: import cirq except ImportError: print("installing cirq...") !pip install --quiet cirq print("installed cirq.") import cirq import cirq_google ``` -------------------------------- ### Setup Cirq and Dependencies Source: https://quantumai.google/cirq/build/pauli_observables Imports the necessary Cirq library and its Google-specific extensions, along with sympy and numpy. Includes a check to install Cirq if it's not already present. ```python try: import cirq except ImportError: print("installing cirq...") !pip install --quiet cirq print("installed cirq.") import cirq import cirq_google import sympy import numpy as np ``` -------------------------------- ### Install and Import Cirq Source: https://quantumai.google/cirq/build/qubits Ensures Cirq is installed and imported for use in the current environment. This is a common setup step for Cirq projects. ```python try: import cirq except ImportError: print("installing cirq...") !pip install --quiet cirq print("installed cirq.") import cirq ``` -------------------------------- ### Install Quantum Chess Package Source: https://quantumai.google/cirq/experiments/quantum_chess/quantum_chess_rest_api Install the Quantum Chess package from its GitHub repository using pip. The '-q' flag suppresses installation output. ```bash pip install -q git+https://github.com/quantumlib/unitary/ ``` -------------------------------- ### Install Cirq and qsim Source: https://quantumai.google/cirq/simulate/qvm_builder_code Installs the `cirq-google` and `qsimcirq` libraries if they are not already present. This is a prerequisite for using the Quantum Virtual Machine. ```python # @title Install `cirq_google` and `qsimcirq` try: import cirq import cirq_google except ImportError: print("installing cirq...") !pip install --quiet cirq-google print("installed cirq.") import cirq import cirq_google try: import qsimcirq except ImportError: print("installing qsimcirq...") !pip install --quiet qsimcirq print(f"installed qsimcirq.") import qsimcirq import time ``` -------------------------------- ### Install ReCirq Source: https://quantumai.google/cirq/experiments/qcqmc/high_level Installs the recirq library. Use this if the library is not already installed. ```python try: import recirq except ImportError: %pip install git+https://github.com/quantumlib/ReCirq ``` -------------------------------- ### Install Dependencies Source: https://quantumai.google/cirq/experiments/quantum_chess/quantum_chess_client Installs the 'unitary' and 'requests' libraries if they are not already present. This is a prerequisite for running the client. ```python try: import unitary except ImportError: !pip install git+https://github.com/quantumlib/unitary -q try: import requests except ImportError: !pip install requests -q ``` -------------------------------- ### Install Cirq and qsimcirq Source: https://quantumai.google/cirq/simulate/qvm_stabilizer_example Installs the necessary Cirq and qsimcirq libraries. This is required before creating a Quantum Virtual Machine. ```python # @title Install `cirq_google` and `qsimcirq` try: import cirq import cirq_google except ImportError: print("installing cirq...") !pip install --quiet cirq-google print("installed cirq.") import cirq import cirq_google try: import qsimcirq except ImportError: print("installing qsimcirq...") !pip install --quiet qsimcirq print(f"installed qsimcirq.") import qsimcirq # Other modules used in this colab import numpy as np import matplotlib.pyplot as plt import time import random ``` -------------------------------- ### Install Cirq Google and QSimCirq Source: https://quantumai.google/cirq/simulate/quantum_virtual_machine Installs the `cirq_google` and `qsimcirq` libraries if they are not already present. This is a prerequisite for using the quantum virtual machine. ```python # @title Install `cirq_google` and `qsimcirq` try: import cirq import cirq_google except ImportError: print("installing cirq...") !pip install --quiet cirq-google print("installed cirq.") import cirq import cirq_google try: import qsimcirq except ImportError: print("installing qsimcirq...") !pip install --quiet qsimcirq print(f"installed qsimcirq.") import qsimcirq ``` -------------------------------- ### Example Output of Processor Listing Source: https://quantumai.google/cirq/tutorials/google/colab This is an example output demonstrating the format of available processors when listed using `engine.list_processors()`. ```text Successful authentication using project ! Available Processors: [, ] Using processor: rainbow ``` -------------------------------- ### Install Quantum Chess Package Source: https://quantumai.google/cirq/experiments/unitary/quantum_chess/quantum_chess_rest_api Installs the Quantum Chess package from its GitHub repository. Use this command in your terminal or notebook environment. ```bash pip install -q git+https://github.com/quantumlib/unitary. ``` -------------------------------- ### Install Cirq using pip Source: https://quantumai.google/cirq/start/install Use this command to install or upgrade pip and then install the Cirq library. Ensure you have Python 3.11.0 or greater. ```bash python -m pip install --upgrade pip python -m pip install cirq ``` -------------------------------- ### Install ReCirq and OpenFermion-pyscf Source: https://quantumai.google/cirq/experiments/hfvqe/molecular_data Installs the necessary ReCirq and OpenFermion-pyscf packages if they are not already present. Use the quiet flag to suppress installation output. ```python try: import recirq except ImportError: !pip install --quiet git+https://github.com/quantumlib/ReCirq try: import openfermionpyscf except ImportError: !pip install --quiet openfermionpyscf~=0.5.0 ``` -------------------------------- ### Example IonQ Targets Output Source: https://quantumai.google/cirq/hardware/azure-quantum/getting_started_ionq This is an example output showing available IonQ targets, including their average queue time and availability status. ```text [, ``` -------------------------------- ### Example QAOA Cut Size Output Source: https://quantumai.google/cirq/experiments/qaoa/qaoa_maxcut This is an example output showing the cut size achieved by the QAOA algorithm. ```text Cut size: 30.930000000000003 ``` -------------------------------- ### Install Unitary via Pip (Directly from GitHub) Source: https://quantumai.google/cirq/experiments/unitary/unitary/getting_started Install the Unitary library directly from its GitHub repository using pip. It is recommended to do this within a virtual environment. ```bash pip install --quiet git+https://github.com/quantumlib/unitary.git ``` -------------------------------- ### Install Cirq and Cirq-Google Source: https://quantumai.google/cirq/tutorials/google/start Installs the cirq-google and cirq libraries if they are not already present. This is a prerequisite for accessing Google's quantum processors. ```python try: import cirq import cirq_google as cg except ImportError: print("installing cirq-google and cirq...") !pip install --quiet cirq-google cirq print("installed cirq-google and cirq.") import cirq import cirq_google as cg ``` -------------------------------- ### Initialize Local Simulator (Ideal) Source: https://quantumai.google/cirq/hardware/aqt/getting_started Sets up a local AQT simulator for ideal (noise-free) quantum circuit simulations. ```python from cirq.aqt.aqt_sampler import AQTSamplerLocalSimulator aqt_sampler = AQTSamplerLocalSimulator(simulate_ideal=True) ``` -------------------------------- ### Initialize AQT Sampler Source: https://quantumai.google/cirq/hardware/aqt/getting_started Sets up the AQTSampler with your access token, workspace, and resource name to interact with AQT's quantum devices. ```python import cirq from cirq.aqt.aqt_device import get_aqt_device from cirq.aqt.aqt_sampler import AQTSampler access_token = 'MY_TOKEN' ``` -------------------------------- ### Initialize Local Simulator (With Noise) Source: https://quantumai.google/cirq/hardware/aqt/getting_started Sets up a local AQT simulator to simulate quantum circuits with a noise model, estimating real hardware performance. ```python from cirq.aqt.aqt_sampler import AQTSamplerLocalSimulator aqt_sampler = AQTSamplerLocalSimulator(simulate_ideal=False) ``` -------------------------------- ### Initialize and Run a Circuit with PasqalSampler Source: https://quantumai.google/cirq/hardware/pasqal/sampler Demonstrates how to initialize the PasqalSampler with an access token and run a simple quantum circuit. Ensure you replace 'my_token' with your actual PASQAL_API_ACCESS_TOKEN. ```python import cirq from cirq_pasqal import ThreeDQubit, PasqalVirtualDevice, PasqalSampler # A simple sample circuit qubit = ThreeDQubit(0, 0, 0) p_circuit = cirq.Circuit() p_circuit.append(cirq.X(qubit)) # NOT gate. p_circuit.append(cirq.measure(qubit, key='result')) # Measurement. # Create a PasqalSampler object to use. # Replace 'my_token' with the access token and uncomment next lines. PASQAL_API_ACCESS_TOKEN = 'my_token' sampler = PasqalSampler(remote_host='http://34.98.71.118/v0/pasqal', access_token=PASQAL_API_ACCESS_TOKEN) results = sampler.run(p_circuit, repetitions=1000) # Runs the circuit and returns the results in a 'Result' ``` -------------------------------- ### InsertStrategy.NEW_THEN_INLINE Example Source: https://quantumai.google/cirq/build/circuits Demonstrates InsertStrategy.NEW_THEN_INLINE, which starts by creating a new moment and then uses the INLINE strategy for subsequent operations. ```python circuit = cirq.Circuit() circuit.append([cirq.H(q0)]) circuit.append([cirq.CZ(q1, q2), cirq.H(q0)], strategy=InsertStrategy.NEW_THEN_INLINE) print(circuit) ``` -------------------------------- ### Example: Executing Shor's Algorithm and Post-processing Source: https://quantumai.google/cirq/experiments/shor This example demonstrates how to create an order finding circuit, execute it, and then use the `process_measurement` function to find the order 'r'. Note that the quantum part of the algorithm has a probability of success, so re-running may be necessary. ```python """Example of the classical post-processing.""" # Set n and x here n = 6 x = 5 print(f"Finding the order of x = {x} modulo n = {n}\n") measurement = cirq.sample(circuit, repetitions=1) print("Raw measurements:") print(measurement) print("\nInteger in exponent register:") print(measurement.data) r = process_measurement(measurement, x, n) print("\nOrder r =", r) if r is not None: print(f"x^r mod n = {x}^{r} mod {n} = {x**r % n}") ``` -------------------------------- ### Get Benchmark Configuration by Name Source: https://quantumai.google/cirq/experiments/ftbbl Retrieve a specific benchmark configuration using its full name. This is useful for selecting a particular setup for execution or analysis. ```python config = algo.get_config_by_full_name('loschmidt.tilted_square_lattice.small-cz-v1') print(config.description) ``` -------------------------------- ### Create AQT Sampler Instance Source: https://quantumai.google/cirq/hardware/aqt/getting_started Instantiates an AQTSampler for a specific workspace and resource, using your provided access token. ```python workspace = 'WORKSPACE_NAME' resource = 'RESOURCE_NAME' aqt_sampler = AQTSampler(workspace=workspace, resource=resource, access_token=access_token) ``` -------------------------------- ### Initialize PasqalVirtualDevice Source: https://quantumai.google/cirq/hardware/pasqal/devices Shows how to initialize a PasqalVirtualDevice with a specified control radius and a predefined set of qubits. The control radius influences qubit connectivity. ```python from cirq_pasqal import PasqalVirtualDevice # A PasqalVirtualDevice with a control radius of 2.0 times the lattice spacing. p_device = PasqalVirtualDevice(control_radius=2.0, qubits=p_qubits) ``` -------------------------------- ### Set up Sampler (Simulator or Device) Source: https://quantumai.google/cirq/noise/qcvv/isolated_xeb Configures a sampler for noisy simulations using `cirq.DensityMatrixSimulator` or retrieves a sampler for a real device via `cirq_google`. For real devices, it also sets up device information and routing graphs. ```python device_name = None # change me! if device_name is None: sampler = cirq.DensityMatrixSimulator(noise=cirq.depolarize(5e-3)) else: import cirq_google as cg sampler = cg.get_engine_sampler(device_name, gate_set_name='sqrt_iswap') device = cg.get_engine_device(device_name) import cirq.contrib.routing as ccr graph = ccr.gridqubits_to_graph_device(device.qubits) pos = {q: (q.row, q.col) for q in graph.nodes} import networkx as nx nx.draw_networkx(graph, pos=pos) ``` -------------------------------- ### Install Cirq Contrib Dependencies Source: https://quantumai.google/cirq/start/install Install optional dependencies for features within cirq.contrib. This command installs the cirq-core package with the 'contrib' extra. ```bash python -m pip install 'cirq-core[contrib]' ``` -------------------------------- ### Create and Visualize a Simple Circuit Source: https://quantumai.google/cirq/experiments/benchmarks/rabi_oscillations Builds a quantum circuit with an RX gate and a measurement, then visualizes it using SVGCircuit. Ensure numpy is imported as np. ```python from cirq.contrib.svg import SVGCircuit # Create a circuit with X, Ry(pi/2) and H. my_circuit = cirq.Circuit( # Rotate the qubit pi/2 radians around the X axis. cirq.rx(np.pi / 2).on(my_qubit), # Measure the qubit. cirq.measure(my_qubit, key="out"), ) SVGCircuit(my_circuit) ``` -------------------------------- ### Install System Dependencies Source: https://quantumai.google/cirq/dev/development Installs system dependencies required for Cirq development using apt. Ensure Python 3.11 or greater is installed. ```bash cat apt-system-requirements.txt dev_tools/conf/apt-list-dev-tools.txt | xargs sudo apt-get install --yes ``` -------------------------------- ### Create a Device-Ready Circuit Source: https://quantumai.google/cirq/simulate/qvm_builder_code Prepare a circuit tailored for a specific quantum device. This example demonstrates creating a circuit with a Hadamard gate and a measurement on a specific qubit. ```python # create your device ready circuit here! q0 = cirq.GridQubit(6, 3) your_circuit = cirq.Circuit([(cirq.X**0.5)(q0), cirq.measure(q0)]) print(your_circuit) ``` ```text (6, 3): ───X^0.5───M─── ``` -------------------------------- ### Install Cirq contrib dependencies Source: https://quantumai.google/cirq/start/install Install optional dependencies for features within `cirq.contrib`. This command installs the core Cirq library along with the contrib extras. ```bash python -m pip install 'cirq-core[contrib]' ``` -------------------------------- ### Install ReCirq and Cirq Source: https://quantumai.google/cirq/experiments/time_crystals/time_crystal_circuit_generation Installs the necessary libraries, Cirq and ReCirq, for time crystal circuit generation. Includes a fallback to install ReCirq from GitHub if it's not found. ```python !pip install cirq --quiet try: import recirq except ImportError: !pip install --quiet git+https://github.com/quantumlib/ReCirq ``` -------------------------------- ### Editable Installs for Cirq Modules Source: https://quantumai.google/cirq/dev/development Install Cirq modules in an editable fashion to pick up code changes immediately. Ensure you install each module separately for effective development. ```bash pip install -e ./cirq-core -e ./cirq-google -e ./cirq-ionq -e ./cirq-aqt ``` -------------------------------- ### Initialize Quantum Chess Board Source: https://quantumai.google/cirq/experiments/quantum_chess/quantum_chess_client Initializes a quantum chess board with the starting occupancy state using bitboard representation. The server should be running and accessible via the provided ngrok URL. ```APIDOC ## POST /quantumboard/init ### Description Initializes a quantum chess board with the starting occupancy state of all pieces. The initial positions are given by the hex 0xFFFF00000000FFFF, occupying ranks 1, 2, 7, and 8. ### Method POST ### Endpoint /quantumboard/init ### Request Body - **init_basis_state** (hex) - Required - The initial state of the board represented as a hexadecimal bitboard. ### Request Example ```json { "init_basis_state": "0xFFFF00000000FFFF" } ``` ### Response #### Success Response (200) - **probabilities** (list of floats) - A list representing the probabilities of each state. - **empty** (integer) - The number of empty squares. - **full** (integer) - The number of occupied squares. #### Response Example ```json { "probabilities": [1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0], "empty": 281474976645120, "full": 18446462598732906495 } ``` ``` -------------------------------- ### Example Counter Output Source: https://quantumai.google/cirq/start/basics This is an example of the output format for the Counter object when using samples.histogram(). ```python Counter({0: 533, 3: 467}) ``` -------------------------------- ### Create Quantum Virtual Machine Source: https://quantumai.google/cirq/simulate/qvm_stabilizer_example Creates a Quantum Virtual Machine using a specified processor ID and the QSimSimulator. It prints the qubit grid of the chosen processor. ```python # @title Create Quantum Virtual Machine: Choose a processor ("willow_pink", "rainbow" or "weber") # (see cirq_google.engine.list_virtual_processors() for available names) processor_id = "willow_pink" # @param {type:"string"} # Instantiate the engine. sim_engine = cirq_google.engine.create_default_noisy_quantum_virtual_machine( processor_id=processor_id, simulator_class=qsimcirq.QSimSimulator ) print( "Your quantum virtual machine", processor_id, "is ready, here is the qubit grid:", "\n========================\n", ) print(sim_engine.get_processor(processor_id).get_device()) ``` -------------------------------- ### Example Kraus Operators Output Source: https://quantumai.google/cirq/build/operators An example output showing the Kraus operators for a depolarizing channel. ```text Kraus operators of depolarize(p=0.01) are: [[0.99 0. ] [0. 0.99]] [[0. +0.j 0.06+0.j] [0.06+0.j 0. +0.j]] [[0.+0.j 0.-0.06j] [0.+0.06j 0.+0.j ]] [[ 0.06+0.j 0. +0.j] [ 0. +0.j -0.06+0.j]] ``` -------------------------------- ### Install and Import Cirq Source: https://quantumai.google/cirq/hardware/ionq/getting_started Installs Cirq if not already present and imports it. Requires Cirq version >0.9. ```python try: import cirq version = cirq.__version__.split(".") assert int(version[0]) > 0 or int(version[1]) > 9, "Cirq version >0.9 required" except (ImportError, AssertionError): print("Installing Cirq...") !pip install --quiet cirq print("Cirq installed.") ``` -------------------------------- ### PasqalSampler Initialization and Circuit Execution Source: https://quantumai.google/cirq/hardware/pasqal/sampler Demonstrates how to initialize the PasqalSampler with an access token and execute a simple quantum circuit. Note that the Pasqal API is not yet publicly available. ```APIDOC ## PasqalSampler Class The `PasqalSampler` class is the entry point to communicate with the API. It can be initialized using your PASQAL_API_ACCESS_TOKEN. ### Initialization ```python import cirq from cirq_pasqal import PasqalSampler PASQAL_API_ACCESS_TOKEN = 'my_token' # Replace with your actual token sampler = PasqalSampler(remote_host='http://34.98.71.118/v0/pasqal', access_token=PASQAL_API_ACCESS_TOKEN) ``` ### Circuit Execution ```python # A simple sample circuit qubit = cirq.LineQubit(0) p_circuit = cirq.Circuit() p_circuit.append(cirq.X(qubit)) # NOT gate. p_circuit.append(cirq.measure(qubit, key='result')) # Measurement. results = sampler.run(p_circuit, repetitions=1000) # Runs the circuit and returns the results ``` **Note:** The Pasqal API is not yet open for public access. Please contact Pasqal if you are interested. ``` -------------------------------- ### Example Measurement Results Source: https://quantumai.google/cirq/tutorials/google/colab This is an example output of measurement results from running a Cirq circuit in Google Colab. ```text Success! Results: 1110110001100001011110100000010010110001101111011110101000010011001110010111010001001101100000111101100110101111010010011000010100011111111000010011010000100001001111111011000001100011001000000111011011110011011000001110101100011110010011011010111101100010001110100111100110110100111100011011111110110100101111011000000011000110110011100000100101000110101000100111001010100010101110011010111011010010100110111011011110110011000110110100110000101101011110001011111000110000001100100111011000111010000001011001001010001101110001101111100011110000110010101111100010110001010011101100111110111111111001010011111100110010010111101010111111110110100111111110000001011001111010100101000110101000101011010111111101100001010011111011011000010001111111001000110101010001011011111001010110101011001110101110010101110100101001100010010011101100011000001111110001000011100000100011011111000010110100000011010100111001010101111100011001111111011111011010000010101000111111101001111011111111001101111000001101101 ``` -------------------------------- ### Example Post-Selection Output Source: https://quantumai.google/cirq/experiments/quantum_chess/concepts An example of the output from the `histogram_post_select` function, showing the frequency of measurements for each square after post-selection. ```json { 'a1': np.int64(0), 'a2': np.int64(0), 'a3': np.int64(0), 'b1': np.int64(0), 'b2': np.int64(503), 'b3': np.int64(0), 'c1': np.int64(246), 'c2': np.int64(257), 'c3': np.int64(0) } ``` -------------------------------- ### Instantiate and Use HardcodedQubitPlacer Source: https://quantumai.google/cirq/google/qubit-placement Demonstrates how to create a HardcodedQubitPlacer with a pre-generated mapping and then use it to place a circuit. It also shows how to visualize the resulting placement. ```python rainbow_mapping = all_offset_placements(rainbow_graph) hardcoded = HardcodedQubitPlacer(mapping=rainbow_mapping) placed_c, placement = hardcoded.place_circuit( circuit, problem_topology=topo, shared_rt_info=shared_rt_info, rs=rs ) cirq.draw_placements(rainbow_graph, circuit_graph, [placement]) ``` -------------------------------- ### Install and Import Cirq Source: https://quantumai.google/cirq/gatezoo Installs Cirq if not already present and imports necessary libraries for gate manipulation and display. ```python try: import cirq except ImportError: print("installing cirq...") !pip install --quiet cirq print("installed cirq.") import IPython.display as ipd import cirq import inspect ``` -------------------------------- ### Install ReCirq Package Source: https://quantumai.google/cirq/experiments/qaoa/example_problems Installs the ReCirq package if it's not already available. This is a prerequisite for using ReCirq functionalities. ```python try: import recirq except ImportError: !pip install git+https://github.com/quantumlib/ReCirq ``` -------------------------------- ### Sample from a Parameterized Circuit with sample Source: https://quantumai.google/cirq/start/intro The sample method provides a pandas DataFrame of results from simulating a parameterized circuit with multiple parameter configurations. Each column represents a parameter or measurement. ```python results = simulator.sample(program=circuit, params=resolvers, repetitions=10) results.describe() ``` -------------------------------- ### Install ReCirq Library Source: https://quantumai.google/cirq/experiments/fermi_hubbard/publication_results Installs the ReCirq library if it's not already present. This is a prerequisite for running the Fermi-Hubbard experiments. ```python try: import recirq except ImportError: print("Installing ReCirq...") !pip install git+https://github.com/quantumlib/recirq --quiet print("Installed ReCirq!") ``` -------------------------------- ### Set up Virtual Engine with Noisy Simulator Source: https://quantumai.google/cirq/simulate/quantum_virtual_machine Packages the noisy simulator and device into a quantum virtual engine. This ensures the virtual processor interface matches that of a real quantum processor, enabling consistent workflow. ```python # Package the simulator and device in an Engine. # The device object device = cirq_google.engine.create_device_from_processor_id(processor_id) # Load the median device noise calibration for your processor. cal = cirq_google.engine.load_median_device_calibration(processor_id) # The simulated processor object sim_processor = cirq_google.engine.SimulatedLocalProcessor( processor_id=processor_id, sampler=sim, device=device, calibrations={cal.timestamp // 1000: cal} ) # The virtual engine sim_engine = cirq_google.engine.SimulatedLocalEngine([sim_processor]) print( "Your quantum virtual machine", processor_id, "is ready, here is the qubit grid:", "\n========================\n", ) print(sim_engine.get_processor(processor_id).get_device()) ``` -------------------------------- ### Example output of measure_observables Source: https://quantumai.google/cirq/build/pauli_observables This is an example of the output format from the `measure_observables` function, showing the observable, its estimated mean, and its variance. ```text Z(q(0))*Z(q(1)) 1.0 0.0 (4+0j)*X(q(0)) -0.24 0.16103434343434342 ``` -------------------------------- ### Install and Import Cirq and Dependencies Source: https://quantumai.google/cirq/experiments/fourier_checking Installs Cirq if not already present and imports necessary libraries like numpy, matplotlib, and pandas for the tutorial. Sets a random seed for reproducible results. ```python # Initial setup to install Cirq and set up dependencies for the tutorial. try: import cirq except: print("installing cirq...") !pip install --quiet cirq print("installed cirq.") import cirq from typing import Sequence import numpy as np import matplotlib.pyplot as plt import pandas as pd # Sets a seed for deterministic results. Uncomment for random results each run. np.random.seed(2021) np.set_printoptions(precision=3, suppress=True, linewidth=200) ``` -------------------------------- ### Install ReCirq Package Source: https://quantumai.google/cirq/experiments/guide/data_analysis Install the ReCirq package if it's not already present. This is a prerequisite for using the data analysis utilities. ```python try: import recirq except ImportError: !pip install --quiet git+https://github.com/quantumlib/ReCirq ``` -------------------------------- ### Example Random Cut Size Output Source: https://quantumai.google/cirq/experiments/qaoa/qaoa_maxcut This is an example output showing the cut size achieved by the random guessing method. ```text Cut size: 30.030000000000005 ``` -------------------------------- ### Set up HF-VQE experiment Source: https://quantumai.google/cirq/experiments/hfvqe/quickstart Generates molecular data, sets up quantum resources (qubits and sampler), and initializes the OpdmFunctional for measurements and optimization. ```python rhf_objective, molecule, parameters, obi, tbi = make_h6_1_3() ansatz, energy, gradient = rhf_func_generator(rhf_objective) # settings for quantum resources qubits = [cirq.GridQubit(0, x) for x in range(molecule.n_orbitals)] sampler = cirq.Simulator(dtype=np.complex128) # this can be a QuantumEngine # OpdmFunctional contains an interface for running experiments opdm_func = OpdmFunctional(qubits=qubits, sampler=sampler, constant=molecule.nuclear_repulsion, one_body_integrals=obi, two_body_integrals=tbi, # only simulate spin-up electrons: num_electrons=molecule.n_electrons // 2, clean_xxyy=True, purification=True ) ``` -------------------------------- ### Build Blueprint and Simulated Experiment Source: https://quantumai.google/cirq/experiments/qcqmc/full_workflow Construct a blueprint for the trial wavefunction and set up a simulated experiment using a statevector simulator. This involves defining parameters for the blueprint and the simulation, including noise models and sampling strategies. ```python from recirq.qcqmc.blueprint import BlueprintParamsTrialWf, BlueprintData from recirq.qcqmc.experiment import SimulatedExperimentParams, ExperimentData blueprint_params = BlueprintParamsTrialWf( name="blueprint_test_medium", trial_wf_params=pp_params, n_cliffords=100, qubit_partition=(tuple(qubit for qubit in pp_params.qubits_jordan_wigner_ordered),), seed=1, ) blueprint = BlueprintData.build_blueprint_from_dependencies(blueprint_params, dependencies={pp_params: trial_wf}) simulated_experiment_params = SimulatedExperimentParams( name="test_1", blueprint_params=blueprint.params, noise_model_name="None", noise_model_params=(0,), n_samples_per_clifford=31, seed=1, ) experiment = ExperimentData.build_experiment_from_dependencies( params=simulated_experiment_params, dependencies={blueprint.params: blueprint} ) ``` -------------------------------- ### Example Output: DataFrame Length Source: https://quantumai.google/cirq/experiments/guide/data_analysis This is an example output showing the length of the prepared DataFrame, indicating the number of qubits to be processed. ```text 5 ```