### Clone Scaluq repository Source: https://github.com/qulacs/scaluq/blob/main/doc/source/tutorials/python/install.md Initial steps to prepare for a source-based installation. ```default git clone https://github.com/qulacs/scaluq cd scaluq ``` -------------------------------- ### Install Project Files and Targets Source: https://github.com/qulacs/scaluq/blob/main/src/CMakeLists.txt This snippet defines the installation rules for ScaluQ. It installs header files, libraries, and CMake configuration files for package management. ```cmake install(DIRECTORY ${PROJECT_SOURCE_DIR}/include/scaluq DESTINATION include/scaluq) install(TARGETS scaluq ${SCALUQ_LIBRARIES} kokkos kokkoscore kokkoscontainers kokkosalgorithms kokkossimd nlohmann_json LIBDL EXPORT scaluqTargets LIBRARY DESTINATION lib PUBLIC_HEADER DESTINATION include) install(EXPORT scaluqTargets FILE scaluq-config.cmake DESTINATION share/cmake/scaluq/ NAMESPACE scaluq::) ``` -------------------------------- ### Install Scaluq via PyPI Source: https://github.com/qulacs/scaluq/blob/main/doc/source/tutorials/python/install.md Standard installation command for the Scaluq package. ```python pip install scaluq ``` -------------------------------- ### Install Scaluq from source with configuration Source: https://github.com/qulacs/scaluq/blob/main/doc/source/tutorials/python/install.md Installation command using environment variables to override default build settings. ```default SCALUQ_USE_CUDA=ON SCALUQ_FLOAT32=OFF pip install . ``` -------------------------------- ### Install Scaluq Source: https://context7.com/qulacs/scaluq/llms.txt Commands to install the library via pip or build from source with GPU support. ```bash pip install scaluq ``` ```bash # Build from source with GPU support git clone https://github.com/qulacs/scaluq cd scaluq SCALUQ_USE_CUDA=ON pip install . ``` -------------------------------- ### Install Scaluq as a C++ Library Source: https://github.com/qulacs/scaluq/blob/main/README.md Standard commands to clone and build the Scaluq static library. ```txt git clone https://github.com/qulacs/scaluq cd scaluq script/configure sudo -E env "PATH=$PATH" ninja -C build install ``` -------------------------------- ### Configure Scaluq Installation Path Source: https://github.com/qulacs/scaluq/blob/main/README.md Install to a custom directory by setting CMAKE_INSTALL_PREFIX. ```txt CMAKE_INSTALL_PREFIX=~/.local script/configure; ninja -C build install ``` -------------------------------- ### Install Scaluq as a Python Library Source: https://github.com/qulacs/scaluq/blob/main/README.md Install the Python package via pip or from source with specific options. ```txt pip install scaluq ``` ```txt git clone https://github.com/qulacs/scaluq cd ./scaluq SCALUQ_USE_CUDA=ON pip install . ``` -------------------------------- ### Run Quantum Circuit Simulation in Python Source: https://github.com/qulacs/scaluq/blob/main/README.md Example demonstrating circuit construction and expectation value calculation using the Python API. ```python from scaluq.default.f64 import * import math n_qubits = 3 state = StateVector.Haar_random_state(n_qubits, 0) circuit = Circuit() circuit.add_gate(gate.X(0)) circuit.add_gate(gate.CNot(0, 1)) circuit.add_gate(gate.Y(1)) circuit.add_gate(gate.RX(1, math.pi / 2)) circuit.update_quantum_state(state) terms = [] terms.append(PauliOperator(1, 0)) observable = Operator(terms) value = observable.get_expectation_value(state) print(value) ``` -------------------------------- ### Configure CMake for Scaluq Source: https://github.com/qulacs/scaluq/blob/main/example_project/CMakeLists.txt Use this configuration to link Scaluq and its dependencies. Ensure the include directories match your local installation paths. ```cmake cmake_minimum_required(VERSION 3.24) project(example) find_package(OpenMP) if(SCALUQ_USE_CUDA) find_package(CUDAToolkit) endif() find_package(Kokkos) find_package(scaluq) add_executable(main main.cpp) target_include_directories(main PUBLIC /usr/local/include/scaluq /usr/local/include/kokkos /usr/local/include/eigen3 /usr/local/include/nlohmann ) target_compile_features(main PUBLIC cxx_std_20) target_compile_options(main PUBLIC -fopenmp) target_compile_definitions(main PUBLIC OPENMP) target_link_libraries(main PUBLIC scaluq::scaluq) ``` -------------------------------- ### Link Libraries and Include Directories Source: https://github.com/qulacs/scaluq/blob/main/src/CMakeLists.txt This snippet configures target libraries to link against Kokkos and nlohmann_json, and sets private include directories for build and installation interfaces. It also adds the Eigen source directory to include paths. ```cmake cmake_minimum_required(VERSION 3.24) foreach(LIBRARY IN LISTS SCALUQ_LIBRARIES) target_link_libraries(${LIBRARY} PUBLIC Kokkos::kokkos nlohmann_json::nlohmann_json ) target_include_directories(${LIBRARY} PRIVATE $ $) target_include_directories(${LIBRARY} PRIVATE ${eigen_SOURCE_DIR}) if(${LIBRARY} STREQUAL scaluq_base) target_sources(${LIBRARY} PRIVATE base/kokkos.cpp base/util/utility.cpp ) else() target_link_libraries(${LIBRARY} PRIVATE scaluq_base) target_sources(${LIBRARY} PRIVATE gate/merge_gate.cpp gate/gate_matrix.cpp gate/update_ops_dense_matrix.cpp gate/update_ops_sparse_matrix.cpp gate/update_ops_standard.cpp state/state_vector.cpp state/state_vector_batched.cpp operator/operator.cpp operator/operator_batched.cpp util/utility.cpp types.cpp ) if(${LIBRARY} MATCHES "scaluq_default_") target_sources(${LIBRARY} PRIVATE circuit/circuit.cpp operator/pauli_operator.cpp gate/gate_pauli.cpp gate/gate_probabilistic.cpp gate/gate_standard.cpp gate/gate.cpp gate/param_gate_pauli.cpp gate/param_gate_probabilistic.cpp gate/param_gate_standard.cpp gate/param_gate.cpp ) endif() endif() endforeach() ``` -------------------------------- ### Get Gate Properties Source: https://github.com/qulacs/scaluq/blob/main/doc/source/tutorials/python/gate.md Retrieve general properties of a gate, such as target and control qubits and their values, using methods of the Gate class. ```python from scaluq.default.f64.gate import H cch = H(0, controls=[1, 2], control_values=[1, 0]) print(cch.target_qubit_list()) # [0] print(cch.control_qubit_list()) # [1, 2] print(cch.control_value_list()) # [1, 0] ``` -------------------------------- ### Get Gate Matrix Source: https://github.com/qulacs/scaluq/blob/main/doc/source/tutorials/python/gate.md Obtain the matrix representation of a gate using `get_matrix`. Control qubits are ignored in this representation. ```python from scaluq.default.f64.gate import H cch = H(0, controls=[1, 2], control_values=[1, 0]) print(cch.get_matrix()) ''' [[ 0.70710678+0.j 0.70710678+0.j] [ 0.70710678+0.j -0.70710678+0.j]] ''' ``` -------------------------------- ### Get Inverse Gate Source: https://context7.com/qulacs/scaluq/llms.txt Obtain the inverse of a gate. For example, the inverse of an S gate is the Sdag gate. ```python s_inv = s_gate.get_inverse() # Returns Sdag gate ``` -------------------------------- ### Initialize and Run Basic C++ Circuit Source: https://context7.com/qulacs/scaluq/llms.txt Demonstrates the standard workflow including initialization, state creation, circuit construction, and expectation value calculation using explicit template parameters. ```cpp #include #include #include #include #include #include int main() { scaluq::initialize(); // Required before any scaluq operations { constexpr scaluq::Precision Prec = scaluq::Precision::F64; constexpr scaluq::ExecutionSpace Space = scaluq::ExecutionSpace::Default; const std::uint64_t n_qubits = 3; // Create random state scaluq::StateVector state = scaluq::StateVector::Haar_random_state(n_qubits, 0); std::cout << state << std::endl; // Build circuit scaluq::Circuit circuit(n_qubits); circuit.add_gate(scaluq::gate::X(0)); circuit.add_gate(scaluq::gate::CNot(0, 1)); circuit.add_gate(scaluq::gate::Y(1)); circuit.add_gate(scaluq::gate::RX(1, std::numbers::pi / 2)); circuit.update_quantum_state(state); // Create observable and measure std::vector> terms; terms.emplace_back(1, 0); // Z on qubit 0 scaluq::Operator observable(terms); auto value = observable.get_expectation_value(state); std::cout << "Expectation: " << value << std::endl; } scaluq::finalize(); // Required at end } ``` -------------------------------- ### Get StateVector Properties Source: https://github.com/qulacs/scaluq/blob/main/doc/source/tutorials/python/state_vector.md Retrieve properties of a StateVector, such as the number of qubits, dimension, amplitudes, and squared norm. ```python from scaluq.default.f64 import StateVector state = StateVector(2) print(state.n_qubits) print(state.dim) print(state.get_amplitudes()) print(state.get_squared_norm()) ``` -------------------------------- ### Create a new Circuit Source: https://github.com/qulacs/scaluq/blob/main/doc/source/tutorials/python/circuit.md Initialize an empty quantum circuit. ```python from scaluq.default.f64 import Circuit nqubits = 2 circuit = Circuit() print(circuit.to_json()) ``` ```default {"gate_list":[]} ``` -------------------------------- ### Get Inverse Gate Source: https://github.com/qulacs/scaluq/blob/main/doc/source/tutorials/python/gate.md Compute the inverse of a gate using `get_inverse`. If the inverse is identical to the original, a shallow copy is returned. ```python from scaluq.default.f64.gate import H, S h = H(0) h_inv = h.get_inverse() print(h_inv) ''' Gate Type: H Target Qubits: {0} Control Qubits: {} Control Value: {} ''' s = S(1) s_inv = s.get_inverse() print(s_inv) ''' Gate Type: Sdag Target Qubits: {0} Control Qubits: {} Control Value: {} ''' ``` -------------------------------- ### Run Quantum Circuit Simulation in C++ Source: https://github.com/qulacs/scaluq/blob/main/README.md Basic usage of the C++ API including state initialization, gate application, and expectation value calculation. ```cpp #include #include #include #include #include #include int main() { scaluq::initialize(); // must be called before using any scaluq methods { constexpr scaluq::Precision Prec = scaluq::Precision::F64; constexpr scaluq::ExecutionSpace Space = scaluq::ExecutionSpace::Default; const std::uint64_t n_qubits = 3; scaluq::StateVector state = scaluq::StateVector::Haar_random_state(n_qubits, 0); std::cout << state << std::endl; scaluq::Circuit circuit(n_qubits); circuit.add_gate(scaluq::gate::X(0)); circuit.add_gate(scaluq::gate::CNot(0, 1)); circuit.add_gate(scaluq::gate::Y(1)); circuit.add_gate(scaluq::gate::RX(1, std::numbers::pi / 2)); circuit.update_quantum_state(state); std::vector> terms; terms.emplace_back(1, 0); scaluq::Operator observable(terms); auto value = observable.get_expectation_value(state); std::cout << value << std::endl; } scaluq::finalize(); // must be called last } ``` -------------------------------- ### Hamiltonian Construction and Expectation Values Source: https://context7.com/qulacs/scaluq/llms.txt Demonstrates how to construct Hamiltonians from Pauli terms, optimize them by combining like terms, and compute expectation values for a given state or transition amplitudes between states. ```python from scaluq.default.f64 import Operator, PauliOperator, StateVector # Create terms for Hamiltonian H = 0.5*Z0Z1 + 0.3*X0 + 0.2*Y1 terms = [ PauliOperator("Z 0 Z 1", coef=0.5), PauliOperator("X 0", coef=0.3), PauliOperator("Y 1", coef=0.2) ] # Build operator hamiltonian = Operator(terms) print(hamiltonian) # Add more terms hamiltonian.add_operator(Operator([PauliOperator("Z 0", coef=0.1)])) # Optimize by combining like terms h_ising = Operator([ PauliOperator("Z 0 Z 1", coef=0.5), PauliOperator("Z 0 Z 1", coef=0.3) # Same Pauli string ]) h_ising.optimize() # Combines to (0.8+0j) Z0 Z1 print(h_ising) # Compute expectation value state = StateVector.Haar_random_state(2, seed=42) exp_value = hamiltonian.get_expectation_value(state) print(f"Expectation value: {exp_value}") # Compute transition amplitude phi = StateVector.Haar_random_state(2, seed=0) psi = StateVector.Haar_random_state(2, seed=1) trans_amp = hamiltonian.get_transition_amplitude(phi, psi) print(f"Transition amplitude: {trans_amp}") ``` -------------------------------- ### Create Basic Gates Source: https://github.com/qulacs/scaluq/blob/main/doc/source/tutorials/python/gate.md Instantiate common quantum gates like X, Swap, and RX using factory functions. DenseMatrix gates can be created with custom unitary matrices. ```python from scaluq.default.f64.gate import X, Swap, RX, DenseMatrix import math import numpy as np x = X(0) # X gate with target 0 swap = Swap(2, 4) # Swap gate with target 2, 4 rx = RX(1, math.pi/4) # RX(pi/4) gate with target 1 mat = np.array([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]]) # DenseMatrix gate with certain unitary matrix and target 1,2 mat_gate = DenseMatrix([1, 2], mat, is_unitary=True) ``` -------------------------------- ### Dynamically Select Precision and Execution Space in Python Source: https://context7.com/qulacs/scaluq/llms.txt Shows how to import specific submodules or use importlib to dynamically switch between different precision levels and execution backends. ```python # Python: Import from precision/space-specific submodule from scaluq.default.f64 import StateVector, Circuit # GPU if CUDA, else CPU from scaluq.host.f32 import StateVector as SV32 # Always CPU, 32-bit from scaluq.host_serial.f64 import StateVector # Sequential CPU # Dynamic selection using importlib import importlib def get_scaluq_module(precision='f64', space='default'): """Dynamically load scaluq module with specified precision and space. Precision: 'f16', 'f32', 'f64', 'bf16' Space: 'default' (GPU if available), 'host' (CPU), 'host_serial' (sequential) """ return importlib.import_module(f'scaluq.{space}.{precision}') # Example: Select based on application needs scaluq_module = get_scaluq_module(precision='f32', space='default') StateVector = scaluq_module.StateVector gate = scaluq_module.gate state = StateVector(3) x = gate.X(0) x.update_quantum_state(state) print(state) ``` -------------------------------- ### Build Scaluq with CUDA Support Source: https://github.com/qulacs/scaluq/blob/main/README.md Enable CUDA acceleration during the build process. ```txt SCALUQ_USE_CUDA=ON script/configure; sudo env -E "PATH=$PATH" ninja -C build install ``` -------------------------------- ### Configure Scaluq Test Executable with CMake Source: https://github.com/qulacs/scaluq/blob/main/tests/CMakeLists.txt Defines the test executable, links required libraries, and sets up Google Test discovery. ```cmake cmake_minimum_required(VERSION 3.24) include(GoogleTest) file(GLOB_RECURSE ALL_TEST_SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/*.[ch]pp ) if(NOT SCALUQ_TEST_SOURCES STREQUAL "ALL" AND DEFINED SCALUQ_TEST_SOURCES) add_executable(scaluq_test ${SCALUQ_TEST_SOURCES} ) else() add_executable(scaluq_test ${ALL_TEST_SOURCES} ) endif() target_link_libraries(scaluq_test PUBLIC scaluq Kokkos::kokkos GTest::gtest_main Eigen3::Eigen nlohmann_json::nlohmann_json ) target_include_directories(scaluq_test PRIVATE $ $) target_include_directories(scaluq_test PRIVATE ${eigen_SOURCE_DIR}) gtest_discover_tests(scaluq_test DISCOVERY_MODE PRE_TEST) ``` -------------------------------- ### Batch State Processing with StateVectorBatched Source: https://context7.com/qulacs/scaluq/llms.txt Illustrates how to process multiple quantum states simultaneously using StateVectorBatched for efficient parallel computation. Shows creation, individual state setting, and applying circuits to all states. ```python from scaluq.default.f64 import StateVectorBatched, StateVector, Circuit from scaluq.default.f64.gate import H, ParamRX import math batch_size = 3 n_qubits = 2 # Create batch of states (all initialized to |00>) states = StateVectorBatched(batch_size, n_qubits) print(states) # Set individual states in batch states.set_state_vector_at(0, StateVector.Haar_random_state(n_qubits, seed=0)) states.set_state_vector_at(1, StateVector.Haar_random_state(n_qubits, seed=1)) # Get state from batch (copy vs view) state_copy = states.get_state_vector_at(0) # Returns copy state_view = states.view_state_vector_at(0) # Returns view (shared memory) # Modify view affects original batch state_view.set_computational_basis(3) print(states.get_state_vector_at(0).get_amplitudes()) # Modified # Apply circuit to all states in batch circuit = Circuit() circuit.add_gate(H(0)) circuit.update_quantum_state(states) # Parametric circuit with different params per batch param_circuit = Circuit() param_circuit.add_param_gate(ParamRX(0), "theta") # Different theta for each batch element param_circuit.update_quantum_state(states, theta=[0.0, math.pi/4, math.pi/2]) ``` -------------------------------- ### Implement VQE Algorithm in Python Source: https://context7.com/qulacs/scaluq/llms.txt Provides a template for a Variational Quantum Eigensolver, including ansatz circuit generation and Hamiltonian construction. ```python from scaluq.default.f64 import Circuit, StateVector, Operator, PauliOperator from scaluq.default.f64.gate import H, ParamRY, CX import math def create_ansatz(n_qubits: int, n_layers: int) -> Circuit: """Create hardware-efficient ansatz circuit.""" circuit = Circuit() param_idx = 0 for layer in range(n_layers): # Rotation layer for q in range(n_qubits): circuit.add_param_gate(ParamRY(q), f"theta_{param_idx}") param_idx += 1 # Entangling layer for q in range(n_qubits - 1): circuit.add_gate(CX(q, q + 1)) return circuit def create_hamiltonian(n_qubits: int) -> Operator: """Create simple Ising Hamiltonian: H = -sum(Z_i Z_{i+1}) - sum(X_i)""" terms = [] for i in range(n_qubits - 1): terms.append(PauliOperator(f"Z {i} Z {i+1}", coef=-1.0)) for i in range(n_qubits): terms.append(PauliOperator(f"X {i}", coef=-0.5)) return Operator(terms) # Setup n_qubits = 4 n_layers = 2 ansatz = create_ansatz(n_qubits, n_layers) hamiltonian = create_hamiltonian(n_qubits) ``` -------------------------------- ### Add and Use Parametric Gates Source: https://context7.com/qulacs/scaluq/llms.txt Demonstrates how to add parametric gates to a circuit, retrieve parameter information, and execute the circuit with parameter values using dictionaries or keyword arguments. ```python from scaluq.default.f64 import StateVector, Circuit from scaluq.default.f64.gate import ParamRX, ParamRY import math # Add parametric gates with keys circuit.add_param_gate(ParamRX(0, coef=0.5), "theta") # coef multiplies the parameter circuit.add_param_gate(ParamRX(1), "theta") # Same key = same parameter circuit.add_param_gate(ParamRY(1), "phi") # Get parameter information print(f"Parameter keys: {circuit.key_set()}") # {'theta', 'phi'} print(f"Key at gate 1: {circuit.get_param_key_at(1)}") # 'theta' # Execute with parameter values (dictionary) state = StateVector(n_qubits) params = {"theta": math.pi, "phi": math.pi / 2} circuit.update_quantum_state(state, params) # Execute with keyword arguments state2 = StateVector(n_qubits) circuit.update_quantum_state(state2, theta=math.pi, phi=math.pi/2) print(state.get_amplitudes()) ``` -------------------------------- ### Build Quantum Circuits Sequentially Source: https://context7.com/qulacs/scaluq/llms.txt Construct quantum circuits by adding gates one after another using the `Circuit` class. The circuit can then be applied to a state vector or serialized to JSON. ```python from scaluq.default.f64 import Circuit, StateVector from scaluq.default.f64.gate import H, X, RX, CX import math # Create circuit circuit = Circuit() # Add gates sequentially circuit.add_gate(H(0)) circuit.add_gate(CX(0, 1)) circuit.add_gate(RX(1, math.pi / 4)) # Get circuit properties print(f"Number of gates: {circuit.n_gates()}") # 3 print(f"Circuit depth: {circuit.calculate_depth()}") # 2 print(f"Gate list: {circuit.gate_list()}") # Apply circuit to state n_qubits = 2 state = StateVector(n_qubits) circuit.update_quantum_state(state) print(state.get_amplitudes()) # Serialize circuit to JSON json_str = circuit.to_json() print(json_str) ``` -------------------------------- ### Dynamically Import Scaluq Submodule Source: https://github.com/qulacs/scaluq/blob/main/README.md Import a specific Scaluq submodule based on desired precision and execution space. Ensure the chosen submodule is compatible with your hardware and computational needs. ```python import importlib prec = 'f64' space = 'default' scaluq_sub = importlib.import_module(f'scaluq.{space}.{prec}') StateVector = scaluq_sub.StateVector gate = scaluq_sub.gate state = StateVector(3) x = gate.X(0) x.update_quantum_state(state) print(state) ``` -------------------------------- ### Perform Measurement and Sampling Source: https://context7.com/qulacs/scaluq/llms.txt Calculate probabilities, marginals, entropy, and sample from quantum states. ```python from scaluq.default.f64 import StateVector import math state = StateVector(2) state.load([0.5, 0, 0, math.sqrt(3)/2 * 1j]) # Get probability of measuring |0> on qubit 0 prob_zero_q0 = state.get_zero_probability(0) print(f"P(q0=0): {prob_zero_q0}") # 0.25 # Marginal probability with partial measurement # UNMEASURED constant for qubits not being measured marginal_prob = state.get_marginal_probability([1, StateVector.UNMEASURED]) print(f"Marginal P(q0=1): {marginal_prob}") # 0.75 # Get entropy of the state entropy = state.get_entropy() print(f"Entropy: {entropy}") # Sample from the state distribution samples = state.sampling(1000, seed=42) print(f"Sample counts: {dict(zip(*np.unique(samples, return_counts=True)))}") ``` -------------------------------- ### Run Quantum Circuit Simulation with Omitted Templates in C++ Source: https://github.com/qulacs/scaluq/blob/main/README.md Use SCALUQ_OMIT_TEMPLATE to simplify code by removing explicit template arguments. ```cpp #include #include #include namespace my_scaluq { SCALUQ_OMIT_TEMPLATE(scaluq::Precision::F64, scaluq::ExecutionSpace::Default) } using namespace my_scaluq; int main() { scaluq::initialize(); // must be called before using any scaluq methods { const std::uint64_t n_qubits = 3; StateVector state = StateVector::Haar_random_state(n_qubits, 0); std::cout << state << std::endl; Circuit circuit; circuit.add_gate(gate::X(0)); circuit.add_gate(gate::CNot(0, 1)); circuit.add_gate(gate::Y(1)); circuit.add_gate(gate::RX(1, std::numbers::pi / 2)); circuit.update_quantum_state(state); std::vector terms; terms.emplace_back(1, 0); Operator observable(terms); auto value = observable.get_expectation_value(state); std::cout << value << std::endl; } scaluq::finalize(); // must be called last } ``` -------------------------------- ### Initialize PauliOperator Source: https://github.com/qulacs/scaluq/blob/main/doc/source/tutorials/python/oprator.md Demonstrates three ways to define a Pauli operator: using strings, target qubit/ID lists, or bitmasks. ```py # 1. Initialization via string # Applies X to qubit 0 and Y to qubit 2 p1 = PauliOperator("X 0 Y 2", coef=1.0) # 2. Initialization via target qubit and Pauli ID lists # IDs: 0=I, 1=X, 2=Y, 3=Z p2 = PauliOperator(target_qubit_list=[0, 1, 2], pauli_id_list=[1, 0, 2], coef=1.0) # 3. Initialization via bitmasks # bit_flip_mask: locations of X, phase_flip_mask: locations of Z p3 = PauliOperator(bit_flip_mask=0b101, phase_flip_mask=0b010, coef=1.0) ``` -------------------------------- ### Build Parametric Circuits for QML Source: https://context7.com/qulacs/scaluq/llms.txt Create variational quantum circuits with named parameters using `ParamRX`, `ParamRY`, and `ParamRZ` gates. These are useful for quantum machine learning tasks. ```python from scaluq.default.f64 import Circuit, StateVector from scaluq.default.f64.gate import H, ParamRX, ParamRY, ParamRZ import math n_qubits = 2 circuit = Circuit() # Add regular gate circuit.add_gate(H(0)) ``` -------------------------------- ### Manage StateVector Objects Source: https://context7.com/qulacs/scaluq/llms.txt Initialize, load, and inspect quantum state vectors using the StateVector class. ```python from scaluq.default.f64 import StateVector import numpy as np # Create a 2-qubit state initialized to |00> state = StateVector(2) print(state.get_amplitudes()) # [(1+0j), 0j, 0j, 0j] # Create random Haar state with optional seed random_state = StateVector.Haar_random_state(3, seed=42) # Load custom amplitudes state.load([0.5, 0.5, 0.5, 0.5]) # Equal superposition state.load(np.array([1, 0, 0, 1]) / np.sqrt(2)) # Bell state preparation # Set computational basis state.set_computational_basis(3) # Sets state to |11> print(state.get_amplitudes()) # [0j, 0j, 0j, (1+0j)] # Get state properties print(f"Qubits: {state.n_qubits()}") # 2 print(f"Dimension: {state.dim()}") # 4 print(f"Squared norm: {state.get_squared_norm()}") # 1.0 # Normalize after operations state.load([1, 2, 3, 4]) state.normalize() print(state.get_squared_norm()) # 1.0 ``` -------------------------------- ### Initialize Batched State Vectors Source: https://github.com/qulacs/scaluq/blob/main/doc/source/tutorials/python/batch.md Create a batched state vector by specifying the batch size and number of qubits. This initializes multiple identical state vectors ready for batched operations. ```Python from scaluq.default.f64 import StateVectorBatched batch_size = 3 n_qubits = 2 # Initialize 3 state vectors, each with 2 qubits states = StateVectorBatched(batch_size, n_qubits) print(states) ``` -------------------------------- ### Execute circuit with parameters Source: https://github.com/qulacs/scaluq/blob/main/doc/source/tutorials/python/param.md Apply a circuit to a state vector by providing parameter values via dictionary or keyword arguments. ```python from scaluq.default.f64.gate import H, ParamRX, ParamRY from scaluq.default.f64 import Circuit, StateVector import math n_qubits = 2 circuit = Circuit() state = StateVector(n_qubits) # Initial state |00> circuit.add_param_gate(ParamRX(0,0.5), "angle_x") # coef 0.5 circuit.add_param_gate(ParamRY(1), "angle_y") params_1 = { "angle_x": math.pi, "angle_y": math.pi/2 } #method 1: using a parameter dictionary circuit.update_quantum_state(state, params_1) print(state.get_amplitudes()) #method 2: using keyword arguments state2 = StateVector(n_qubits) circuit.update_quantum_state(state2, angle_x = math.pi, angle_y = math.pi/2) print(state2.get_amplitudes()) ``` ```text [(0.5000000000000001+0j), -0.5j, (0.5+0j), -0.4999999999999999j] [(0.5000000000000001+0j), -0.5j, (0.5+0j), -0.4999999999999999j] ``` -------------------------------- ### Define Pauli Operators Source: https://context7.com/qulacs/scaluq/llms.txt Shows different methods for defining Pauli operators, including string format, target and Pauli ID lists, and bitmasks. Also demonstrates how to access operator properties. ```python from scaluq.default.f64 import PauliOperator # Method 1: String format "PAULI qubit PAULI qubit ..." pauli1 = PauliOperator("X 0 Y 2", coef=1.0) # X on q0, Y on q2 pauli2 = PauliOperator("Z 0 Z 1", coef=0.5) # ZZ interaction # Method 2: Target list and Pauli ID list (0=I, 1=X, 2=Y, 3=Z) pauli3 = PauliOperator( target_qubit_list=[0, 1, 2], pauli_id_list=[1, 0, 2], # X on q0, I on q1, Y on q2 coef=1.0 ) # Method 3: Bitmasks (advanced) # bit_flip_mask: locations of X, phase_flip_mask: locations of Z # X = bit_flip only, Y = both, Z = phase_flip only pauli4 = PauliOperator( bit_flip_mask=0b101, # X on q0 and q2 phase_flip_mask=0b010, # Z on q1 coef=1.0 ) # Get operator properties print(f"Coefficient: {pauli1.coef()}") print(f"Target qubits: {pauli1.target_qubit_list()}") print(f"Pauli IDs: {pauli1.pauli_id_list()}") ``` -------------------------------- ### Initialize StateVector Source: https://github.com/qulacs/scaluq/blob/main/doc/source/tutorials/python/state_vector.md Initialize a StateVector with a specified number of qubits. The state is initially set to |0...0>. ```python from scaluq.default.f64 import StateVector state = StateVector(2) print(state) ``` -------------------------------- ### Manage Operator Terms Source: https://github.com/qulacs/scaluq/blob/main/doc/source/tutorials/python/oprator.md Shows how to aggregate multiple Pauli operators into a single Operator and optimize it by merging identical terms. ```py from scaluq.default.f64 import Operator, PauliOperator #prepare two pauli pauli1 = PauliOperator("Z 0 Z 1", coef=0.5) # (0.5 + 0.0j) Z0 Z1 pauli2 = PauliOperator("Z 0 Z 1", coef=0.3) # (0.3 + 0.0j) Z0 Z1 terms = [pauli1, pauli2] op1 = Operator(terms) print(op1) # (0.5 + 0.0j) Z0 Z1,(0.3 + 0.0j) Z0 Z1 # you can optimize the operator by merging terms with the same Pauli string op1.optimize() print(op1) # (0.8 + 0.0j) Z0 Z1 ``` -------------------------------- ### Calculating Probabilistic Measures Source: https://github.com/qulacs/scaluq/blob/main/doc/source/tutorials/python/state_vector.md Illustrates how to compute zero-basis probabilities and marginal probabilities for a given StateVector. ```python import math from scaluq.default.f64 import StateVector state = StateVector.uninitialized_state(2) vec = [1/2, 0, 0, math.sqrt(3)/2 * 1j] state.load(vec) print("zero probability of 0:", state.get_zero_probability(0)) assert abs(state.get_zero_probability(0) - (abs(vec[0])**2 + abs(vec[2])**2)) < 1e-9 print("zero probability of 1:", state.get_zero_probability(1)) assert abs(state.get_zero_probability(1) - (abs(vec[0])**2 + abs(vec[1])**2)) < 1e-9 print("marginal probability of [1, UNMEASURED]:", state.get_marginal_probability([1, StateVector.UNMEASURED])) assert abs(state.get_marginal_probability([1, StateVector.UNMEASURED]) - (abs(vec[1])**2 + abs(vec[3])**2)) < 1e-9 ``` -------------------------------- ### Configure clang-format for C++ Source Files Source: https://github.com/qulacs/scaluq/blob/main/CMakeLists.txt This CMake script configures the clang-format tool to format C++ source files within the ScaluQ project. It identifies all relevant source files and sets up a custom target named 'format' to apply the formatting. ```cmake find_program(CLANG_FORMAT "clang-format") if(CLANG_FORMAT) file(GLOB_RECURSE ALL_CXX_SOURCE_FILES ${CMAKE_CURRENT_SOURCE_DIR}/scaluq/*.[ch]pp ${CMAKE_CURRENT_SOURCE_DIR}/scaluq/*.[ch] ${CMAKE_CURRENT_SOURCE_DIR}/test/*.[ch]pp ${CMAKE_CURRENT_SOURCE_DIR}/test/*.[ch] ${CMAKE_CURRENT_SOURCE_DIR}/python/*.[ch]pp ${CMAKE_CURRENT_SOURCE_DIR}/python/*.[ch] ) add_custom_target( format COMMAND clang-format -style=file -i ${ALL_CXX_SOURCE_FILES} ) endif() ``` -------------------------------- ### Define Custom Matrix Gates and Simulate Noise Source: https://context7.com/qulacs/scaluq/llms.txt Create custom unitary gates using dense matrices and simulate noise channels like BitFlip, Dephasing, and Depolarizing. Probabilistic gates allow for applying different gates with specified probabilities. ```python from scaluq.default.f64 import StateVector from scaluq.default.f64.gate import ( DenseMatrix, Probabilistic, I, BitFlipNoise, DephasingNoise, DepolarizingNoise ) import numpy as np state = StateVector(2) # Custom unitary matrix gate hadamard_matrix = np.array([[1, 1], [1, -1]]) / np.sqrt(2) custom_h = DenseMatrix([0], hadamard_matrix, is_unitary=True) custom_h.update_quantum_state(state) # Multi-qubit custom gate cnot_matrix = np.array([ [1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0] ]) custom_cnot = DenseMatrix([0, 1], cnot_matrix, is_unitary=True) # Probabilistic gate (noise simulation) from scaluq.default.f64.gate import X, Y, Z prob_gate = Probabilistic( distribution=[0.1, 0.1, 0.1, 0.7], # Probabilities gate_list=[X(0), Y(0), Z(0), I()] # Gates to apply ) # Built-in noise channels bit_flip = BitFlipNoise(target=0, error_rate=0.01) dephasing = DephasingNoise(target=0, error_rate=0.01) depolarizing = DepolarizingNoise(target=0, error_rate=0.03) # Apply noise to state depolarizing.update_quantum_state(state) ``` -------------------------------- ### Performing StateVector Arithmetic Source: https://github.com/qulacs/scaluq/blob/main/doc/source/tutorials/python/state_vector.md Shows how to add state vectors with coefficients and perform scalar multiplication on a StateVector. ```python import math from scaluq.default.f64 import StateVector phi = StateVector(2) print("phi:", phi.get_amplitudes()) psi = StateVector.uninitialized_state(2) psi.set_computational_basis(3) print("psi:", psi.get_amplitudes()) phi.add_state_vector_with_coef(1j, psi) print("phi after added psi:", phi.get_amplitudes()) phi.multiply_coef(1 / math.sqrt(2)) print("phi after multiplied coef:", phi.get_amplitudes()) ``` -------------------------------- ### Copying a StateVector Source: https://github.com/qulacs/scaluq/blob/main/doc/source/tutorials/python/state_vector.md Demonstrates creating a detached copy of a state vector from a batch and modifying it independently. ```python state1_copy = states.get_state_vector_at(1) state1_copy.set_computational_basis(2) print("batch 1 in states:", states.get_state_vector_at(1).get_amplitudes()) print("detached copy:", state1_copy.get_amplitudes()) ``` -------------------------------- ### Apply Standard Quantum Gates Source: https://context7.com/qulacs/scaluq/llms.txt Construct and apply immutable quantum gates to state vectors. ```python from scaluq.default.f64 import StateVector from scaluq.default.f64.gate import X, Y, Z, H, S, T, RX, RY, RZ, Swap import math state = StateVector(3) # Single-qubit Pauli gates x_gate = X(0) # X gate on qubit 0 y_gate = Y(1) # Y gate on qubit 1 z_gate = Z(2) # Z gate on qubit 2 # Hadamard gate h_gate = H(0) h_gate.update_quantum_state(state) print(state.get_amplitudes()) # Superposition on qubit 0 # Phase gates s_gate = S(0) # S gate (π/2 phase) t_gate = T(0) # T gate (π/4 phase) # Rotation gates with angle in radians rx_gate = RX(0, math.pi / 2) # Rotate around X-axis ry_gate = RY(1, math.pi / 4) # Rotate around Y-axis rz_gate = RZ(2, math.pi) # Rotate around Z-axis # Two-qubit SWAP gate swap_gate = Swap(0, 1) # Get gate properties print(f"Target qubits: {x_gate.target_qubit_list()}") print(f"Gate matrix:\n{h_gate.get_matrix()}") ``` -------------------------------- ### Define Scaluq Executable CMake Function Source: https://github.com/qulacs/scaluq/blob/main/exe/CMakeLists.txt This function automates the creation of executables, linking necessary dependencies like Eigen, Kokkos, and nlohmann_json. It conditionally links GTest if SCALUQ_USE_TEST is enabled. ```cmake cmake_minimum_required(VERSION 3.24) function(exe name) add_executable(${name} ${name}.cpp) target_link_libraries(${name} PRIVATE scaluq Eigen3::Eigen Kokkos::kokkos nlohmann_json::nlohmann_json ) if (SCALUQ_USE_TEST) target_link_libraries(${name} PRIVATE GTest::gtest_main) endif(SCALUQ_USE_TEST) target_include_directories(${name} PRIVATE ${PROJECT_SOURCE_DIR}/include) endfunction() exe(main) ``` -------------------------------- ### Parametric Circuit Execution with Batched States Source: https://github.com/qulacs/scaluq/blob/main/doc/source/tutorials/python/batch.md Execute parametric circuits on batched states, applying different parameter values for each batch element. This is useful for exploring parameter spaces efficiently. ```Python from scaluq.default.f64 import Circuit, StateVectorBatched from scaluq.default.f64.gate import ParamRX import math states = StateVectorBatched(batch_size=2, n_qubits=1) circuit = Circuit(1) # set a parameterized RX gate on qubit 0 with parameter name "theta" circuit.add_param_gate(ParamRX(0), "theta") # Batch 0: theta=0.0, Batch 1: theta=pi/2 circuit.update_quantum_state(states, theta=[0.0, math.pi / 2]) print(states) ``` -------------------------------- ### Execute Linear Algebra Operations Source: https://context7.com/qulacs/scaluq/llms.txt Perform vector arithmetic and inner product calculations on quantum states. ```python from scaluq.default.f64 import StateVector import math # Create two states phi = StateVector(2) phi.set_zero_state() # |00> psi = StateVector(2) psi.set_computational_basis(3) # |11> # Add state with coefficient: phi = phi + c*psi phi.add_state_vector_with_coef(1j, psi) print(phi.get_amplitudes()) # [(1+0j), 0j, 0j, 1j] # Multiply by coefficient phi.multiply_coef(1 / math.sqrt(2)) print(phi.get_amplitudes()) # Normalized Bell state # Calculate inner product state1 = StateVector(2) state1.load([0.5, 0, 0, 0.5]) # (|00> + |11>)/sqrt(2) state2 = StateVector(2) state2.load([0.5, 0, 0, -0.5]) # (|00> - |11>)/sqrt(2) inner = StateVector.inner_product(state1, state2) print(f"Inner product: {inner}") # 0j (orthogonal states) ``` -------------------------------- ### Load StateVector from List Source: https://github.com/qulacs/scaluq/blob/main/doc/source/tutorials/python/state_vector.md Load amplitudes into the StateVector from a list of complex numbers. ```python from scaluq.default.f64 import StateVector state = StateVector(2) state.load([0.5, 0.5, -0.5, 0.5]) print("loaded state:", state.get_amplitudes()) ``` -------------------------------- ### Initialize Batched Operators Source: https://github.com/qulacs/scaluq/blob/main/doc/source/tutorials/python/batch.md Create a batched operator to calculate expectation values for multiple different operators against a single state vector. This is useful for evaluating multiple observables simultaneously. ```Python from scaluq.default.f64 import OperatorBatched, PauliOperator, StateVector # Initialize a random state vector using Haar measure state = StateVector.Haar_random_state(2) # get expectation value pauli1 = PauliOperator("Z 0 X 1", coef=1.0) pauli2 = PauliOperator("X 0 Z 1", coef=0.5) pauli3 = PauliOperator("Y 0 Y 1", coef=0.8) op = OperatorBatched([[pauli1], [pauli2], [pauli3]]) # batch of 3 operators exp_val = op.get_expectation_value(state) print(f"Expectation value: {exp_val}") # e.g., [(-0.09541586059802383+0j), (-0.0537398701798849+0j), (0.47697004250289277+0j)] ``` -------------------------------- ### Batch Expectation Values with OperatorBatched Source: https://context7.com/qulacs/scaluq/llms.txt Shows how to efficiently compute expectation values for multiple operators simultaneously using OperatorBatched. This is useful for evaluating several Hamiltonians or terms at once. ```python from scaluq.default.f64 import OperatorBatched, PauliOperator, StateVector # Create state state = StateVector.Haar_random_state(2, seed=42) # Define multiple operators to evaluate op1_terms = [PauliOperator("Z 0 X 1", coef=1.0)] op2_terms = [PauliOperator("X 0 Z 1", coef=0.5)] op3_terms = [PauliOperator("Y 0 Y 1", coef=0.8)] # Create batched operator batch_ops = OperatorBatched([op1_terms, op2_terms, op3_terms]) # Get all expectation values at once exp_values = batch_ops.get_expectation_value(state) print(f"Expectation values: {exp_values}") ```