### Execute Quantum Circuit with Qibo Source: https://context7.com/qiboteam/qibojit/llms.txt Demonstrates executing a quantum circuit using the MetaBackend. It shows how to obtain the final state vector without measurements and how to perform measurements to get frequencies and samples. Requires qibo and numpy libraries. ```python from qibojit.backends import MetaBackend from qibo import Circuit, gates import numpy as np backend = MetaBackend.load(platform="numba") # Build a variational circuit def create_variational_circuit(nqubits, params): circuit = Circuit(nqubits) idx = 0 for layer in range(2): for q in range(nqubits): circuit.add(gates.RY(q, theta=params[idx])) idx += 1 circuit.add(gates.RZ(q, theta=params[idx])) idx += 1 for q in range(nqubits - 1): circuit.add(gates.CNOT(q, q + 1)) return circuit # Create circuit with random parameters nqubits = 4 params = np.random.random(nqubits * 2 * 2) * 2 * np.pi circuit = create_variational_circuit(nqubits, params) # Execute without measurements - get state vector result = backend.execute_circuit(circuit) final_state = result.state() print(f"Final state norm: {np.linalg.norm(backend.to_numpy(final_state)):.6f}") # Execute with measurements circuit.add(gates.M(*range(nqubits))) result_measured = backend.execute_circuit(circuit, nshots=10000) # Access results print(f"Frequencies: {result_measured.frequencies()}") print(f"Samples shape: {result_measured.samples().shape}") ``` -------------------------------- ### List Available Qibo JIT Backends Source: https://context7.com/qiboteam/qibojit/llms.txt Returns a dictionary indicating which qibojit backends are available on the current system based on installed dependencies and hardware. This is useful for conditionally loading a backend. ```python from qibojit.backends import MetaBackend # Check available backends meta = MetaBackend() available = meta.list_available() print(available) # Output: {'numba': True, 'cupy': False, 'cuquantum': False} # Conditionally load GPU backend if available.get('cupy'): backend = MetaBackend.load(platform='cupy') else: backend = MetaBackend.load(platform='numba') ``` -------------------------------- ### GET /backend/matrices Source: https://context7.com/qiboteam/qibojit/llms.txt Retrieves optimized matrix representations for standard and parameterized quantum gates. ```APIDOC ## GET /backend/matrices ### Description Fetches precomputed matrix representations for gates like Pauli X, Y, Z, Hadamard, and parameterized gates like RX, RY, RZ. ### Method GET ### Endpoint /backend/matrices ### Parameters #### Query Parameters - **dtype** (string) - Optional - Data type for the matrices (e.g., 'complex128'). ### Request Example GET /backend/matrices?dtype=complex128 ### Response #### Success Response (200) - **matrices** (object) - A collection of gate matrices. #### Response Example { "X": [[0, 1], [1, 0]], "H": [[0.707, 0.707], [0.707, -0.707]] } ``` -------------------------------- ### NVIDIA cuQuantum Acceleration with CuQuantumBackend Source: https://context7.com/qiboteam/qibojit/llms.txt Leverages NVIDIA's cuQuantum SDK for optimized quantum gate operations, providing the highest performance for GPU-based quantum simulation. This backend requires the cuQuantum SDK to be installed and only supports complex numerical types. ```python from qibojit.backends import MetaBackend from qibo import Circuit, gates # Load cuQuantum backend (requires cuQuantum SDK) backend = MetaBackend.load(platform="cuquantum") # cuQuantum only supports complex types backend.set_dtype("complex128") # Create a deep circuit circuit = Circuit(5) for layer in range(10): for q in range(5): circuit.add(gates.RY(q, theta=0.1 * layer)) for q in range(4): circuit.add(gates.CNOT(q, q + 1)) ``` -------------------------------- ### Convert Data Types with cast Source: https://context7.com/qiboteam/qibojit/llms.txt Provides examples of converting NumPy arrays and SciPy sparse matrices into backend-native tensors, including handling dtypes and memory copying. ```python from qibojit.backends import MetaBackend import numpy as np backend = MetaBackend.load(platform="numba") backend_array = backend.cast(np.array([1+0j, 0, 0, 0])) complex_array = backend.cast(np.random.random(10), dtype="complex128") backend_sparse = backend.cast(sparse_matrix) ``` -------------------------------- ### Initialize Quantum States with zero_state Source: https://context7.com/qiboteam/qibojit/llms.txt Shows how to create initial quantum states, including state vectors and density matrices, with configurable qubit counts and data types. ```python from qibojit.backends import MetaBackend backend = MetaBackend.load(platform="numba") state = backend.zero_state(nqubits=4) dm = backend.zero_state(nqubits=3, density_matrix=True) state_f32 = backend.zero_state(nqubits=5, dtype="complex64") ``` -------------------------------- ### POST /backend/execute_circuit Source: https://context7.com/qiboteam/qibojit/llms.txt Executes a full quantum circuit simulation using the JIT backend. ```APIDOC ## POST /backend/execute_circuit ### Description Runs a complete quantum circuit simulation, returning measurement frequencies or final state. ### Method POST ### Endpoint /backend/execute_circuit ### Parameters #### Request Body - **circuit** (object) - Required - The circuit definition. - **nshots** (integer) - Optional - Number of shots for sampling. ### Request Example { "circuit": {"gates": [...]}, "nshots": 1000 } ### Response #### Success Response (200) - **frequencies** (object) - Measurement outcomes and counts. #### Response Example { "frequencies": {"00": 500, "11": 500} } ``` -------------------------------- ### Load Qibo JIT Backend Source: https://context7.com/qiboteam/qibojit/llms.txt Loads the appropriate qibojit backend based on the specified platform (CPU or GPU). This is the primary entry point for obtaining a backend instance for JIT-accelerated quantum circuit execution. It can auto-detect the best available backend. ```python from qibojit.backends import MetaBackend # Load specific backend by platform name numba_backend = MetaBackend.load(platform="numba") # CPU backend with Numba JIT cupy_backend = MetaBackend.load(platform="cupy") # GPU backend with CuPy cuquantum_backend = MetaBackend.load(platform="cuquantum") # GPU backend with cuQuantum # Auto-detect best available backend (prefers GPU if available) backend = MetaBackend.load() # Check backend properties print(f"Backend: {backend.name}, Platform: {backend.platform}") print(f"Device: {backend.device}") print(f"Versions: {backend.versions}") ``` -------------------------------- ### Execute Circuits and Measure Outcomes Source: https://context7.com/qiboteam/qibojit/llms.txt Demonstrates how to add measurements to a quantum circuit, execute it using the backend, and extract frequency counts from the results. ```python circuit.add(gates.M(*range(5))) result = backend.execute_circuit(circuit, nshots=10000) frequencies = result.frequencies() most_common = max(frequencies, key=frequencies.get) print(f"Most common outcome: {most_common} ({frequencies[most_common]} times)") ``` -------------------------------- ### Density Matrix Simulation with Qibo JIT Source: https://context7.com/qiboteam/qibojit/llms.txt Performs quantum circuit simulations using density matrices to model mixed states and noise. Includes applying gates, noise channels, and executing circuits with measurement. ```python from qibojit.backends import MetaBackend from qibo import Circuit, gates from qibo.quantum_info import random_density_matrix import numpy as np backend = MetaBackend.load(platform="numba") nqubits = 3 # Create random density matrix rho = random_density_matrix(2**nqubits, backend=backend) print(f"Initial trace: {backend.trace(rho):.6f}") print(f"Initial purity: {backend.trace(rho @ rho).real:.6f}") # Apply gates to density matrix h_gate = gates.H(0) rho = backend.apply_gate(h_gate, rho, nqubits) cnot = gates.CNOT(0, 1) rho = backend.apply_gate(cnot, rho, nqubits) # Apply noise channel from qibo.gates import UnitaryChannel x_matrix = gates.X(0).matrix(backend) noise_channel = UnitaryChannel( [(0,)], [(0.1, x_matrix)] # 10% bit flip probability ) rho = backend.apply_channel(noise_channel, rho, nqubits) print(f"After noise - trace: {backend.trace(rho):.6f}") print(f"After noise - purity: {backend.trace(rho @ rho).real:.6f}") # Execute circuit with density matrix circuit = Circuit(nqubits, density_matrix=True) circuit.add(gates.H(0)) circuit.add(gates.CNOT(0, 1)) circuit.add(gates.DepolarizingChannel(0, lam=0.1)) circuit.add(gates.M(0, 1, 2)) result = backend.execute_circuit(circuit, nshots=10000) print(f"Measurement frequencies: {result.frequencies()}") ``` -------------------------------- ### Custom Gate Matrices with Qibo JIT Source: https://context7.com/qiboteam/qibojit/llms.txt Generates optimized matrix representations for standard and parameterized quantum gates using the CustomMatrices class. Supports various gates like Pauli, RX, RY, RZ, U1, fSim, and GeneralizedfSim. ```python from qibojit.backends.matrices import CustomMatrices import numpy as np # Create custom matrices with specific precision matrices = CustomMatrices(dtype="complex128") # Access standard gate matrices print("Pauli X:", matrices.X) print("Pauli Y:", matrices.Y) print("Pauli Z:", matrices.Z) print("Hadamard:", matrices.H) # Parameterized gates theta = np.pi / 4 rx = matrices.RX(theta) ry = matrices.RY(theta) rz = matrices.RZ(theta) print(f"RX({theta:.4f}):\n{rx}") # U1 gate (returns scalar for efficiency) u1_phase = matrices.U1(theta) print(f"U1 phase factor: {u1_phase}") # fSim gate (special 5-element representation) fsim = matrices.fSim(theta=0.5, phi=0.3) print(f"fSim parameters: {fsim}") # Generalized fSim with custom unitary u = np.array([[np.cos(0.1), -np.sin(0.1)], [np.sin(0.1), np.cos(0.1)]], dtype=np.complex128) gfsim = matrices.GeneralizedfSim(u, phi=0.2) print(f"Generalized fSim: {gfsim}") ``` -------------------------------- ### Linear Algebra Operations with Qibo JIT Backends Source: https://context7.com/qiboteam/qibojit/llms.txt Provides optimized linear algebra functions for quantum computing, including matrix exponentiation, eigenvalue decomposition, and sparse matrix operations. ```python from qibojit.backends import MetaBackend from scipy import sparse import numpy as np backend = MetaBackend.load(platform="numba") # Matrix exponentiation (for time evolution) H = np.array([[1, 0.5], [0.5, -1]], dtype=np.complex128) H = backend.cast(H) exp_H = backend.expm(-1j * 0.1 * H) # e^{-iHt} print(f"Unitary evolution operator:\n{backend.to_numpy(exp_H)}") # Eigenvalue decomposition eigenvalues, eigenvectors = backend.eigenvectors(H) print(f"Eigenvalues: {backend.to_numpy(eigenvalues)}") # Sparse matrix operations sparse_H = sparse.random(64, 64, density=0.1, format='csr') sparse_H = sparse_H + sparse_H.T # Make Hermitian sparse_H = backend.cast(sparse_H) # Sparse eigenvalue computation (k smallest) eigvals, eigvecs = backend.eigenvectors(sparse_H, k=6) print(f"6 smallest eigenvalues: {backend.to_numpy(eigvals)}") # Fractional matrix power matrix = np.random.random((4, 4)) + np.eye(4) matrix = backend.cast(matrix, dtype="complex128") sqrt_matrix = backend.matrix_power(matrix, 0.5) print(f"Matrix square root computed") ``` -------------------------------- ### CPU Quantum Simulation with NumbaBackend Source: https://context7.com/qiboteam/qibojit/llms.txt Provides JIT-compiled parallel CPU execution for quantum circuit simulation using Numba. It automatically utilizes all available CPU cores for state vector operations and allows configuration of threading, numerical precision, and random seed. ```python from qibojit.backends import MetaBackend from qibo import Circuit, gates import numpy as np # Load Numba backend backend = MetaBackend.load(platform="numba") # Configure threading backend.set_threads(4) # Use 4 CPU threads print(f"Using {backend.nthreads} threads") # Set numerical precision backend.set_dtype("complex128") # or "complex64" for single precision # Set random seed for reproducibility backend.set_seed(42) # Create and execute a quantum circuit circuit = Circuit(3) circuit.add(gates.H(0)) circuit.add(gates.CNOT(0, 1)) circuit.add(gates.CNOT(1, 2)) circuit.add(gates.M(0, 1, 2)) # Execute circuit result = backend.execute_circuit(circuit, nshots=1000) print(f"Measurement frequencies: {result.frequencies()}") # Output: {'000': 512, '111': 488} ``` -------------------------------- ### Apply Quantum Gates with apply_gate Source: https://context7.com/qiboteam/qibojit/llms.txt Illustrates the application of various quantum gates (single-qubit, multi-qubit, and custom unitaries) to a state vector or density matrix. ```python from qibojit.backends import MetaBackend from qibo import gates import numpy as np backend = MetaBackend.load(platform="numba") state = backend.apply_gate(gates.H(0), state, nqubits) state = backend.apply_gate(gates.CNOT(0, 1), state, nqubits) custom_gate = gates.Unitary(np.array([[1, 0], [0, 1j]]), 3) state = backend.apply_gate(custom_gate, state, nqubits) ``` -------------------------------- ### Distributed Circuit Execution on GPUs Source: https://context7.com/qiboteam/qibojit/llms.txt Shows how to execute quantum circuits across multiple GPUs using the CupyBackend for simulating larger quantum systems. It requires a backend with multi-GPU support and demonstrates creating a circuit that benefits from distributed execution. ```python from qibojit.backends import MetaBackend from qibo import Circuit, gates from qibo.models import QFT # Load GPU backend with multi-GPU support backend = MetaBackend.load(platform="cupy") if backend.ngpus > 1: # Create a large circuit that benefits from distribution nqubits = 20 circuit = Circuit(nqubits, accelerators={"/GPU:0": 2, "/GPU:1": 2}) # Add QFT-like operations for q in range(nqubits): circuit.add(gates.H(q)) for j in range(q + 1, nqubits): circuit.add(gates.CU1(q, j, theta=np.pi / (2 ** (j - q)))) # Execute across GPUs result = backend.execute_distributed_circuit(circuit, nshots=1000) print(f"Distributed execution completed") print(f"State vector size: {2**nqubits} amplitudes") ``` -------------------------------- ### POST /backend/execute_distributed_circuit Source: https://context7.com/qiboteam/qibojit/llms.txt Executes quantum circuits across multiple GPUs for simulating larger quantum systems that exceed single GPU memory. ```APIDOC ## POST /backend/execute_distributed_circuit ### Description Distributes the simulation of a quantum circuit across multiple GPU devices. ### Method POST ### Endpoint /backend/execute_distributed_circuit ### Parameters #### Request Body - **circuit** (Circuit) - Required - The circuit configured with accelerators. - **nshots** (int) - Optional - Number of shots for sampling. ### Request Example { "circuit": "", "nshots": 1000 } ### Response #### Success Response (200) - **result** (Result) - Distributed execution result object. ``` -------------------------------- ### Numba JIT Gate Kernels for Quantum Operations Source: https://context7.com/qiboteam/qibojit/llms.txt Utilizes optimized Numba JIT kernels from `qibojit.custom_operators` for direct manipulation of quantum state vectors. This includes initializing a state vector and applying gates like X and Hadamard using low-level kernel functions. ```python from qibojit.custom_operators import gates as jit_gates from qibojit.custom_operators import ops as jit_ops import numpy as np # Initialize a state vector directly nqubits = 3 state = np.zeros(2**nqubits, dtype=np.complex128) state = jit_ops.initial_state_vector(state) print(f"Initial state |000>: {state[0]}") # Apply X gate kernel directly nstates = 2**(nqubits - 1) m = nqubits - 1 - 0 # Target qubit 0 gate_matrix = np.array([[0, 1], [1, 0]], dtype=np.complex128) state = jit_gates.apply_x_kernel(state, gate_matrix, nstates, m) print(f"After X on qubit 0: {state}") # Should be |001> # Apply Hadamard using general gate kernel h_matrix = np.array([[1, 1], [1, -1]], dtype=np.complex128) / np.sqrt(2) m = nqubits - 1 - 1 # Target qubit 1 state = jit_gates.apply_gate_kernel(state, h_matrix, nstates, m) ``` -------------------------------- ### GPU Quantum Simulation with CupyBackend Source: https://context7.com/qiboteam/qibojit/llms.txt Provides GPU-accelerated quantum circuit simulation using CuPy with custom CUDA kernels. It supports multi-GPU execution for large quantum systems and allows setting the specific GPU device and converting GPU arrays to NumPy. ```python from qibojit.backends import MetaBackend from qibo import Circuit, gates import numpy as np # Load CuPy GPU backend backend = MetaBackend.load(platform="cupy") # Check GPU availability print(f"Number of GPUs: {backend.ngpus}") print(f"Device: {backend.device}") # Set specific GPU device backend.set_device("/GPU:0") # Create a parameterized circuit circuit = Circuit(4) circuit.add(gates.H(0)) circuit.add(gates.RX(1, theta=0.5)) circuit.add(gates.RY(2, theta=0.3)) circuit.add(gates.CNOT(0, 1)) circuit.add(gates.CZ(1, 2)) circuit.add(gates.fSim(2, 3, theta=0.1, phi=0.2)) # Execute and get state vector result = backend.execute_circuit(circuit) state = result.state() # Convert GPU array to numpy state_numpy = backend.to_numpy(state) print(f"State vector shape: {state_numpy.shape}") print(f"Probability of |0000>: {np.abs(state_numpy[0])**2:.4f}") ``` -------------------------------- ### POST /backend/execute_circuit Source: https://context7.com/qiboteam/qibojit/llms.txt Executes a quantum circuit on the selected backend and returns the result object containing state vectors or measurement outcomes. ```APIDOC ## POST /backend/execute_circuit ### Description Executes a complete quantum circuit and returns results including final state and measurement outcomes. ### Method POST ### Endpoint /backend/execute_circuit ### Parameters #### Request Body - **circuit** (Circuit) - Required - The quantum circuit object to execute. - **nshots** (int) - Optional - Number of shots for sampling (if measurements are present). ### Request Example { "circuit": "", "nshots": 10000 } ### Response #### Success Response (200) - **result** (Result) - Object containing state vector or measurement frequencies. #### Response Example { "frequencies": {"0000": 5000, "1111": 5000}, "samples": "" } ``` -------------------------------- ### Collapse Quantum State Source: https://context7.com/qiboteam/qibojit/llms.txt Demonstrates collapsing a quantum state after a measurement using the `collapse_state` method. It shows how to project the state onto a specific measurement outcome and normalize it. Requires qibo and numpy. ```python from qibojit.backends import MetaBackend from qibo import gates from qibo.quantum_info import random_statevector import numpy as np backend = MetaBackend.load(platform="numba") nqubits = 4 # Create superposition state state = backend.zero_state(nqubits) h_gate = gates.H(0) state = backend.apply_gate(h_gate, state, nqubits) h_gate = gates.H(1) state = backend.apply_gate(h_gate, state, nqubits) print("Before collapse:") probs_before = np.abs(backend.to_numpy(state))**2 print(f" Non-zero amplitudes: {np.sum(probs_before > 0.01)}") # Collapse qubits 0 and 1 to outcome |01> (binary 1) qubits = [0, 1] shot = 1 # Binary representation of measurement outcome state_collapsed = backend.collapse_state( state, qubits=qubits, shot=shot, nqubits=nqubits, normalize=True ) print("After collapse to |01>:") probs_after = np.abs(backend.to_numpy(state_collapsed))**2 print(f" Non-zero amplitudes: {np.sum(probs_after > 0.01)}") print(f" State norm: {np.sqrt(np.sum(probs_after)):.6f}") ``` -------------------------------- ### POST /backend/apply_gate Source: https://context7.com/qiboteam/qibojit/llms.txt Applies a quantum gate operation to a state vector or density matrix using JIT-compiled kernels. ```APIDOC ## POST /backend/apply_gate ### Description Applies a specific quantum gate to the current state representation. This endpoint handles both pure state vectors and density matrices. ### Method POST ### Endpoint /backend/apply_gate ### Parameters #### Request Body - **gate** (object) - Required - The gate object (e.g., H, CNOT, X). - **state** (array) - Required - The current state vector or density matrix. - **nqubits** (integer) - Required - Total number of qubits in the circuit. ### Request Example { "gate": {"type": "CNOT", "targets": [0, 1]}, "state": [1, 0, 0, 0], "nqubits": 2 } ### Response #### Success Response (200) - **state** (array) - The updated state vector or density matrix after gate application. #### Response Example { "state": [1, 0, 0, 0] } ``` -------------------------------- ### Export Backend Tensors to NumPy with to_numpy Source: https://context7.com/qiboteam/qibojit/llms.txt Demonstrates converting backend-specific tensors back to standard NumPy arrays for analysis, visualization, or external processing. ```python from qibojit.backends import MetaBackend import numpy as np backend = MetaBackend.load() state_np = backend.to_numpy(state) probabilities = np.abs(state_np)**2 ``` -------------------------------- ### Sample Frequencies with Metropolis Source: https://context7.com/qiboteam/qibojit/llms.txt Calculates measurement frequencies for a quantum circuit using the Metropolis algorithm for a large number of shots. It prints the top 5 most frequent outcomes and their probabilities. This method is efficient for large shot counts. ```python frequencies = backend.sample_frequencies(probs, nshots=100000) print("Measurement frequencies:") for outcome, count in sorted(frequencies.items(), key=lambda x: -x[1])[:5]: print(f" |{outcome:04b}>: {count} ({count/100000*100:.1f}%)") ``` -------------------------------- ### Apply Two-Qubit Gate Kernel Source: https://context7.com/qiboteam/qibojit/llms.txt Applies a two-qubit gate represented by a matrix to a quantum state vector. This function is optimized for performance using JIT compilation. ```python cnot_matrix = np.array([ [1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0] ], dtype=np.complex128) nstates_2q = 2**(nqubits - 2) state = jit_gates.apply_two_qubit_gate_kernel( state, cnot_matrix, nstates_2q, m1=1, m2=0, swap_targets=False ) ``` -------------------------------- ### POST /backend/collapse_state Source: https://context7.com/qiboteam/qibojit/llms.txt Collapses a quantum state after measurement, projecting onto the measured outcome and optionally normalizing. ```APIDOC ## POST /backend/collapse_state ### Description Projects the quantum state onto a specific measurement outcome. ### Method POST ### Endpoint /backend/collapse_state ### Parameters #### Request Body - **state** (ndarray) - Required - The current quantum state vector. - **qubits** (list) - Required - List of qubits measured. - **shot** (int) - Required - The binary outcome of the measurement. - **nqubits** (int) - Required - Total number of qubits. - **normalize** (bool) - Optional - Whether to re-normalize the state after collapse. ### Request Example { "state": "", "qubits": [0, 1], "shot": 1, "nqubits": 4, "normalize": true } ### Response #### Success Response (200) - **state** (ndarray) - The collapsed and optionally normalized state vector. ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.