### Install Required Packages Source: https://github.com/quantumbfs/yao.jl/blob/master/notebooks/README.md Install essential packages for quantum computing, plotting, and data analysis. These are needed for the tutorials. ```julia ] add Plots, BitBasis, StatsBase, Yao, YaoPlots ``` -------------------------------- ### Serve Documentation Locally Source: https://github.com/quantumbfs/yao.jl/blob/master/CLAUDE.md Starts a local web server to view the project documentation with live reloading capabilities. ```bash # Serve docs locally with live reload make servedocs ``` -------------------------------- ### Install YaoToEinsum Package Source: https://github.com/quantumbfs/yao.jl/blob/master/lib/YaoToEinsum/README.md To install the YaoToEinsum package, open Julia's REPL, enter package mode by pressing ']', and then type 'add YaoToEinsum'. ```julia pkg> add YaoToEinsum ``` -------------------------------- ### Install Pluto.jl Source: https://github.com/quantumbfs/yao.jl/blob/master/notebooks/README.md Run this command in the Julia REPL to install the Pluto notebook environment. ```julia ] add Pluto ``` -------------------------------- ### Install PauliPropagation Extension Source: https://github.com/quantumbfs/yao.jl/blob/master/docs/src/man/paulipropagation.md Load the necessary packages for using the Pauli Propagation extension in Yao. This is automatically handled if both packages are installed. ```julia using Yao using PauliPropagation ``` -------------------------------- ### YaoBlocks Module Documentation Source: https://github.com/quantumbfs/yao.jl/blob/master/lib/YaoBlocks/docs/src/index.md This snippet shows the setup for documenting the YaoBlocks module using DocTestSetup and autodocs. ```julia # DocTestSetup = quote # using Yao, YaoBlocks, YaoArrayRegister # end # @autodocs # Modules = [YaoBlocks] # ``` -------------------------------- ### Add YaoArrayRegister Package Source: https://github.com/quantumbfs/yao.jl/blob/master/lib/YaoArrayRegister/README.md Install the YaoArrayRegister package using the Julia package manager. Requires Julia v1.0 or later. ```julia pkg> add YaoArrayRegister ``` -------------------------------- ### Install Stable Release of Yao Source: https://github.com/quantumbfs/yao.jl/blob/master/README.md Command to add the stable release of the Yao Julia package. This is done within Julia's package manager (REPL). ```julia pkg> add Yao ``` -------------------------------- ### Get Circuit Parameters Source: https://github.com/quantumbfs/yao.jl/blob/master/docs/src/quick-start.md Retrieves a list of parameters for a given quantum circuit. Useful in conjunction with automatic differentiation. ```julia parameters(qft(3)) ``` -------------------------------- ### Install Master Branch of Yao Source: https://github.com/quantumbfs/yao.jl/blob/master/README.md Command to add the latest development version (master branch) of the Yao Julia package. This is done within Julia's package manager (REPL). ```julia pkg> add Yao#master ``` -------------------------------- ### Define apply! for Custom Block Source: https://github.com/quantumbfs/yao.jl/blob/master/docs/src/man/blocks.md Overload the apply! interface for custom blocks to improve performance or dispatch to specialized instructions. This example shows a specialized implementation for XGate. ```julia function apply!(r::ArrayReg, x::XGate) nactive(r) == 1 || throw(QubitMismatchError("register size ", nactive(r), " mismatch with block size ", N)) instruct!(matvec(r.state), Val(:X), (1, )) return r end ``` -------------------------------- ### Convert Simple Single-Qubit Gate to QASM Source: https://github.com/quantumbfs/yao.jl/blob/master/docs/src/man/openqasm.md Converts a simple single-qubit gate (X gate on the first qubit of a 2-qubit system) to its OpenQASM representation. This is a basic example of exporting a Yao circuit. ```julia using Yao # Simple single-qubit gate qasm(put(2, 1=>X)) ``` -------------------------------- ### Run Pluto Notebook Environment Source: https://github.com/quantumbfs/yao.jl/blob/master/notebooks/README.md Import and run Pluto to access the interactive notebooks. This is the entry point for the tutorials. ```julia import Pluto Pluto.run() ``` -------------------------------- ### Initialize Local Development Environment Source: https://github.com/quantumbfs/yao.jl/blob/master/CLAUDE.md Initializes the local development environment by developing all sub-packages within the lib/ directory. ```bash # Initialize local dev environment (develops all lib packages) make init ``` -------------------------------- ### Initialize and Test CuYao Backend Source: https://github.com/quantumbfs/yao.jl/blob/master/ext/CuYao/README.md Run these commands in the terminal within the Yao folder to set up and execute tests for the CuYao backend. ```bash make init-CuYao make test-CuYao ``` -------------------------------- ### Using GPU Backend with CuYao Source: https://github.com/quantumbfs/yao.jl/blob/master/docs/src/performancetips.md To leverage GPU acceleration, use the `CuYao` package. Initialize your quantum register on the GPU using `CuYao.cu()` and then apply your circuits. ```julia julia> using Yao, CuYao julia> reg = CuYao.cu(rand_state(20)); julia> circ = Yao.EasyBuild.qft_circuit(20); julia> apply!(reg, circ) ArrayReg{2, ComplexF64, CuArray...} active qubits: 20/20 nlevel: 2 ``` -------------------------------- ### Import Qiskit Circuit to Yao Source: https://github.com/quantumbfs/yao.jl/blob/master/docs/src/man/openqasm.md Save a Qiskit circuit to OpenQASM format and then load it into Yao. ```python from qiskit import QuantumCircuit pc = QuantumCircuit(2) pc.h(0) pc.cx(0, 1) pc.measure_all() pc.qasm(filename="qiskit_circuit.qasm") ``` ```julia using Yao qasm_str = read("qiskit_circuit.qasm", String) task = parseblock(qasm_str) circuit = task.circuit ``` -------------------------------- ### Get Matrix Form of a Block Source: https://github.com/quantumbfs/yao.jl/blob/master/lib/YaoAPI/README.md Returns the matrix form of a given block. Use this to obtain the matrix representation of a Yao block. ```julia help?> YaoAPI.mat mat([T=ComplexF64], blk) Returns the matrix form of given block. ``` -------------------------------- ### Run Full Test Suite Source: https://github.com/quantumbfs/yao.jl/blob/master/CLAUDE.md Executes the complete test suite across all packages in the repository. ```bash # Run full test suite (all packages) make test ``` -------------------------------- ### Query and Manipulate Register Properties Source: https://github.com/quantumbfs/yao.jl/blob/master/docs/src/man/registers.md Demonstrates how to query properties like the number of qudits, active qubits, remaining qubits, batch size, and levels. Also shows how to activate specific qubits with `focus!`, deactivate them with `relax!`, reorder qubits with `reorder!`, and calculate fidelity and trace distance between states. ```julia using Yao reg = rand_state(3; nlevel=4, nbatch=2) nqudits(reg) # the total number of qudits nactive(reg) # the number of active qubits nremain(reg) # the number of remaining qubits batch(reg) # the batch size nlevel(reg) # the number of levels of each qudit basis(reg) # the basis of the register focus!(reg, 1:2) # set on the first two qubits as active nactive(reg) # the number of active qubits basis(reg) # the basis of the register relax!(reg) # set all qubits as active nactive(reg) # the number of active qubits reorder!(reg, (3,1,2)) # reorder the qubits reg1 = product_state(bit"111"); reg2 = ghz_state(3); fidelity(reg1, reg2) # the fidelity between two states tracedist(reg1, reg2) # the trace distance between two states ``` -------------------------------- ### Create Unnormalized Bell State Source: https://github.com/quantumbfs/yao.jl/blob/master/docs/src/man/registers.md Creates an unnormalized Bell state |01⟩ - |10⟩ from a given vector. Use `statevec` to get the normalized state vector and `print_table` for a tabular representation. ```julia using Yao reg = ArrayReg([0, 1, -1+0.0im, 0]) # a unnormalized Bell state |01⟩ - |10⟩ statevec(reg) # a quantum state is represented as a vector print_table(reg) ``` -------------------------------- ### cpu Source: https://github.com/quantumbfs/yao.jl/blob/master/docs/src/man/cuda.md Downloads a quantum register from the GPU to the CPU. ```APIDOC ## cpu ### Description Downloads a quantum register from the GPU to the CPU. ### Method (Implicitly called via pipe operator `|>`) ### Endpoint N/A (Function call) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```julia cureg |> cpu ``` ### Response #### Success Response - **reg** (QuantumRegister) - The quantum register downloaded to the CPU. #### Response Example ```julia # Example output structure (actual type may vary) QuantumRegister(...) ``` ``` -------------------------------- ### Run Yao Circuits on GPU with CuYao Source: https://github.com/quantumbfs/yao.jl/blob/master/docs/src/man/cuda.md Demonstrates creating a quantum register on the GPU, applying gates, measuring, and downloading the result back to the CPU. Use `cu(reg)` to upload registers to the GPU and `cpu(cureg)` to download them. ```julia julia> using Yao, CUDA # create a register on GPU julia> cureg = rand_state(9; nbatch=1000) |> cu; # or `curand_state(9; nbatch=1000)`. # run a circuit on GPU julia> cureg |> put(9, 2=>Z); # measure the register on GPU julia> measure!(cureg) 1000-element CuArray{DitStr{2, 9, Int64}, 1, CUDA.Mem.DeviceBuffer}: 110110100 ₍₂₎ 000100001 ₍₂₎ 111111001 ₍₂₎ ⋮ 010001101 ₍₂₎ 000100110 ₍₂₎ # download the register to CPU julia> reg = cureg |> cpu; ``` -------------------------------- ### Compare with Direct Yao Simulation (Density Matrix) Source: https://github.com/quantumbfs/yao.jl/blob/master/docs/src/man/yao2einsum.md Compares the result obtained from YaoToEinsum's density matrix mode with a direct simulation using Yao's built-in functions. This verifies the correctness of the simulation. ```julia initial_dm = density_matrix(zero_state(n_small)) res_exact = expect(put(n_small, 1=>Z), apply(initial_dm, noisy_circuit)) ``` -------------------------------- ### Define Symbolic Variables and Create Circuits Source: https://github.com/quantumbfs/yao.jl/blob/master/docs/src/man/symbolic.md Demonstrates defining a symbolic variable θ using `@vars`, creating a quantum circuit with this symbolic parameter, and computing its matrix representation. It also shows how to substitute the symbolic variable with a concrete value (π/2) and obtain the new circuit's matrix. ```julia using Yao @vars θ circuit = chain(2, put(1=>H), put(2=>Ry(θ))) mat(circuit) new_circuit = subs(circuit, θ=>π/2) mat(new_circuit) ``` -------------------------------- ### Create Quantum Registers/States Source: https://github.com/quantumbfs/yao.jl/blob/master/docs/src/quick-start.md Demonstrates creating different types of quantum registers and states, including random states, zero states, product states, and GHZ states. ```julia using Yao ArrayReg(randn(ComplexF64, 2^3)) # a random unnormalized 3-qubit state ``` ```julia zero_state(5) # |00000⟩ ``` ```julia rand_state(5) # a random state ``` ```julia product_state(bit"10100") # |10100⟩ ``` ```julia ghz_state(5) # (|00000⟩ + |11111⟩)/√2 ``` -------------------------------- ### Create a Simpler Circuit for Noisy Simulation Source: https://github.com/quantumbfs/yao.jl/blob/master/docs/src/man/yao2einsum.md This snippet sets up a basic quantum circuit with amplitude damping noise for simulation. ```julia # Create a simpler circuit for noisy simulation n_small = 3 γ = 0.1 # damping parameter # Create amplitude damping channels damping_channel = quantum_channel(AmplitudeDampingError(γ)) # Build noisy circuit: gate followed by noise on the same qubits noisy_circuit = chain(n_small, put(1=>X), put(1=>damping_channel), put(2=>H), put(2=>damping_channel), cnot(1,2), put(1=>damping_channel), put(2=>damping_channel), put(3=>Z), put(3=>damping_channel) ) ``` -------------------------------- ### Applying Gates with instruct! Source: https://github.com/quantumbfs/yao.jl/blob/master/docs/src/man/registers.md Applies quantum gates to specific qubits using the `instruct!` function for efficient simulation. This method is faster and more memory-efficient than matrix multiplication for quantum simulations. ```julia reg = zero_state(2) instruct!(reg, Val(:H), (1,)) # apply a Hadamard gate on the first qubit print_table(reg) ``` -------------------------------- ### Export Yao Circuit to Qiskit Source: https://github.com/quantumbfs/yao.jl/blob/master/docs/src/man/openqasm.md Export a Yao circuit to OpenQASM format and then load it into Qiskit. ```julia using Yao # Create circuit in Yao circuit = chain(2, put(1=>H), control(1, 2=>X)) # Save as QASM write("bell_state.qasm", qasm(circuit; include_header=true)) ``` ```python from qiskit import QuantumCircuit circuit = QuantumCircuit.from_qasm_file("bell_state.qasm") ``` -------------------------------- ### Load Yao Circuit from OpenQASM File Source: https://github.com/quantumbfs/yao.jl/blob/master/docs/src/man/openqasm.md Read an OpenQASM string from a file and parse it into a Yao circuit object. This enables the use of pre-existing QASM circuits within the Yao.jl framework. ```julia using Yao # Read QASM file qasm_string = read("my_circuit.qasm", String) # Parse to Yao circuit task = parseblock(qasm_string) circuit = task.circuit # Use the circuit reg = zero_state(nqubits(circuit)) apply!(reg, circuit) ``` -------------------------------- ### Visualize a QFT Circuit Source: https://github.com/quantumbfs/yao.jl/blob/master/docs/src/man/plot.md Visualize a Quantum Fourier Transform circuit defined in Yao. This is useful for understanding the structure of QFT circuits. ```julia using Yao.EasyBuild, YaoPlots # show a qft circuit vizcircuit(qft_circuit(5)) ``` -------------------------------- ### Export Complex QFT Circuit to QASM with Header Source: https://github.com/quantumbfs/yao.jl/blob/master/docs/src/man/openqasm.md Exports a Quantum Fourier Transform (QFT) circuit, built using nested chains and controlled phase gates, to an OpenQASM string with a header. This demonstrates Yao's ability to handle and export complex, high-level circuit constructs after automatic simplification. ```julia using Yao.EasyBuild # QFT circuit uses nested chains and controlled phase gates circuit = qft_circuit(3) println(qasm(circuit; include_header=true)) ``` -------------------------------- ### Visualize Quantum Circuit Source: https://github.com/quantumbfs/yao.jl/blob/master/docs/src/quick-start.md Visualizes a quantum circuit using the `YaoPlots` package. Requires `Compose` for rendering. ```julia using Yao.EasyBuild, Yao.YaoPlots using Compose # show a qft circuit vizcircuit(qft_circuit(5)) ``` -------------------------------- ### Quantum Fourier Transformation (QFT) in Yao Source: https://github.com/quantumbfs/yao.jl/blob/master/README.md A 3-line implementation of the Quantum Fourier Transformation using Yao's Quantum Blocks. This snippet defines helper functions for creating controlled phase shifts and applying them in a chain. ```julia A(i, j) = control(i, j=>shift(2π/(1<<(i-j+1)))) B(n, k) = chain(n, j==k ? put(k=>H) : A(j, k) for j in k:n) qft(n) = chain(B(n, k) for k in 1:n) ``` -------------------------------- ### Applying Quantum Operators Source: https://github.com/quantumbfs/yao.jl/blob/master/docs/src/man/registers.md The `instruct!` function is for applying quantum operators on a quantum register. ```APIDOC ### Applying Operators ```@docs YaoArrayRegister.instruct! ``` ``` -------------------------------- ### Parse OpenQASM String to Yao Circuit Source: https://github.com/quantumbfs/yao.jl/blob/master/docs/src/man/openqasm.md Parses a given OpenQASM 2.0 string into a Yao `SimulationTask`, which includes the quantum circuit and measurement outcome references. This demonstrates how to import circuits from OpenQASM format into Yao. ```julia qasm_str = """ OPENQASM 2.0; include "qelib1.inc"; qreg q[2]; creg c[2]; h q[0]; cx q[0],q[1]; measure q -> c; """ task = parseblock(qasm_str) task.circuit ``` -------------------------------- ### Save Yao Circuit to OpenQASM File Source: https://github.com/quantumbfs/yao.jl/blob/master/docs/src/man/openqasm.md Convert a Yao circuit to its OpenQASM string representation and save it to a file. This allows for persistent storage and sharing of quantum circuits. ```julia using Yao # Create a circuit circuit = chain(3, put(1=>H), control(1, 2=>X), control(2, 3=>X), put(1=>Rz(0.5)), Measure(3) ) # Convert to QASM and save qasm_string = qasm(circuit; include_header=true) write("my_circuit.qasm", qasm_string) ``` -------------------------------- ### Convert Circuit to QASM with Header Source: https://github.com/quantumbfs/yao.jl/blob/master/docs/src/man/openqasm.md Converts a Yao circuit to an OpenQASM string, including the full QASM header (version, includes, and register declarations) by setting `include_header=true`. This is useful for generating complete, standalone QASM files. ```julia qasm(circuit; include_header=true) ``` -------------------------------- ### Create a QFT Circuit Source: https://github.com/quantumbfs/yao.jl/blob/master/docs/src/man/yao2einsum.md Generates a Quantum Fourier Transform circuit for a specified number of qubits. This is the initial step before converting it to a tensor network. ```julia using Yao, LuxorGraphPlot using Yao.EasyBuild: qft_circuit n = 4 circuit = qft_circuit(n) # Create a QFT circuit for n qubits ``` -------------------------------- ### Comparing `put` and `subroutine` for QFT Circuit Source: https://github.com/quantumbfs/yao.jl/blob/master/docs/src/performancetips.md Use `subroutine` for larger circuits as it can be more performant than `put` due to its focus mechanism. `put` is generally better for smaller subblocks. ```julia julia> using Yao julia> reg = rand_state(20); julia> @time apply(reg, put(20, 1:6=>EasyBuild.qft_circuit(6))); # second run 0.070245 seconds (1.32 k allocations: 16.525 MiB) ``` ```julia julia> @time apply(reg, subroutine(20, EasyBuild.qft_circuit(6), 1:6)); # second run 0.036840 seconds (1.07 k allocations: 16.072 MiB) ``` -------------------------------- ### Parse OpenQASM with Noise Model in Yao Source: https://github.com/quantumbfs/yao.jl/blob/master/docs/src/man/openqasm.md Parse an OpenQASM string with a defined noise model to simulate noisy quantum circuits. ```julia using Yao using YaoBlocks: ErrorPattern, parse_noise_model # Define noise model noise_data = [ Dict( "type" => "depolarizing", "operations" => ["x", "y", "z", "h"], "qubits" => [[0], [1]], "probability" => 0.01 ), Dict( "type" => "depolarizing2", "operations" => ["cx"], "qubits" => [[0, 1]], "probability" => 0.02 ) ] gate_errors, ro_errors = parse_noise_model(noise_data) # Parse QASM with noise qasm_str = """ OPENQASM 2.0; include "qelib1.inc"; qreg q[2]; creg c[2]; h q[0]; cx q[0],q[1]; """ task = parseblock(qasm_str, gate_errors) # The circuit now includes noise channels after each gate ``` -------------------------------- ### Export Yao Circuit for Other Frameworks Source: https://github.com/quantumbfs/yao.jl/blob/master/docs/src/man/openqasm.md Export a Yao circuit to OpenQASM, which can then be loaded by frameworks like Cirq and PennyLane. ```julia # Yao write("circuit.qasm", qasm(circuit; include_header=true)) ``` ```python # Cirq import cirq from cirq.contrib.qasm_import import circuit_from_qasm circuit = circuit_from_qasm(open("circuit.qasm").read()) # PennyLane import pennylane as qml circuit = qml.from_qasm(open("circuit.qasm").read()) ``` -------------------------------- ### Autodocs for Simplification Module Source: https://github.com/quantumbfs/yao.jl/blob/master/docs/src/man/simplification.md This snippet shows how to use autodocs to generate documentation for the YaoBlocks.Optimise module, which contains simplification functions. ```julia # Simplify API ```@autodocs Modules = [YaoBlocks.Optimise] Order = [:function, :macro] ``` ``` -------------------------------- ### cuproduct_state Source: https://github.com/quantumbfs/yao.jl/blob/master/docs/src/man/cuda.md Creates a product quantum state register on the GPU. ```APIDOC ## cuproduct_state ### Description Creates a quantum register in a product state on the GPU. ### Method (Implicitly called via pipe operator `|>`) ### Endpoint N/A (Function call) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```julia cuproduct_state(register_config; nbatch=1) ``` ### Response #### Success Response - **cureg** (CuArray) - A CuArray representing the product quantum state register on the GPU. #### Response Example ```julia # Example output structure (actual type may vary) CuArray{...} ``` ``` -------------------------------- ### Create Product State from Bit String Source: https://github.com/quantumbfs/yao.jl/blob/master/docs/src/man/registers.md Creates a product state from a bit string. The bit string is interpreted in little-endian format. `print_table` displays the state. ```julia using Yao reg_prod = product_state(bit"110") # a product state bit"110"[3] # the bit string is in little-endian format print_table(reg_prod) ``` -------------------------------- ### Roundtrip Verification of Yao Circuits with OpenQASM Source: https://github.com/quantumbfs/yao.jl/blob/master/docs/src/man/openqasm.md Verify that a Yao circuit can be converted to OpenQASM and back to Yao while maintaining functional equivalence. This is useful for ensuring circuit integrity after conversion. ```julia using Yao, Yao.EasyBuild # Create a circuit circuit = variational_circuit(4, 2) # Convert to QASM and back qasm_str = qasm(circuit; include_header=true) parsed = parseblock(qasm_str).circuit # Verify equivalence reg1 = rand_state(4) reg2 = copy(reg1) apply!(reg1, circuit) apply!(reg2, parsed) fidelity(reg1, reg2) ≈ 1.0 # true ``` -------------------------------- ### Quantum Register Constructors Source: https://github.com/quantumbfs/yao.jl/blob/master/docs/src/man/registers.md Constructors for creating different types of quantum registers. ```APIDOC ## API ### Constructors ```@docs AbstractRegister AbstractArrayReg ArrayReg BatchedArrayReg arrayreg product_state zero_state zero_state_like rand_state uniform_state ghz_state clone ``` ``` -------------------------------- ### Create a 3-Qubit Quantum Fourier Transform Circuit Source: https://github.com/quantumbfs/yao.jl/blob/master/docs/src/quick-start.md Defines and creates a 3-qubit Quantum Fourier Transform (QFT) circuit. This involves defining helper functions for controlled phase gates and applying them in a chain. ```julia A(i, j) = control(i, j=>shift(2π/(1<<(i-j+1)))) # a cphase gate ``` ```julia B(n, k) = chain(n, j==k ? put(k=>H) : A(j, k) for j in k:n) ``` ```julia qft(n) = chain(B(n, k) for k in 1:n) ``` ```julia circuit = qft(3) # a 3-qubit QFT circuit ``` ```julia mat(circuit) # the matrix representation of the circuit ``` ```julia apply!(zero_state(3), circuit) # apply the circuit to a zero state ``` -------------------------------- ### Density Matrix Operations Source: https://github.com/quantumbfs/yao.jl/blob/master/docs/src/man/registers.md Demonstrates common operations on density matrices, such as creation, partial tracing, purification, and entropy calculation. These functions are useful for analyzing mixed quantum states. ```julia reg = rand_state(3) rho = density_matrix(reg) # the density matrix of the state ``` ```julia rand_density_matrix(3) # a random density matrix ``` ```julia completely_mixed_state(3) # a completely mixed state ``` ```julia partial_tr(rho, 1) # partial trace on the first qubit ``` ```julia purify(rho) # purify the state ``` ```julia von_neumann_entropy(rho) # von Neumann entropy ``` ```julia mutual_information(rho, 1, 2) # mutual information between qubits 1 and 2 ``` -------------------------------- ### Create a 5-Qubit Ising Hamiltonian Source: https://github.com/quantumbfs/yao.jl/blob/master/docs/src/quick-start.md Constructs a 5-qubit Ising Hamiltonian on a 1D chain using `sum`, `kron`, and `mod1` for periodic boundary conditions. ```julia h = sum([kron(5, i=>Z, mod1(i+1, 5)=>Z) for i in 1:5]) # a 5-qubit Ising Hamiltonian ``` ```julia mat(h) # the matrix representation of the Hamiltonian ``` -------------------------------- ### Create a 2-Qubit Circuit Source: https://github.com/quantumbfs/yao.jl/blob/master/docs/src/quick-start.md Constructs a simple 2-qubit quantum circuit using the `chain` function and `put` for applying gates. ```julia chain(2, put(1=>H), put(2=>X)) ``` -------------------------------- ### Test with Coverage Source: https://github.com/quantumbfs/yao.jl/blob/master/CLAUDE.md Runs the full test suite and generates a coverage report. Coverage data is typically uploaded to Codecov. ```bash # Test with coverage make test coverage=true ``` -------------------------------- ### Simulate Noisy Circuit with Pauli Propagation Source: https://github.com/quantumbfs/yao.jl/blob/master/docs/src/man/paulipropagation.md Create a noisy quantum circuit, convert it to Pauli propagation representation, and propagate the observable. Compares the result with an exact density matrix simulation. ```julia using Yao, PauliPropagation # Create a noisy circuit with rotation gates and depolarizing noise n = 5 circuit = chain(n, put(n, 1=>H), put(n, 2=>Rx(0.3)), control(n, 1, 2=>X), put(n, 1=>quantum_channel(DepolarizingError(1, 0.01))) ) # Define an observable (e.g., measure Z on first qubit) observable = put(n, 1=>Z) # Convert to PauliPropagation representation pc = yao2paulipropagation(circuit; observable=observable) # Propagate the observable through the circuit psum = propagate(pc) # Get the expectation value exp_pauli = real(overlapwithzero(psum)) println("PauliPropagation result: ", exp_pauli) # Compare with exact density matrix simulation reg = zero_state(n) |> density_matrix reg_final = apply!(reg, circuit) exp_exact = real(expect(observable, reg_final)) println("Exact simulation result: ", exp_exact) println("Difference: ", abs(exp_pauli - exp_exact)) ``` -------------------------------- ### Create Batched Quantum States Source: https://github.com/quantumbfs/yao.jl/blob/master/docs/src/man/registers.md Generates a batch of random quantum states. `viewbatch` can be used to access individual states within the batch. `print_table` displays the states. ```julia using Yao reg_batch = rand_state(3; nbatch=2) # a batch of 2 random qubit states print_table(reg_batch) reg_view = viewbatch(reg_batch, 1) # view the first state in the batch print_table(reg_view) ``` -------------------------------- ### Create Random and Product Qudit States Source: https://github.com/quantumbfs/yao.jl/blob/master/docs/src/man/registers.md Generates a random qutrit state and a qudit product state. The number of levels for qudits is specified after a semicolon in the `product_state` function. ```julia using Yao reg_rand3 = rand_state(3, nlevel=3) # a random qutrit state reg_prod3 = product_state(dit"120;3") # a qudit product state, what follows ";" symbol denotes the number of levels print_table(reg_prod3) ``` -------------------------------- ### Convert Complete Circuit to QASM Source: https://github.com/quantumbfs/yao.jl/blob/master/docs/src/man/openqasm.md Converts a complete 2-qubit circuit, including a Hadamard gate and a controlled-X gate, to its OpenQASM string representation. This shows the export of a more complex circuit. ```julia # A complete circuit circuit = chain(2, put(1=>H), control(1, 2=>X)) qasm(circuit) ``` -------------------------------- ### Define Parameters for Custom Block Source: https://github.com/quantumbfs/yao.jl/blob/master/docs/src/man/blocks.md Declare and define methods for niparams, getiparams, and setiparams! to manage tweakable parameters within a custom block. ```julia niparams(::Type{<:PhaseGate}) = 1 getiparams(x::PhaseGate) = x.theta setiparams!(r::PhaseGate, param::Real) = (r.theta = param; r) ``` -------------------------------- ### Comparing `repeat` and `chain(put)` for X Gate Source: https://github.com/quantumbfs/yao.jl/blob/master/docs/src/performancetips.md The `repeat` block can offer significant speedups over manually chaining `put` operations for certain gates like `X`. ```julia julia> reg = rand_state(20); julia> @time apply!(reg, repeat(20, X)); 0.002252 seconds (5 allocations: 656 bytes) ``` ```julia julia> @time apply!(reg, chain([put(20, i=>X) for i=1:20])); 0.049362 seconds (82.48 k allocations: 4.694 MiB, 47.11% compilation time) ``` -------------------------------- ### Test Single Sub-package Source: https://github.com/quantumbfs/yao.jl/blob/master/CLAUDE.md Tests a specific sub-package using Julia's Pkg API. Ensure you are in the repository root. ```bash # Test a single sub-package julia --project -e 'using Pkg; Pkg.test("YaoBlocks")' ``` -------------------------------- ### Run Specific Test File Source: https://github.com/quantumbfs/yao.jl/blob/master/CLAUDE.md Executes a particular test file within a sub-package. This is useful for targeted debugging. ```bash # Run a specific test file within a sub-package julia --project=lib/YaoBlocks -e 'include("test/runtests.jl")' ``` -------------------------------- ### Block Method Prototypes Source: https://github.com/quantumbfs/yao.jl/blob/master/docs/src/notes.md These are the prototypes for the 'apply!' and 'mat' methods used when defining blocks. Overload 'mat' to define the block's matrix form and 'apply!' to define its application to a register. ```julia apply!(reg, block) mat(block) ``` -------------------------------- ### Calculate Expectation Value Source: https://github.com/quantumbfs/yao.jl/blob/master/docs/src/man/automatic_differentiation.md This snippet shows how to calculate the expectation value of a Hamiltonian for a given quantum state and circuit. ```julia expect(H, rand_state(10)=>circuit) ``` -------------------------------- ### Customize Quantum Circuit Plot Attributes Source: https://github.com/quantumbfs/yao.jl/blob/master/docs/src/man/plot.md Customize various attributes of the quantum circuit visualization, such as line color, gate background color, text color, line width, and text sizes. This allows for tailored visual representations of circuits. ```julia using YaoPlots, Yao YaoPlots.CircuitStyles.linecolor[] = "pink" YaoPlots.CircuitStyles.gate_bgcolor[] = "yellow" YaoPlots.CircuitStyles.textcolor[] = "#000080" # the navy blue color YaoPlots.CircuitStyles.fontfamily[] = "JuliaMono" YaoPlots.CircuitStyles.lw[] = 2.5 YaoPlots.CircuitStyles.textsize[] = 13 YaoPlots.CircuitStyles.paramtextsize[] = 8 vizcircuit(chain(3, put(1=>X), repeat(3, H), put(2=>Y), repeat(3, Rx(π/2)))) ``` -------------------------------- ### cuzero_state Source: https://github.com/quantumbfs/yao.jl/blob/master/docs/src/man/cuda.md Creates a zero quantum state register on the GPU. ```APIDOC ## cuzero_state ### Description Creates a quantum register initialized to the zero state on the GPU. ### Method (Implicitly called via pipe operator `|>`) ### Endpoint N/A (Function call) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```julia cuzero_state(nqubits; nbatch=1) ``` ### Response #### Success Response - **cureg** (CuArray) - A CuArray representing the zero quantum state register on the GPU. #### Response Example ```julia # Example output structure (actual type may vary) CuArray{...} ``` ``` -------------------------------- ### yao2einsum Source: https://github.com/quantumbfs/yao.jl/blob/master/docs/src/man/yao2einsum.md Converts a Yao circuit into an Einsum string representation. This is the primary function for translating quantum circuits into a format suitable for tensor network contraction. ```APIDOC ## yao2einsum ### Description Converts a Yao circuit into an Einsum string representation. ### Parameters (No specific parameters are detailed in the source for this function, but it is expected to take a Yao circuit as input.) ### Returns (The return type is an Einsum string, but not explicitly detailed.) ``` -------------------------------- ### Visualize Single Qubit State and Density Matrix on Bloch Sphere Source: https://github.com/quantumbfs/yao.jl/blob/master/docs/src/man/plot.md Visualize a single qubit state and a density matrix on a Bloch sphere. This helps in understanding the state of a qubit. The `show_projection_lines` argument can be used to display projection lines. ```julia using YaoPlots, Yao reg = zero_state(1) |> Rx(π/8) |> Rx(π/8) rho = density_matrix(ghz_state(2), 1) bloch_sphere("|ψ⟩"=>reg, "ρ"=>rho; show_projection_lines=true) ``` -------------------------------- ### Convert Controlled Gate to QASM Source: https://github.com/quantumbfs/yao.jl/blob/master/docs/src/man/openqasm.md Converts a controlled gate (CX gate) to its OpenQASM 2.0 compatible representation. This demonstrates exporting controlled operations. ```julia # Control gate (outputs QASM 2.0 compatible cx) qasm(control(2, 1, 2=>X)) ``` -------------------------------- ### cughz_state Source: https://github.com/quantumbfs/yao.jl/blob/master/docs/src/man/cuda.md Creates a GHZ quantum state register on the GPU. ```APIDOC ## cughz_state ### Description Creates a quantum register in a GHZ (Greenberger–Horne–Zeilinger) state on the GPU. ### Method (Implicitly called via pipe operator `|>`) ### Endpoint N/A (Function call) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```julia cughz_state(nqubits; nbatch=1) ``` ### Response #### Success Response - **cureg** (CuArray) - A CuArray representing the GHZ quantum state register on the GPU. #### Response Example ```julia # Example output structure (actual type may vary) CuArray{...} ``` ``` -------------------------------- ### Create Tensor Network for Expectation Value Source: https://github.com/quantumbfs/yao.jl/blob/master/docs/src/man/yao2einsum.md Sets up a tensor network to compute the expectation value of an observable. It requires specifying the initial state, the observable, and the computation mode (e.g., DensityMatrixMode). ```julia # Define the observable (Pauli-Y on first qubit) observable = put(n, 1=>Y) # Create tensor network for expectation value computation # We need to use the `DensityMatrixMode` to sandwich the circuit between the initial state and the observable network_obs = Yao.yao2einsum(circuit; initial_state=Dict(1=>0, 2=>1, 3=>1, 4=>1), # Start in |0111⟩ observable = observable, # Measure expectation value mode = DensityMatrixMode() ) viznet(network_obs) ``` -------------------------------- ### Convert Yao Circuit to Tensor Network Source: https://github.com/quantumbfs/yao.jl/blob/master/docs/src/man/yao2einsum.md Converts a Yao quantum circuit into a tensor network represented in Einstein summation notation. Use this function to enable advanced analysis and simulation of quantum circuits as tensor networks. The function accepts optional parameters for initial and final states, and an optimizer for contraction order. ```julia using Yao, LuxorGraphPlot yao2einsum(circuit; initial_state=Dict(), final_state=Dict(), optimizer=TreeSA()) ``` -------------------------------- ### Simulate Noisy Circuit with Pauli Basis Mode Source: https://github.com/quantumbfs/yao.jl/blob/master/docs/src/man/yao2einsum.md Simulates the noisy circuit using the Pauli basis representation. This mode can be more efficient for certain types of noise and observables. ```julia network_pauli = Yao.yao2einsum(noisy_circuit; mode=PauliBasisMode(), initial_state=Dict([i=>0 for i=1:n_small]), observable=put(n_small, 1=>Z) ) viznet(network_pauli) ``` -------------------------------- ### Arithmetic Operations on ArrayReg Source: https://github.com/quantumbfs/yao.jl/blob/master/docs/src/man/registers.md Demonstrates basic arithmetic operations on ArrayReg objects, including addition, subtraction, scalar multiplication, division, adjoint, and inner product. Ensure states are normalized after operations like addition. ```julia reg1 = rand_state(3) reg2 = rand_state(3) reg3 = reg1 + reg2 # addition normalize!(reg3) # normalize the state isnormalized(reg3) # check if the state is normalized reg1 - reg2 # subtraction reg1 * 2 # scalar multiplication reg1 / 2 # scalar division reg1' # adjoint reg1' * reg1 # inner product ``` -------------------------------- ### Simulate Noisy Circuit with Density Matrix Mode Source: https://github.com/quantumbfs/yao.jl/blob/master/docs/src/man/yao2einsum.md Simulates the noisy circuit using the density matrix representation. This is useful for tracking the full state of the system including decoherence. ```julia network_dm = Yao.yao2einsum(noisy_circuit; mode=DensityMatrixMode(), initial_state=Dict([i=>0 for i=1:n_small]), observable=put(n_small, 1=>Z) ) viznet(network_dm) ``` -------------------------------- ### curand_state Source: https://github.com/quantumbfs/yao.jl/blob/master/docs/src/man/cuda.md Creates a random quantum state register on the GPU. ```APIDOC ## curand_state ### Description Creates a quantum register with a random state on the GPU. ### Method (Implicitly called via pipe operator `|>`) ### Endpoint N/A (Function call) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```julia curand_state(9; nbatch=1000) ``` ### Response #### Success Response - **cureg** (CuArray) - A CuArray representing the random quantum state register on the GPU. #### Response Example ```julia # Example output structure (actual type may vary) CuArray{...} ``` ``` -------------------------------- ### Measurement and Post-selection Source: https://github.com/quantumbfs/yao.jl/blob/master/docs/src/man/registers.md Functions for measurement and post-selection on quantum registers. ```APIDOC ### Measurement and Post-selection ```@docs measure! measure select! select collapseto! probs most_probable ``` ``` -------------------------------- ### Qubit Addition and Reordering Source: https://github.com/quantumbfs/yao.jl/blob/master/docs/src/man/registers.md Functions for adding and reordering qubits in a quantum register. ```APIDOC ### Qubit Manipulation ```@docs insert_qudits! insert_qubits! append_qudits! append_qubits! reorder! invorder! ``` ``` -------------------------------- ### Convert Yao Circuit to PauliPropagation Representation Source: https://github.com/quantumbfs/yao.jl/blob/master/docs/src/man/paulipropagation.md Convert a Yao circuit into the PauliPropagationCircuit intermediate representation. The circuit must only contain gates supported by PauliPropagation, and the observable must be a sum of Pauli strings. ```julia yao2paulipropagation(circuit; observable) ``` -------------------------------- ### Convert Circuit to Tensor Network Source: https://github.com/quantumbfs/yao.jl/blob/master/docs/src/man/yao2einsum.md Converts a Yao circuit into a tensor network representation. This allows for visualization and further contraction. ```julia network = Yao.yao2einsum(circuit) # Convert circuit to tensor network viznet(network) # Visualize the network structure ``` -------------------------------- ### Define Cache Key for Custom Block Source: https://github.com/quantumbfs/yao.jl/blob/master/docs/src/man/blocks.md Implement cache_key for custom blocks to enable caching. For PhaseGate, the cache key is its phase. ```julia cache_key(gate::PhaseGate) = gate.theta ``` -------------------------------- ### paulipropagation2yao Source: https://github.com/quantumbfs/yao.jl/blob/master/docs/src/man/paulipropagation.md Converts a PauliPropagationCircuit to a Yao circuit. ```APIDOC ## Function paulipropagation2yao Converts a PauliPropagationCircuit to a Yao circuit. ``` -------------------------------- ### Quantum Register Properties Source: https://github.com/quantumbfs/yao.jl/blob/master/docs/src/man/registers.md Functions for querying the properties of a quantum register. ```APIDOC ### Properties ```@docs nqudits nqubits nactive nremain nbatch nlevel focus! focus relax! exchange_sysenv ``` ``` -------------------------------- ### Density Matrices Source: https://github.com/quantumbfs/yao.jl/blob/master/docs/src/man/registers.md Functions for creating and manipulating density matrices. ```APIDOC ### Density Matrices ```@docs DensityMatrix density_matrix rand_density_matrix completely_mixed_state partial_tr purify von_neumann_entropy mutual_information ``` ``` -------------------------------- ### yao2paulipropagation Source: https://github.com/quantumbfs/yao.jl/blob/master/docs/src/man/paulipropagation.md Converts a Yao circuit to a PauliPropagationCircuit. ```APIDOC ## Function yao2paulipropagation Converts a Yao circuit to a PauliPropagationCircuit. ``` -------------------------------- ### Visualize Quantum States on Bloch Sphere Source: https://github.com/quantumbfs/yao.jl/blob/master/lib/YaoPlots/README.md The `bloch_sphere` function visualizes single-qubit states or density matrices on a Bloch sphere. It supports showing projection lines for clarity. ```julia using YaoPlots, Yao reg = zero_state(1) |> Rx(π/8) |> Rx(π/8) rho = density_matrix(ghz_state(2), 1) bloch_sphere("|ψ>"=>reg, "ρ"=>rho; show_projection_lines=true) ``` -------------------------------- ### Contract Network for Expectation Value and Compare Source: https://github.com/quantumbfs/yao.jl/blob/master/docs/src/man/yao2einsum.md Contracts the tensor network configured for expectation value computation to obtain the result. This is then compared with the exact expectation value computed directly using Yao. ```julia # Contract to get the expectation value res_network = real(Yao.contract(network_obs)[]) # Compare with direct Yao computation state_after_circuit = product_state(bit"1110") |> circuit res_exact = real(expect(observable, state_after_circuit)) ``` -------------------------------- ### Register Manipulation Operations Source: https://github.com/quantumbfs/yao.jl/blob/master/docs/src/man/registers.md Shows how to manipulate the qubits within an ArrayReg. Use `append_qudits!` to add qubits to the end and `insert_qudits!` to add qubits at a specific position. ```julia reg0 = rand_state(3) append_qudits!(reg0, 2) # append 2 qubits insert_qudits!(reg0, 2, 2) # insert 2 qubits at the 2nd position ``` -------------------------------- ### Contract Network for Amplitude and Compare Source: https://github.com/quantumbfs/yao.jl/blob/master/docs/src/man/yao2einsum.md Contracts the tensor network configured for specific states to obtain the probability amplitude. This result is then compared with a direct computation using Yao. ```julia # Contract the network to get the amplitude amplitude_from_network = Yao.contract(network_with_states)[] # Compare with direct Yao computation initial_state = Yao.zero_state(n) final_state = initial_state |> circuit amplitude_from_yao = (Yao.zero_state(n)' * final_state)[] amplitude_from_network ≈ amplitude_from_yao ``` -------------------------------- ### Clean Build Artifacts Source: https://github.com/quantumbfs/yao.jl/blob/master/CLAUDE.md Removes generated build artifacts and temporary files from the project, ensuring a clean state for subsequent builds or tests. ```bash # Clean build artifacts make clean ``` -------------------------------- ### Create Random State Source: https://github.com/quantumbfs/yao.jl/blob/master/docs/src/man/registers.md Generates a random quantum state for a specified number of qubits and optionally a specific complex number type. ```julia using Yao reg_rand = rand_state(ComplexF32, 3) # a random state ``` -------------------------------- ### Compute Probability Amplitude with Fixed States Source: https://github.com/quantumbfs/yao.jl/blob/master/docs/src/man/yao2einsum.md Creates a tensor network with specified initial and final states to compute a specific probability amplitude. An optimizer can be provided for efficient contraction. ```julia # Create a network with fixed initial and final states network_with_states = Yao.yao2einsum(circuit; initial_state=Dict([i=>0 for i=1:n]), # Start in |00...0⟩ final_state=Dict([i=>0 for i=1:n]), # Measure in |00...0⟩ basis optimizer=Yao.YaoToEinsum.TreeSA() ) viznet(network_with_states) ``` -------------------------------- ### Create Uniform State Source: https://github.com/quantumbfs/yao.jl/blob/master/docs/src/man/registers.md Generates a uniform superposition state for a specified number of qubits and optionally a specific complex number type. `print_table` provides a tabular view. ```julia using Yao reg_uniform = uniform_state(ComplexF32, 3) # a uniform state print_table(reg_uniform) ``` -------------------------------- ### propagate Source: https://github.com/quantumbfs/yao.jl/blob/master/docs/src/man/paulipropagation.md Propagate the observable through the circuit. ```APIDOC ## Function propagate Propagate the observable through the circuit. ### Method `propagate(pc::PauliPropagationCircuit; kwargs...) ### Keyword Arguments - `max_weight`: Maximum Pauli weight to keep (default: no limit) - `min_abs_coeff`: Minimum coefficient magnitude to keep (default: 0) ### Returns `PauliSum` - the propagated observable ``` -------------------------------- ### Hamiltonian Expectation with Pauli Propagation Source: https://github.com/quantumbfs/yao.jl/blob/master/docs/src/man/paulipropagation.md Calculate the expectation value of a multi-term Pauli Hamiltonian for a given circuit using Pauli propagation. ```julia # Multi-term observable hamiltonian = put(n, 1=>X) + 2.0 * kron(n, 1=>Z, 2=>Z) pc2 = yao2paulipropagation(circuit; observable=hamiltonian) exp_val = real(overlapwithzero(propagate(pc2))) println("Hamiltonian expectation: ", exp_val) ``` -------------------------------- ### Quantum Register State Source: https://github.com/quantumbfs/yao.jl/blob/master/docs/src/man/registers.md Functions for querying the state of a quantum register. ```APIDOC ### State Queries ```@docs state basis statevec relaxedvec hypercubic rank3 viewbatch transpose_storage ``` ``` -------------------------------- ### Calculate Gradients with Adjoint Source: https://github.com/quantumbfs/yao.jl/blob/master/docs/src/man/automatic_differentiation.md To obtain gradients for expectation values, append an adjoint (') to the expect function. This returns gradients for both the input register and circuit parameters. ```julia expect'(H, rand_state(10)=>circuit) ``` -------------------------------- ### Create Zero State Source: https://github.com/quantumbfs/yao.jl/blob/master/docs/src/man/registers.md Generates a zero state |000⟩ for a specified number of qubits. `print_table` displays the state in a tabular format. ```julia using Yao reg_zero = zero_state(3) # create a zero state |000⟩ print_table(reg_zero) ``` -------------------------------- ### Measurement Operations on ArrayReg Source: https://github.com/quantumbfs/yao.jl/blob/master/docs/src/man/registers.md Demonstrates measurement operations on ArrayReg. `measure!` collapses the state after measurement, while `measure` does not. Functions like `reorder!`, `invorder!`, and `select!` can be used for state manipulation before or after measurement. ```julia measure!(reg0, 1) # measure the qubit, the state collapses measure!(reg0) # measure all qubits measure(reg0, 3) # measure the qubit at location 3, the state does not collapse (hacky) reorder!(reg0, 7:-1:1) # reorder the qubits measure!(reg0) invorder!(reg0) # reverse the order of qubits measure!(reg0) measure!(RemoveMeasured(), reg0, 2:4) # remove the measured qubits reg0 ``` ```julia reg1 = ghz_state(3) select!(reg1, bit"111") # post-select the |111⟩ state isnormalized(reg1) # check if the state is normalized ```