### Install MindQuantum via Pip Source: https://github.com/mindspore-ai/mindquantum/blob/master/docs/source/installation.rst Use this command to install the pre-compiled binary package from PyPI. ```bash python3 -m pip install --user mindquantum ``` -------------------------------- ### Build Script Example Source: https://github.com/mindspore-ai/mindquantum/blob/master/docs/source/installation.rst Example calls to the build script with various options for GPU support, C++ compilation, third-party libraries, and virtual environment configuration. ```bash build.sh build.sh --gpu build.sh --cxx --with-boost --without-gmp --venv=/tmp/venv ``` -------------------------------- ### Install dependencies in MSYS2-MINGW64 Source: https://github.com/mindspore-ai/mindquantum/blob/master/docs/source/installation.rst Update package databases and install MinGW64-specific toolchains and libraries. ```bash pacman -Syu pacman -S git patch make mingw-w64-x86_64-toolchain mingw-w64-x86_64-cmake \ mingw-w64-x86_64-python mingw-w64-x86_64-python-pip ``` -------------------------------- ### Install GCC Compiler Source: https://github.com/mindspore-ai/mindquantum/blob/master/CONTRIBUTING.md Commands to install the GCC compiler suite on Ubuntu and CentOS systems. ```shell # Ubuntu install apt-get update apt-get install gcc apt-get install build-essential # Centos install yum install gcc gcc-c++ # output gcc version,verify successful installation gcc --version ``` -------------------------------- ### Compile and Install MindQuantum via Build Script Source: https://github.com/mindspore-ai/mindquantum/blob/master/README.md Compile the source code using the provided build script and install the resulting wheel package. ```bash cd ~/mindquantum bash build.sh cd output pip install mindquantum-*.whl ``` -------------------------------- ### Install Python Include Directory Source: https://github.com/mindspore-ai/mindquantum/blob/master/ccsrc/python/mqbackend/CMakeLists.txt Installs the Python-specific include directory to the specified installation path. ```cmake install(DIRECTORY ${CMAKE_CURRENT_LIST_DIR}/include/python DESTINATION ${MQ_INSTALL_INCLUDEDIR}) ``` -------------------------------- ### Install MindQuantum via Pip Source: https://github.com/mindspore-ai/mindquantum/blob/master/README_CN.md Use this command to install the MindQuantum package using pip. Ensure MindSpore version 1.4.0 or higher is installed first. ```bash pip install mindquantum ``` -------------------------------- ### View Local Build Script Help Source: https://github.com/mindspore-ai/mindquantum/blob/master/docs/source/installation.rst Displays the help message for the local build script, detailing available options for environment setup and compilation. ```bash Build MindQunantum locally (in-source build) This is mainly relevant for developers that do not want to always have to reinstall the Python package This script will create a Python virtualenv in the MindQuantum root directory and then build all the C++ Python modules and place the generated libraries in their right locations within the MindQuantum folder hierarchy so Python knows how to find them. A pth-file will be created in the virtualenv site-packages directory so that the MindQuantum root folder will be added to the Python PATH without the need to modify PYTHONPATH. Usage: build_locally.sh [options] [-- cmake_options] Options: -h,--help Show this help message and exit -n Dry run; only print commands but do not execute them -B,--build=[dir] Specify build directory Defaults to: /home/user/mindquantum/build --ccache If ccache or sccache are found within the PATH, use them with CMake --clean-3rdparty Clean 3rd party installation directory --clean-all Clean everything before building. Equivalent to --clean-venv --clean-builddir --clean-builddir Delete build directory before building --clean-cache Re-run CMake with a clean CMake cache --clean-venv Delete Python virtualenv before building --config=[dir] Path to INI configuration file with default values for the parameters ``` -------------------------------- ### Execute build_locally.sh with various configurations Source: https://github.com/mindspore-ai/mindquantum/blob/master/docs/source/installation.rst Examples of invoking the build script with different flags for GPU support, dependency management, and custom CMake arguments. ```bash build_locally.sh -B build ``` ```bash build_locally.sh -B build --gpu ``` ```bash build_locally.sh -B build --cxx --with-boost --without-gmp --venv=/tmp/venv ``` ```bash build_locally.sh -B build -- -DCMAKE_CUDA_COMPILER=/opt/cuda/bin/nvcc ``` ```bash build_locally.sh -B build --cxx --gpu -- \ -DCMAKE_NVCXX_COMPILER=/opt/nvidia/hpc_sdk/Linux_x86_64/22.3/compilers/bin/nvc++ ``` -------------------------------- ### Warm Start State Preparation Source: https://github.com/mindspore-ai/mindquantum/blob/master/example/Adapt-Clifford/Adapt-Clifford-for-MaxCut.ipynb Prepares an initial quantum state using X gates and calculates its expectation value. Then applies Hadamard gates and adds a barrier. Requires Circuit, X, H, and get_exp. ```python def warm_state_qualitative(target_qubits, ham, nodes, sim): circ = Circuit().un(X, target_qubits) exp = get_exp(circ, ham, sim) circ.un(H, range(nodes)) circ.barrier() return circ, exp ``` -------------------------------- ### Verify MindQuantum Installation Source: https://github.com/mindspore-ai/mindquantum/blob/master/README_CN.md Run this Python command to check if MindQuantum has been successfully imported. An error indicates a failed installation. ```python python -c 'import mindquantum' ``` -------------------------------- ### Verify CMake Installation Source: https://github.com/mindspore-ai/mindquantum/blob/master/CONTRIBUTING.md Check the installed version of CMake to ensure it meets the minimum requirements. ```shell cmake --version >>> cmake version 3.24.2 ``` -------------------------------- ### Verify GCC Installation on Windows Source: https://github.com/mindspore-ai/mindquantum/blob/master/CONTRIBUTING.md Check the installed version of GCC in the Windows command prompt. ```shell C:\Users\xx> gcc --version gcc (x86_64-win32-seh-rev0, Built by MinGW-W64 project) 8.1.0 Copyright (C) 2018 Free Software Foundation, Inc. ``` -------------------------------- ### VQE Example with Hardware Efficient Ansatz Source: https://context7.com/mindspore-ai/mindquantum/llms.txt Sets up and optimizes a Variational Quantum Eigensolver (VQE) using a Hardware Efficient Ansatz and a simple Hamiltonian. Uses scipy.optimize.minimize for optimization. ```python # VQE example with HEA n_qubits = 4 ansatz = HardwareEfficientAnsatz(n_qubits=n_qubits, single_rot_gate_seq=['ry'], entangle_gate='CNOT', depth=2) # Simple Hamiltonian ham = sum([QubitOperator(f'Z{i} Z{(i+1)%n_qubits}') for i in range(n_qubits)]) ham += 0.5 * sum([QubitOperator(f'X{i}') for i in range(n_qubits)]) hamiltonian = Hamiltonian(ham) # Setup VQE sim = Simulator('mqvector', n_qubits) grad_ops = sim.get_expectation_with_grad(hamiltonian, ansatz.circuit) def vqe_objective(params): exp, grad = grad_ops(params.reshape(1, -1)) return np.real(exp[0, 0]), np.real(grad[0, 0]) # Optimize from scipy.optimize import minimize x0 = np.random.uniform(-np.pi, np.pi, len(ansatz.circuit.params_name)) result = minimize(vqe_objective, x0, method='L-BFGS-B', jac=True, options={'maxiter': 200}) print(f"VQE ground state energy: {result.fun:.6f}") ``` -------------------------------- ### Install Python on Windows via Chocolatey Source: https://github.com/mindspore-ai/mindquantum/blob/master/docs/source/installation.rst Install a specific version of Python and create a symbolic link for the executable. ```powershell choco install -y python3 --version 3.9.11 cmd /c mklink "C:\Python38\python3.exe" "C:\Python38\python.exe" ``` -------------------------------- ### Install Build Tools on Ubuntu/Debian Source: https://github.com/mindspore-ai/mindquantum/blob/master/docs/source/installation.rst Installs essential build tools, including g++, for compiling C++ projects on Ubuntu or Debian-based systems. ```bash sudo apt-get install build-essential ``` -------------------------------- ### Install Development Tools on CentOS 7 Source: https://github.com/mindspore-ai/mindquantum/blob/master/docs/source/installation.rst Installs EPEL repository, SCL, devtoolset-8, and essential build tools like gcc-c++, make, and git on CentOS 7. ```bash sudo yum install -y epel-release sudo yum install -y centos-release-scl sudo yum install -y devtoolset-8 sudo yum check-update -y scl enable devtoolset-8 bash sudo yum install -y gcc-c++ make git ``` -------------------------------- ### Install CMake using APT on Ubuntu Source: https://github.com/mindspore-ai/mindquantum/blob/master/docs/source/installation.rst Installs CMake using the Advanced Package Tool (APT) for systems where the default version is sufficient. ```bash sudo apt-get install cmake ``` -------------------------------- ### Install CMake via pip on MinGW64 Source: https://github.com/mindspore-ai/mindquantum/blob/master/docs/source/installation.rst Install the CMake build tool using the Python package manager. ```bash python -m pip install --user cmake ``` -------------------------------- ### Sample Optimized Circuit Source: https://context7.com/mindspore-ai/mindquantum/llms.txt Demonstrates sampling an optimized quantum circuit with provided parameters and shots. Requires a pre-defined circuit and simulation setup. ```python sim.reset() from mindquantum.core.gates import Measure measure_circuit = qaoa.circuit + sum([Measure(f'q{i}').on(i) for i in range(qaoa.circuit.n_qubits)]) samples = sim.sampling(measure_circuit, pr=dict(zip(qaoa.circuit.params_name, result.x)), shots=1000) print(f"Sampling results: {samples}") ``` -------------------------------- ### Install Windows build tools via Chocolatey Source: https://github.com/mindspore-ai/mindquantum/blob/master/docs/source/installation.rst Install Visual Studio workloads, SDKs, and build utilities using the Chocolatey package manager. ```powershell choco install -y visualstudio2019-workload-vctools --includeOptional choco install -y windows-sdk-10-version-2004-all choco install -y cmake git ``` -------------------------------- ### Install dependencies in MSYS2-MSYS Source: https://github.com/mindspore-ai/mindquantum/blob/master/docs/source/installation.rst Update package databases and install development tools within the MSYS2-MSYS shell. ```bash pacman -Syu pacman -S git base-devel gcc cmake python-devel python-pip gmp-devel ``` -------------------------------- ### Implement Quantum Fourier Transform (QFT) Source: https://context7.com/mindspore-ai/mindquantum/llms.txt Demonstrates the creation and application of the Quantum Fourier Transform circuit using MindQuantum's library. Includes examples of QFT on different states, sparse QFT, and inverse QFT. Requires importing qft, Simulator, Circuit, X, and numpy. ```python from mindquantum.algorithm.library import qft from mindquantum.simulator import Simulator import numpy as np # Create QFT circuit for 3 qubits qft_circuit = qft([0, 1, 2]) print(f"QFT circuit:\n{qft_circuit}") # Apply QFT and observe uniform superposition from |000> sim = Simulator('mqvector', 3) sim.apply_circuit(qft_circuit) print(f"QFT of |000>:\n{sim.get_qs(ket=True)}") # Output: Equal superposition of all basis states # Prepare a computational basis state and apply QFT sim.reset() from mindquantum.core.circuit import Circuit from mindquantum.core.gates import X # Prepare |101> prep = Circuit().x(0).x(2) sim.apply_circuit(prep + qft_circuit) qs = sim.get_qs() print(f"QFT of |101>: {np.abs(qs)**2}") # Probability distribution # Inverse QFT inverse_qft = qft_circuit.hermitian() sim.reset() sim.apply_circuit(qft_circuit + inverse_qft) print(f"QFT followed by inverse QFT: {sim.get_qs(ket=True)}") # Output: 1|000> (back to initial state) # QFT on non-adjacent qubits qft_sparse = qft([0, 2, 4]) # QFT on qubits 0, 2, 4 print(f"Sparse QFT circuit depth: {qft_sparse.n_qubits}") ``` -------------------------------- ### Install Python 3 and Pip on CentOS 7 Source: https://github.com/mindspore-ai/mindquantum/blob/master/docs/source/installation.rst Installs Python 3, its development headers, and pip on CentOS 7. ```bash sudo yum install -y python3 python3-devel python3-pip ``` -------------------------------- ### Run Adapt Clifford with Random Start Source: https://github.com/mindspore-ai/mindquantum/blob/master/example/Adapt-Clifford/Adapt-Clifford-for-MaxCut.ipynb Executes the adapt_clifford function with a randomly chosen starting qubit and prints the result and used mixers. Requires adapt_clifford, random, and print. ```python import random t = random.choice(range(nodes)) res, circ, mixers_used = adapt_clifford(nodes, t, ham) print(t, res) print(mixers_used) ``` -------------------------------- ### Install Development Tools on CentOS 8 Source: https://github.com/mindspore-ai/mindquantum/blob/master/docs/source/installation.rst Installs EPEL repository and essential build tools like gcc-c++, make, and git on CentOS 8. ```bash sudo yum install -y epel-release sudo yum check-update -y sudo yum install -y gcc-c++ make git ``` -------------------------------- ### Figure 7.1 Example Source: https://github.com/mindspore-ai/mindquantum/blob/master/example/QAOAs_advantages/QAOAs_advantages.ipynb Example function to reproduce the first figure, using a specific 'easy' J matrix and a time parameter. ```python def fig7_1(t=0.5): """Use the J in the 'easy' instance""" num_layers = 2000 J = np.array( [ [ 0.0, 0.42132292, -0.25571582, -0.16267926, -0.77219702, 0.06310006, 0.03975859, 0.14472543, 0.52842128, 0.2399146, -0.5426827, ], [ 0.42132292, 0.0, -0.04705895, -0.28587394, 0.50008779, 0.19371417, 0.43070882, 0.21708425, -0.09432905, -0.07647162, 0.0410539, ], ``` -------------------------------- ### Install Xcode Command Line Tools on macOS Source: https://github.com/mindspore-ai/mindquantum/blob/master/docs/source/installation.rst Installs the necessary command line developer tools for macOS, required for compilation. ```bash xcode-select --install ``` -------------------------------- ### Install Python 3 and Pip on ArchLinux/Manjaro Source: https://github.com/mindspore-ai/mindquantum/blob/master/docs/source/installation.rst Installs Python 3 and its package manager, pip, on Arch Linux or Manjaro. ```bash sudo pacman -Syu python python-pip ``` -------------------------------- ### Install CMake using Pip on CentOS 7 Source: https://github.com/mindspore-ai/mindquantum/blob/master/docs/source/installation.rst Installs CMake using pip for CentOS 7 systems. ```bash sudo python3 -m pip install cmake ``` -------------------------------- ### Install Python and LLVM with Homebrew on macOS Source: https://github.com/mindspore-ai/mindquantum/blob/master/docs/source/installation.rst Installs Python and LLVM (compiler infrastructure) using Homebrew. LLVM is preferred over GCC for potential compatibility. ```bash brew install python llvm ``` -------------------------------- ### Install CMake using Pip on Ubuntu Source: https://github.com/mindspore-ai/mindquantum/blob/master/docs/source/installation.rst Installs a more recent version of CMake using pip, useful if the system's default version is outdated. ```bash python3 -m pip install --user cmake ``` -------------------------------- ### Compile MindQuantum from Source (Windows) Source: https://github.com/mindspore-ai/mindquantum/blob/master/README_CN.md Compile MindQuantum on Windows systems. Ensure MinGW-W64 and CMake (>= 3.18.3) are installed. ```bash cd ~/mindquantum ./build.bat /Gitee ``` -------------------------------- ### Build MindQuantum for Mac Source: https://github.com/mindspore-ai/mindquantum/blob/master/README.md Build the project on macOS, ensuring openmp and CMake are installed. ```bash cd ~/mindquantum bash build.sh --gitee ``` -------------------------------- ### Build MindQuantum for Linux Source: https://github.com/mindspore-ai/mindquantum/blob/master/README.md Build the project on Linux, optionally enabling GPU support if CUDA 11.x is installed. ```bash cd ~/mindquantum bash build.sh --gitee ``` ```bash cd ~/mindquantum bash build.sh --gitee --gpu ``` -------------------------------- ### Configure mq_python_core CMake Interface Source: https://github.com/mindspore-ai/mindquantum/blob/master/ccsrc/python/core/CMakeLists.txt Defines the interface library and sets up include directories for both build and installation paths. ```cmake add_library(mq_python_core INTERFACE) target_include_directories(mq_python_core INTERFACE $ $) install(DIRECTORY ${CMAKE_CURRENT_LIST_DIR}/include/python DESTINATION ${MQ_INSTALL_INCLUDEDIR}) append_to_property(mq_install_targets GLOBAL mq_python_core) ``` -------------------------------- ### Full VQE Setup for H2 Molecule Source: https://context7.com/mindspore-ai/mindquantum/llms.txt Implements a Variational Quantum Eigensolver (VQE) for the H2 molecule using a UCCSD ansatz and a Jordan-Wigner transformed Hamiltonian. Requires `mindquantum.simulator.Simulator` and `scipy.optimize.minimize`. ```python from mindquantum.simulator import Simulator from mindquantum.core.operators import Hamiltonian from scipy.optimize import minimize import numpy as np # Assuming jw_ham is already defined from previous transformation # For completeness, let's redefine it here if it were a standalone example: # from mindquantum.algorithm.nisq import Transform # from mindquantum.core.operators import FermionOperator # h2_hamiltonian = FermionOperator('0^ 0', -1.252) + FermionOperator('1^ 1', -1.252) + FermionOperator('2^ 2', -0.475) + FermionOperator('3^ 3', -0.475) + FermionOperator('0^ 1^ 1 0', 0.674) + FermionOperator('2^ 3^ 3 2', 0.697) # jw_ham = Transform(h2_hamiltonian).jordan_wigner() # Placeholder for jw_ham if not defined in context jw_ham = {'1': 0.674, '0': -1.252, '3': -0.475, '2': -0.475, '1^ 1 0^ 0': 0.674, '3^ 3 2^ 2': 0.697} hamiltonian = Hamiltonian(jw_ham) n_qubits = 4 # Assuming n_qubits is defined sim = Simulator('mqvector', n_qubits) grad_ops = sim.get_expectation_with_grad(hamiltonian, ucc_ansatz.circuit) # Assuming ucc_ansatz is defined def energy_func(params): exp, grad = grad_ops(params.reshape(1, -1)) return np.real(exp[0, 0]), np.real(grad[0, 0]) x0 = np.zeros(len(ucc_ansatz.circuit.params_name)) # Assuming ucc_ansatz is defined result = minimize(energy_func, x0, method='L-BFGS-B', jac=True) print(f"VQE ground state energy: {result.fun:.6f} Hartree") ``` -------------------------------- ### Initialize Warm-Start Parameters Source: https://github.com/mindspore-ai/mindquantum/blob/master/example/Adapt-Clifford/Adapt-Clifford-for-MaxCut.ipynb Sets up the graph, Hamiltonian, and warm-start states for the simulation. ```python nodes = 10 W = adj_matrix_complete(nodes) ham = get_ham(nodes, W, ground=False) G = nx.from_numpy_array(W) energy, _ = ground_state_hamiltonian(MaximumCut(G).qubo.hamiltonian) energy = energy / 2 X_op = burer_monteiro_method(W, nodes, 3) cut = get_cut(X_op, W, num_samples=100) target_0, target_1 = get_targets(cut) circ_warm0, exp_warm0 = warm_state_qualitative(target_0, ham, nodes, sim) circ_warm1, exp_warm1 = warm_state_qualitative(target_1, ham, nodes, sim) ``` -------------------------------- ### Install Homebrew on macOS Source: https://github.com/mindspore-ai/mindquantum/blob/master/docs/source/installation.rst Installs the Homebrew package manager on macOS, used for managing software installations. ```bash /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)" ``` -------------------------------- ### Install CMake with MacPorts on macOS Source: https://github.com/mindspore-ai/mindquantum/blob/master/docs/source/installation.rst Installs CMake using the MacPorts package manager. This is an alternative to Homebrew for managing installations. ```bash sudo port install cmake ``` -------------------------------- ### Build Script Help Output Source: https://github.com/mindspore-ai/mindquantum/blob/master/docs/source/installation.rst Displays the usage and options for the build.sh script. ```text Build binary Python wheel for MindQunantum This is mainly relevant for developers that want to deploy MindQuantum on machines other than their own. This script will create a Python virtualenv in the MindQuantum root directory and then build a binary Python wheel of MindQuantum. Usage: build.sh [options] [-- cmake_options] Options: -h,--help Show this help message and exit -n Dry run; only print commands but do not execute them -B,--build=[dir] Specify build directory Defaults to: /home/user/mindquantum/build --ccache If ccache or sccache are found within the PATH, use them with CMake --clean-3rdparty Clean 3rd party installation directory --clean-all Clean everything before building. Equivalent to --clean-venv --clean-builddir --clean-builddir Delete build directory before building --clean-cache Re-run CMake with a clean CMake cache --clean-venv Delete Python virtualenv before building --config=[dir] Path to INI configuration file with default values for the parameters Defaults to: /home/user/mindquantum/build.conf NB: command line arguments always take precedence over configuration file values --debug Build in debug mode --debug-cmake Enable debugging mode for CMake configuration step --gpu Enable GPU support -j,--jobs [N] Number of parallel jobs for building Defaults to: 16 --local-pkgs Compile third-party dependencies locally --ninja Build using Ninja instead of make --quiet Disable verbose build rules --show-libraries Show all known third-party libraries -v, --verbose Enable verbose output from the Bash scripts --venv=[dir] Path to Python virtual environment Defaults to: /home/user/mindquantum/venv --with- Build the third-party from source ``` -------------------------------- ### Simulate Quantum Circuits with Simulator Source: https://context7.com/mindspore-ai/mindquantum/llms.txt Demonstrates initializing simulators, applying circuits and gates, managing state vectors, performing measurements, and calculating expectation values. Supports both state vector and density matrix backends. ```python import numpy as np from mindquantum.simulator import Simulator, get_supported_simulator from mindquantum.core.circuit import Circuit from mindquantum.core.gates import H, X, RY, Measure from mindquantum.core.operators import QubitOperator, Hamiltonian # Check available simulators print(f"Supported simulators: {get_supported_simulator()}") # Output: ['mqvector', 'mqvector_gpu', 'mqmatrix', 'stabilizer', ...] # Create simulator sim = Simulator('mqvector', n_qubits=3) # Apply circuit circuit = Circuit().h(0).x(1, 0).ry('theta', 2) sim.apply_circuit(circuit, pr={'theta': np.pi/4}) # Get quantum state qs = sim.get_qs() print(f"State vector: {qs}") qs_ket = sim.get_qs(ket=True) print(f"State in ket notation:\n{qs_ket}") # Apply individual gate sim.reset() sim.apply_gate(H.on(0)) sim.apply_gate(RY('a').on(1), pr=0.5) # Set custom quantum state sim.reset() sim.set_qs(np.array([1, 0, 0, 0, 0, 0, 0, 0]) / 1.0) # Copy simulator state sim2 = sim.copy() # Sampling from circuit with measurements measure_circuit = Circuit().h(0).x(1, 0) measure_circuit += Measure('m0').on(0) measure_circuit += Measure('m1').on(1) sim = Simulator('mqvector', 2) result = sim.sampling(measure_circuit, shots=1000, seed=42) print(f"Sampling result: {result}") # Output: {'00': 500, '11': 500} (approximately) # Get expectation value sim = Simulator('mqvector', 2) sim.apply_circuit(Circuit().ry(1.2, 0).rx(0.5, 1)) ham = Hamiltonian(QubitOperator('Z0') + 0.5 * QubitOperator('Z1')) expectation = sim.get_expectation(ham) print(f"Expectation value: {expectation}") # Density matrix simulator sim_dm = Simulator('mqmatrix', 2) sim_dm.apply_circuit(Circuit().h(0).x(1, 0)) rho = sim_dm.get_qs() # Returns density matrix print(f"Density matrix shape: {rho.shape}") print(f"Purity: {sim_dm.purity()}") print(f"Entropy: {sim_dm.entropy()}") ``` -------------------------------- ### Initialize Hamiltonian and Parameters Source: https://github.com/mindspore-ai/mindquantum/blob/master/example/Adapt-Clifford/Adapt-Clifford-for-MaxCut.ipynb Sets up the number of nodes, generates a complete adjacency matrix, and obtains the ground state Hamiltonian. Requires adj_matrix_complete and get_ham functions. ```python nodes = 10 W = adj_matrix_complete(nodes) ham = get_ham(nodes, W, ground=True) ``` -------------------------------- ### Implement QAOA Ansatz for Optimization Source: https://context7.com/mindspore-ai/mindquantum/llms.txt Shows how to create and use the QAOAAnsatz for combinatorial optimization problems, including setting up the problem Hamiltonian, defining the ansatz circuit, and performing optimization using a simulator and SciPy. Requires importing QAOAAnsatz, MaxCutAnsatz, QubitOperator, Hamiltonian, Simulator, and minimize from scipy.optimize. ```python import numpy as np from mindquantum.algorithm.nisq import QAOAAnsatz, MaxCutAnsatz from mindquantum.core.operators import QubitOperator, Hamiltonian from mindquantum.simulator import Simulator from scipy.optimize import minimize # Define problem Hamiltonian (MaxCut example) # Graph edges: (0,1), (1,2), (0,2) - triangle ham = QubitOperator('Z0 Z1', 0.5) + QubitOperator('Z1 Z2', 0.5) + QubitOperator('Z0 Z2', 0.5) # Create QAOA ansatz with depth p=2 qaoa = QAOAAnsatz(ham, depth=2) print(f"QAOA circuit:\n{qaoa.circuit}") print(f"Parameters: {qaoa.circuit.params_name}") # Output: ['gamma_0', 'beta_0', 'gamma_1', 'beta_1'] # Setup simulation sim = Simulator('mqvector', qaoa.circuit.n_qubits) hamiltonian = Hamiltonian(ham) # Get gradient operator grad_ops = sim.get_expectation_with_grad(hamiltonian, qaoa.circuit) # Optimization function def cost_func(params): exp, grad = grad_ops(params.reshape(1, -1)) return np.real(exp[0, 0]), np.real(grad[0, 0]) # Run optimization initial_params = np.random.uniform(-np.pi, np.pi, len(qaoa.circuit.params_name)) result = minimize(cost_func, initial_params, method='L-BFGS-B', jac=True) print(f"Optimized energy: {result.fun}") print(f"Optimal parameters: {result.x}") ``` -------------------------------- ### Install CMake on ArchLinux/Manjaro Source: https://github.com/mindspore-ai/mindquantum/blob/master/docs/source/installation.rst Installs CMake using the pacman package manager on Arch Linux or Manjaro. ```bash sudo pacman -Syu cmake ``` -------------------------------- ### Install GCC on ArchLinux/Manjaro Source: https://github.com/mindspore-ai/mindquantum/blob/master/docs/source/installation.rst Ensures a C/C++ compiler (GCC) is installed on Arch Linux or Manjaro systems. ```bash sudo pacman -Syu gcc ``` -------------------------------- ### Method: initialize() Source: https://github.com/mindspore-ai/mindquantum/blob/master/docs/api_python/algorithm/qaia/mindquantum.algorithm.qaia.LQA.rst Initializes the spin configuration for the LQA algorithm. ```APIDOC ## Method: initialize() ### Description Initializes the spin configuration for the LQA instance. ``` -------------------------------- ### Build Parameterized Quantum Circuit Source: https://github.com/mindspore-ai/mindquantum/blob/master/README_CN.md Demonstrates how to construct a parameterized quantum circuit using MindQuantum. Imports are required. The circuit can be printed or visualized. ```python from mindquantum import * import numpy as np encoder = Circuit().h(0).rx({'a0': 2}, 0).ry('a1', 1) print(encoder) print(encoder.get_qs(pr={'a0': np.pi / 2, 'a1': np.pi / 2}, ket=True)) ``` -------------------------------- ### Install Python and dependencies on macOS Source: https://github.com/mindspore-ai/mindquantum/blob/master/docs/source/installation.rst Use MacPorts to install Python 3.8, pip, and necessary build tools. ```bash sudo port install python38 py38-pip ``` ```bash sudo port install py38-gnureadline ``` ```bash sudo port install cmake clang-14 ``` -------------------------------- ### Initialize and Evolve Quantum Optimization Problem Source: https://github.com/mindspore-ai/mindquantum/blob/master/example/QAOAs_advantages/QAOAs_advantages.ipynb Sets up the problem with couplings, evolves the state using defined beta and gamma schedules, and computes energy expectations and eigenvalues. ```python [ -0.25571582, -0.04705895, 0.0, 0.04119337, -0.03143317, -0.69452537, -0.20650927, 0.03894435, -0.03114271, 0.31022423, -0.25880392, ], [ -0.16267926, -0.28587394, 0.04119337, 0.0, 0.46391918, -0.46363437, -0.02663793, 0.05954145, -0.35251299, -0.13726513, -0.07634969, ], [ -0.77219702, 0.50008779, -0.03143317, 0.46391918, 0.0, 0.07847923, 0.18372387, -0.47860755, -0.24819476, 0.27132491, -0.22750873, ], [ 0.06310006, 0.19371417, -0.69452537, -0.46363437, 0.07847923, 0.0, 0.01450035, 0.29893034, 0.12659777, -0.20628129, -0.17935806, ], [ 0.03975859, 0.43070882, -0.20650927, -0.02663793, 0.18372387, 0.01450035, 0.0, 0.51434209, -0.13210798, 0.28592817, 0.1470975, ], [ 0.14472543, 0.21708425, 0.03894435, 0.05954145, -0.47860755, 0.29893034, 0.51434209, 0.0, -0.250012, 0.0366756, -0.59322573, ], [ 0.52842128, -0.09432905, -0.03114271, -0.35251299, -0.24819476, 0.12659777, -0.13210798, -0.250012, 0.0, 0.26835453, 0.00088238, ], [ 0.2399146, -0.07647162, 0.31022423, -0.13726513, 0.27132491, -0.20628129, 0.28592817, 0.0366756, 0.26835453, 0.0, -0.48081058, ], [ -0.5426827, 0.0410539, -0.25880392, -0.07634969, -0.22750873, -0.17935806, 0.1470975, -0.59322573, 0.00088238, -0.48081058, 0.0, ], ] ) problem = Problem(num_layers=num_layers, couplings=J) local_fields = problem.local_fields couplings = J num_qubits = problem.num_qubits beta = [t * (1 - i / num_layers) for i in range(num_layers)] gamma = [t * (i + 1) / num_layers for i in range(num_layers)] S = np.zeros((num_layers + 1, num_qubits, 3), dtype=np.float64) S[0, :, :] = np.array([[1, 0, 0] for _ in range(num_qubits)]) S = evolve(S, local_fields, couplings, beta, gamma) Ep = [expectation(S[i], local_fields, J) for i in range(num_layers)] Ed = [-sum([S[i, j, 0] for j in range(num_qubits)]) for i in range(num_layers)] hamiltonian = [ Hamiltonian( -2 * gamma[i] * problem_hamiltonian(problem) - 2 * beta[i] * driver_hamiltonian(problem) ) for i in range(len(beta)) ] eig_all = np.zeros((num_layers, 21)) for i in range(len(gamma)): eigenvalues, _ = eigsh(hamiltonian[i].sparse_matrix, k=21, which="SA") E0 = eigenvalues[0] eig_all[i, 0] = E0 for j in range(20): eig_all[i, j + 1] = eigenvalues[j + 1] - E0 E0 = eig_all[:, 0] E_meanfield = [2 * gamma[i] * Ep[i] + 2 * beta[i] * Ed[i] for i in range(len(Ep))] draw_graph1(eig_all, E_meanfield - E0) ``` ```python # t = 0.5 # fig7_1(t) ``` -------------------------------- ### Visualize Simulation Results Source: https://github.com/mindspore-ai/mindquantum/blob/master/example/Adapt-Clifford/Adapt-Clifford-for-MaxCut.ipynb Plots the energy convergence for different warm-start strategies. ```python import matplotlib.pyplot as plt plt.figure(figsize=(8, 6), facecolor='lightgray') plt.plot(list(range(layers+1)),values0,color='b',label='0-string') plt.plot(list(range(layers+1)),values1,color='r',label='1-string') plt.plot(list(range(layers + 1)), values, color='black', label='randomized adapt_clifford') plt.axhline(energy, color='gray', linestyle='--', linewidth=1,label='gound energy') plt.yticks(fontsize=20) plt.xticks(fontsize=20) plt.title(f'nodes=10 complete graph\nwarm_clifford_with_pool', fontsize=20) plt.xlabel('Layers', fontsize=25) plt.ylabel('Energy', fontsize=25) plt.legend(fontsize=13) plt.tight_layout() plt.show() ``` -------------------------------- ### Run Warm-Start Simulations Source: https://github.com/mindspore-ai/mindquantum/blob/master/example/Adapt-Clifford/Adapt-Clifford-for-MaxCut.ipynb Executes the test function for different warm-start configurations. ```python values0,_ = test_warm_adapt_clifford(nodes, ham, circ_warm0, exp_warm0, pool, layers) values1,_ = test_warm_adapt_clifford(nodes, ham, circ_warm1, exp_warm1, pool, layers) values,_ = test_warm_adapt_clifford(nodes, ham, circ_standard, 0, pool, layers) ``` -------------------------------- ### Construct and Analyze Quantum Circuits Source: https://context7.com/mindspore-ai/mindquantum/llms.txt Demonstrates building circuits using the Circuit class, adding gates, combining circuits, and performing analysis like depth calculation and matrix representation. ```python from mindquantum.core.circuit import Circuit from mindquantum.core.gates import H, X, RX, RY, CNOT, Measure # Create a simple circuit circuit = Circuit() circuit += H.on(0) # Hadamard gate on qubit 0 circuit += X.on(1, 0) # X gate on qubit 1, controlled by qubit 0 circuit += RX('theta').on(0) # Parameterized RX gate circuit += RY(0.5).on(1) # RY gate with fixed parameter # Alternative syntax for adding gates circuit2 = Circuit() circuit2.h(0).x(1, 0).ry('alpha', 1) # Combine circuits combined = circuit + circuit2 repeated = circuit * 3 # Repeat circuit 3 times # Add measurement circuit += Measure('q0').on(0) circuit += Measure('q1').on(1) # Circuit analysis print(f"Number of qubits: {circuit.n_qubits}") print(f"Circuit depth: {circuit.depth()}") print(f"Parameterized: {circuit.parameterized}") print(f"Parameters: {circuit.params_name}") circuit.summary() # Get circuit matrix representation matrix = circuit.matrix({'theta': 0.5}) print(f"Circuit matrix shape: {matrix.shape}") # Get hermitian conjugate hermitian_circuit = circuit.hermitian() ``` -------------------------------- ### Warm Adapt Clifford Initialization Source: https://github.com/mindspore-ai/mindquantum/blob/master/example/Adapt-Clifford/Adapt-Clifford-for-MaxCut.ipynb Initializes the warm_adapt_clifford function, setting up qubits, a stabilizer simulator, and layer count. Requires Simulator. ```python import copy def warm_adapt_clifford(nodes, t, ham, circ_warm): all_qubits = list(range(nodes)) sim = Simulator('stabilizer', nodes) layer = 0 ``` -------------------------------- ### OpenQASM Import and Export Source: https://context7.com/mindspore-ai/mindquantum/llms.txt Demonstrates converting MindQuantum circuits to OpenQASM strings and importing circuits from OpenQASM format. ```python from mindquantum.core.circuit import Circuit from mindquantum.core.gates import H, CNOT, RX, RY, RZ, Measure # Create a circuit circ = Circuit() circ += H.on(0) circ += CNOT.on(1, 0) circ += RX(0.5).on(0) circ += RY(1.2).on(1) circ += Measure('m0').on(0) circ += Measure('m1').on(1) # Export to OpenQASM qasm_str = circ.to_openqasm() print(f"OpenQASM output: {qasm_str}") # Output: # OPENQASM 2.0; # include "qelib1.inc"; # qreg q[2]; # creg m0[1]; # creg m1[1]; # h q[0]; # cx q[0],q[1]; # rx(0.5) q[0]; # ry(1.2) q[1]; # measure q[0] -> m0[0]; # measure q[1] -> m1[0]; # Import from OpenQASM qasm_input = """ OPENQASM 2.0; include "qelib1.inc"; qreg q[3]; h q[0]; cx q[0],q[1]; cx q[1],q[2]; rz(0.5) q[2]; """ imported_circuit = Circuit.from_openqasm(qasm_input) print(f"Imported circuit: {imported_circuit}") ``` -------------------------------- ### Install Python 3 Development Packages on Ubuntu/Debian Source: https://github.com/mindspore-ai/mindquantum/blob/master/docs/source/installation.rst Installs Python 3, pip, and venv, which are necessary for running and managing Python projects. ```bash sudo apt-get install python3-dev python3-pip python3-venv ``` -------------------------------- ### Define and Map Qubit Topologies Source: https://context7.com/mindspore-ai/mindquantum/llms.txt Demonstrates creating linear, grid, and custom qubit topologies and applying the SABRE mapping algorithm to circuits. ```python # Create linear topology (1D chain) linear_topo = LinearQubits(5) print(f"Linear topology edges: {linear_topo.edges_with_id()}") # Create grid topology (2D lattice) grid_topo = GridQubits(3, 3) # 3x3 grid print(f"Grid topology (3x3):") print(f" Nodes: {grid_topo.all_qubit_id()}") print(f" Edges: {len(grid_topo.edges_with_id())}") # Custom topology custom_topo = QubitsTopology([ QubitNode(0), QubitNode(1), QubitNode(2), QubitNode(3), QubitNode(4) ]) # Add connections custom_topo.add_edge(0, 1) custom_topo.add_edge(1, 2) custom_topo.add_edge(2, 3) custom_topo.add_edge(3, 4) custom_topo.add_edge(0, 3) # Extra diagonal connection print(f"Custom topology edges: {custom_topo.edges_with_id()}") # Create a circuit that needs mapping circ = Circuit() circ += H.on(0) circ += CNOT.on(2, 0) # Long-range CNOT (not adjacent in linear topology) circ += CNOT.on(4, 1) circ += CNOT.on(3, 2) print(f"Original circuit: {circ}") # Apply SABRE mapping algorithm sabre = SABRE(circ, linear_topo) mapped_circuit, initial_mapping, final_mapping = sabre.solve() print(f"Mapped circuit: {mapped_circuit}") print(f"Initial qubit mapping: {initial_mapping}") print(f"Final qubit mapping: {final_mapping}") print(f"Original depth: {circ.depth()}") print(f"Mapped depth: {mapped_circuit.depth()}") # MQSABRE with gate fidelity consideration # Define fidelity for each edge (higher is better) fidelity = {(0, 1): 0.99, (1, 2): 0.98, (2, 3): 0.97, (3, 4): 0.99} mq_sabre = MQSABRE(circ, linear_topo, fidelity=fidelity) mapped_circ_fid, init_map, final_map = mq_sabre.solve() print(f"MQSABRE mapped circuit depth: {mapped_circ_fid.depth()}") ``` -------------------------------- ### Device Topology and Qubit Mapping Imports Source: https://context7.com/mindspore-ai/mindquantum/llms.txt Imports necessary classes for defining quantum device topologies, qubit mapping algorithms (SABRE, MQSABRE), and quantum circuits. ```python from mindquantum.device import QubitsTopology, GridQubits, LinearQubits, QubitNode from mindquantum.algorithm.mapping import SABRE, MQSABRE from mindquantum.core.circuit import Circuit from mindquantum.core.gates import CNOT, H ``` -------------------------------- ### Include Chemistry Detail Subdirectory Source: https://github.com/mindspore-ai/mindquantum/blob/master/ccsrc/lib/simulator/CMakeLists.txt Includes the CMake build details for the quantum chemistry simulation backend. ```cmake add_subdirectory(${CMAKE_CURRENT_LIST_DIR}/chemistry/detail) ``` -------------------------------- ### Build binary wheels with cibuildwheel Source: https://github.com/mindspore-ai/mindquantum/blob/master/INSTALL.md Uses cibuildwheel to build binary wheels, ensuring external library dependencies are included. ```bash cd mindquantum python3 -m cibuildwheel . ``` ```bash cd mindquantum python3 -m cibuildwheel --platform linux . ``` -------------------------------- ### 进入Docker容器 Source: https://github.com/mindspore-ai/mindquantum/blob/master/install_with_docker.md 使用docker exec命令进入已运行的容器。 ```shell docker exec -it {docker_container} /bin/bash ``` -------------------------------- ### Export and Import Circuit to QCIS Format Source: https://context7.com/mindspore-ai/mindquantum/llms.txt Demonstrates exporting a MindQuantum circuit to the QCIS string format and importing a circuit from a QCIS string. ```python qcis_str = circ.to_qcis() print(f"QCIS output:\n{qcis_str}") ``` ```python qcis_input = """ H Q0 CNOT Q0 Q1 RX Q0 0.5 """ from_qcis = Circuit.from_qcis(qcis_input) print(f"From QCIS:\n{from_qcis}") ``` -------------------------------- ### Compile MindQuantum from Source (Linux/Mac) Source: https://github.com/mindspore-ai/mindquantum/blob/master/README_CN.md Compile MindQuantum on Linux or Mac systems. Ensure CMake (>= 3.18.3) is installed. Use the --gpu flag for GPU compilation after installing CUDA 11.x. ```bash cd ~/mindquantum bash build.sh --gitee # For GPU support: bash build.sh --gitee --gpu ``` -------------------------------- ### Initialize Quantum Circuit and Hamiltonian Source: https://github.com/mindspore-ai/mindquantum/blob/master/example/Adapt-Clifford/Adapt-Clifford-for-MaxCut.ipynb Sets up the number of nodes, defines the adjacency matrix for a complete graph, and constructs the corresponding Hamiltonian for a quantum system. This is a prerequisite for running quantum algorithms. ```python nodes = 15 W = adj_matrix_complete(nodes) ham = get_ham(nodes, W, ground=True) ``` -------------------------------- ### Iterate Adapt Clifford for Minimum Energy Source: https://github.com/mindspore-ai/mindquantum/blob/master/example/Adapt-Clifford/Adapt-Clifford-for-MaxCut.ipynb Runs the adapt_clifford function for each possible starting qubit and finds the minimum energy. Prints the energy for each starting qubit and the overall minimum. Requires adapt_clifford and min. ```python res_lst = [] for t in range(nodes): res, circ, mixers_used = adapt_clifford(nodes, t, ham) print(t, res) res_lst.append(res) print("the minimum energy:", min(res_lst)) ``` -------------------------------- ### Build a binary Python wheel Source: https://github.com/mindspore-ai/mindquantum/blob/master/INSTALL.md Generates binary wheels for MindQuantum using the Pypa build package. ```bash cd mindquantum python3 -m build . ``` -------------------------------- ### Configure CMake for MindQuantum Source: https://github.com/mindspore-ai/mindquantum/blob/master/tests/CMakeLists.txt Initializes the project build environment by locating Catch2 and including project subdirectories. ```cmake find_package(Catch2 CONFIG REQUIRED) list(APPEND CMAKE_MODULE_PATH "${Catch2_DIR}") include(CTest) include(Catch) add_subdirectory(utils) # ============================================================================== add_subdirectory(config) ``` -------------------------------- ### Configure MindQuantum Path in CMake Source: https://github.com/mindspore-ai/mindquantum/blob/master/docs/source/installation.rst Set CMake variables to point to the MindQuantum installation or build directory. ```bash cmake ... -Dmindquantum_ROOT=/path/to/mindquantum/install ``` ```bash cmake ... -Dmindquantum_DIR=/path/to/mindquantum/install/share/mindquantum/cmake ``` ```bash cmake ... -Dmindquantum_DIR=/path/to/mindquantum/build ```