diff --git a/.clang-format b/.clang-format index e4ffe2317..554920e01 100644 --- a/.clang-format +++ b/.clang-format @@ -38,8 +38,6 @@ IncludeCategories: # 3. CUDA headers # 4. Boost headers # 5. Eigen headers - # 6. tweedledum headers - # 7. SymEngine headers # 8. Other system headers # 9. Any local config header # 10. Local headers @@ -52,8 +50,6 @@ IncludeCategories: Priority: 40 - Regex: '<(Eigen|Unsupported/Eigen)\/' Priority: 50 - - Regex: '[<"]symengine\/' - Priority: 70 - Regex: '[<"]cuda[A-Za-z0-9.\/\-_]+[>"]' Priority: 30 - Regex: '[<"](driver_types.h)[>"]' @@ -70,10 +66,6 @@ IncludeCategories: Priority: 20 - Regex: '<[[:alnum:]_\.]+' Priority: 80 - - Regex: '"experimental/config/[[:alnum:]\/\-_\.]+\.hpp"' - Priority: 105 - - Regex: '"experimental/[[:alnum:]\/\-_\.]+\.hpp"' - Priority: 106 - Regex: '"config/[[:alnum:]\/\-_\.]+\.hpp"' Priority: 90 - Regex: '"python/[[:alnum:]\/\-_\.]+"' diff --git a/.cppcheck.suppressions b/.cppcheck.suppressions index 95beba572..28f95381e 100644 --- a/.cppcheck.suppressions +++ b/.cppcheck.suppressions @@ -6,60 +6,47 @@ constParameter:tests/* unreadVariable:tests/* assignBoolToPointer:ccsrc/python/simulator/include/python/vector/bind_vec_state.h -assignBoolToPointer:ccsrc/python/simulator/include/python/densitymatrix/bind_mat_state.hpp +assignBoolToPointer:ccsrc/python/simulator/include/python/densitymatrix/bind_mat_state.h containerOutOfBounds:ccsrc/include/ops/gates/fermion_operator.tpp containerOutOfBounds:ccsrc/lib/ops/gates/fermion_operator.cpp containerOutOfBounds:ccsrc/lib/ops/gates/fermion_operator_parameter_resolver.cpp -cstyleCast:ccsrc/include/simulator/cintrin.hpp +cstyleCast:ccsrc/include/simulator/cintrin.h duplicateExpression:ccsrc/include/core/parameter_resolver.h:707 duplicateExpression:ccsrc/python/math/lib/bind_math.cpp -noExplicitConstructor:ccsrc/include/experimental/decompositions/decomposition_atom.hpp:41 -noExplicitConstructor:ccsrc/include/experimental/ops/parametric/gate_base.hpp -noValidConfiguration:ccsrc/include/config/config.hpp -noValidConfiguration:ccsrc/include/config/details/cxx20_compatibility.hpp -noValidConfiguration:ccsrc/include/config/type_traits.hpp -noValidConfiguration:ccsrc/include/experimental/ops/parametric/angle_base.hpp -noValidConfiguration:ccsrc/include/experimental/ops/parametric/angle_gates.hpp +noValidConfiguration:ccsrc/include/config/details/cxx20_compatibility.h +noValidConfiguration:ccsrc/include/config/type_traits.h noValidConfiguration:tests/decompositions/test_apply_atoms.cpp -operatorEqVarError:ccsrc/include/experimental/decompositions/decomposition_atom.hpp -preprocessorErrorDirective:ccsrc/include/config/details/cxx20_compatibility.hpp -preprocessorErrorDirective:ccsrc/include/experimental/decompositions/rules/config.hpp -preprocessorErrorDirective:ccsrc/include/experimental/ops/parametric/angle_base.hpp -preprocessorErrorDirective:ccsrc/python/core/include/python/details/define_binary_operator_helpers.hpp -preprocessorErrorDirective:ccsrc/python/experimental/lib/ops/ops.cpp +preprocessorErrorDirective:ccsrc/include/config/details/cxx20_compatibility.h preprocessorErrorDirective:tests/decompositions/test_apply_atoms.cpp preprocessorErrorDirective:tests/ops/test_angle_parametric_gates.cpp -unusedStructMember:ccsrc/include/math/tensor/ops_cpu/utils.hpp -stlIfFind:ccsrc/lib/experimental/decompositions/atom_storage.cpp -stlIfFind:ccsrc/lib/experimental/decompositions/gate_decomposer.cpp +unusedStructMember:ccsrc/include/math/tensor/ops_cpu/utils.h -syntaxError:ccsrc/include/core/parameter_resolver_external_ops.hpp:90 -syntaxError:ccsrc/include/core/sparse/algo.hpp -syntaxError:ccsrc/include/ops/gates/terms_operator_base_external_ops.hpp:92 +syntaxError:ccsrc/include/core/parameter_resolver_external_ops.h:90 +syntaxError:ccsrc/include/core/sparse/algo.h +syntaxError:ccsrc/include/ops/gates/terms_operator_base_external_ops.h:92 syntaxError:ccsrc/lib/simulator/vector/detail/cpu_vector_policy.cpp syntaxError:ccsrc/lib/simulator/vector/detail/cpu_vector_policy_gate_expec.cpp -syntaxError:ccsrc/python/mqbackend/lib/details/define_terms_ops.hpp +syntaxError:ccsrc/python/mqbackend/lib/details/define_terms_ops.h syntaxError:ccsrc/lib/simulator/vector/detail/cpu_common/cpu_vector_core_condition.cpp syntaxError:ccsrc/lib/simulator/vector/detail/cpu_common/cpu_vector_core_gate_expect.cpp syntaxError:ccsrc/lib/simulator/vector/detail/cpu_common/cpu_vector_core_dot_like.cpp syntaxError:ccsrc/lib/simulator/vector/detail/cpu_avx_double/cpu_vector_core_gate_expect.cpp syntaxError:ccsrc/lib/simulator/densitymatrix/detail/cpu_common/cpu_densitymatrix_core_gate_expect.cpp -syntaxError:ccsrc/python/device/include/python/device/binding.hpp +syntaxError:ccsrc/python/device/include/python/device/binding.h syntaxError:ccsrc/lib/simulator/vector/detail/cpu_common/cpu_vector_core_policy.cpp syntaxError:ccsrc/lib/simulator/densitymatrix/detail/cpu_common/cpu_densitymatrix_core_condition.cpp syntaxError:ccsrc/lib/simulator/densitymatrix/detail/cpu_common/cpu_densitymatrix_core_policy.cpp unknownMacro:ccsrc/lib/simulator/densitymatrix/detail/cpu_common/cpu_densitymatrix_core_rot_pauli.cpp -unknownMacro:ccsrc/include/simulator/densitymatrix/detail/cpu_densitymatrix_policy.hpp -unknownMacro:ccsrc/include/core/sparse/paulimat.hpp -unknownMacro:ccsrc/include/core/sparse/paulimat.hpp:58 +unknownMacro:ccsrc/include/core/sparse/paulimat.h +unknownMacro:ccsrc/include/math/tensor/ops_cpu/basic_math.h unknownMacro:ccsrc/lib/simulator/vector/detail/cpu_vector_policy_single_ops.cpp unknownMacro:ccsrc/lib/simulator/vector/detail/cpu_vector_policy_xlike.cpp unknownMacro:ccsrc/lib/simulator/vector/detail/cpu_common/cpu_vector_core_z_like.cpp @@ -69,21 +56,12 @@ unknownMacro:ccsrc/lib/simulator/vector/detail/cpu_common/cpu_vector_core_matrix unknownMacro:ccsrc/lib/simulator/vector/detail/cpu_common/cpu_vector_core_x_like.cpp unknownMacro:ccsrc/lib/simulator/vector/detail/cpu_avx_double/cpu_vector_core_matrix_gate.cpp unknownMacro:ccsrc/lib/simulator/densitymatrix/detail/cpu_common/cpu_densitymatrix_core_matrix_gate.cpp -unknownMacro:ccsrc/include/simulator/vector/detail/cpu_vector_policy.hpp +unknownMacro:ccsrc/include/simulator/vector/detail/cpu_vector_policy.h -unreadVariable:ccsrc/lib/experimental/decompositions/time_evolution.cpp - -unusedStructMember:ccsrc/include/experimental/ops/gates/details/coeff_policy.hpp:29 - -unusedStructMember:ccsrc/include/experimental/ops/parametric/param_names.hpp -unusedStructMember:ccsrc/include/experimental/ops/gates/details/coeff_policy.hpp -unusedStructMember:ccsrc/include/core/mq_base_types.hpp - -useStlAlgorithm:ccsrc/include/config/tsl_ordered_map.hpp -useStlAlgorithm:ccsrc/include/experimental/core/control.hpp:79 -useStlAlgorithm:ccsrc/include/ops/gates/terms_coeff_dict.hpp +useStlAlgorithm:ccsrc/include/config/tsl_ordered_map.h +useStlAlgorithm:ccsrc/include/ops/gates/terms_coeff_dict.h useStlAlgorithm:ccsrc/include/ops/gates/terms_operator_base.tpp -useInitializationList:ccsrc/include/simulator/cintrin.hpp +useInitializationList:ccsrc/include/simulator/cintrin.h ctuOneDefinitionRuleViolation:tests/core/test_circuit_block.cpp diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index fe8f3c600..143506633 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -7,6 +7,7 @@ on: push: branches-ignore: - 'test' + pull_request: env: CMAKE_VERSION: 3.22.3 @@ -14,6 +15,7 @@ env: jobs: standard: + if: ${{ false }} strategy: fail-fast: false matrix: @@ -98,92 +100,47 @@ jobs: - name: Configure run: | - ./build_locally.sh --cxx --debug-cmake --test --ccache --no-gitee --debug \ + ./build_locally.sh --debug-cmake --ccache --no-gitee --debug \ --configure-only -c --clean-3rdparty --prefix="${{ github.workspace }}/install" \ --cmake-no-registry \ -- -DPython_FIND_UNVERSIONED_NAMES:STRING='FIRST' - name: Build - run: ./build_locally.sh --cxx --debug-cmake --test --ccache + run: ./build_locally.sh --debug-cmake --ccache - name: Install run: ./build_locally.sh --install # NB: no need to pass the other parameters # ------------------------------------------------------------------------ - - name: Run C++ tests - run: | - cd build - catchsegv ctest --output-on-failure - - # ------------------------------------------------------------------------ - - - name: In-build config files - if: matrix.test_install - run: | - cat ${{ github.workspace }}/build/mindquantumConfig.cmake - echo ---------- - cat ${{ github.workspace }}/build/mindquantumTargetsExternal.cmake - - - name: Out-of-build config files - if: matrix.test_install - run: | - cat ${{ github.workspace }}/build/config_for_install/mindquantumConfig.cmake - echo ---------- - cat ${{ github.workspace }}/build/config_for_install/mindquantumTargetsExternal.cmake - - - name: Setup installation test - if: matrix.test_install - run: | - mkdir other - cat << \EOF > other/CMakeLists.txt - cmake_minimum_required(VERSION 3.20) - project(test CXX) - find_package(mindquantum CONFIG REQUIRED) - set(CMAKE_CXX_STANDARD 20) - set(CMAKE_CXX_STANDARD_REQUIRED OFF) - set(CMAKE_CXX_EXTENSIONS OFF) - add_library(mylib STATIC test.cpp) - target_link_libraries(mylib PUBLIC mindquantum::mq_cxx_nextgen) - EOF - cat << \EOF > other/test.cpp - #include "experimental/ops/parametric/angle_gates.hpp" - double foo() { return mindquantum::ops::parametric::Rxx{1.3}.eval_full().angle(); } - EOF - - - name: Test (local) installation - if: matrix.test_install - run: | - . venv/bin/activate - unset Python_ROOT_DIR - hash -r - cmake -S other -B other/local_build -Dmindquantum_DEBUG=ON -Dmindquantum_ROOT=${{ github.workspace }}/build - cmake --build other/local_build --target all -v - - - name: Test (normal) installation - if: matrix.test_install - run: | - . venv/bin/activate - unset Python_ROOT_DIR - hash -r - cmake -S other -B other/build -Dmindquantum_DEBUG=ON -Dmindquantum_ROOT="${{ github.workspace }}/install" - cmake --build other/build --target all -v - - # ------------------------------------------------------------------------ - - name: Test (setup.py) installation if: matrix.test_bdist_wheel env: VENV_PYTHON_TEST_PKGS: ${{ matrix.VENV_PYTHON_TEST_PKGS }} run: | - ./build.sh --cxx --debug-cmake --test \ + ./build.sh --debug-cmake \ --fast-build --no-build-isolation --no-delocate --ccache --cmake-no-registry --no-gitee + - name: Test tests/st + run: | + pwd + source venv/bin/activate + export PYTHONPATH=`pwd`:$PYTHONPATH + which python + which python3 + which pip + echo $PYTHONPATH + pip install -r requirements_test.txt + pip install pytest + python3 -c "import mindquantum as mq;print(mq.qft(range(3)))" + pytest tests/st -rs + # ============================================================================ macos: - runs-on: macos-11 - name: "MacOS 11 • ${{ matrix.xcode }} • x64" + if: ${{ true }} + runs-on: macos-12 + name: "MacOS 12 • ${{ matrix.xcode }} • x64" env: DEVELOPER_DIR: "/Applications/${{ matrix.xcode }}.app/Contents/Developer" CC: /usr/bin/clang @@ -192,13 +149,13 @@ jobs: fail-fast: false matrix: xcode: - - "Xcode_11.7" # Not available on macos-12 - - "Xcode_12.4" # Not available on macos-12 - - "Xcode_12.5.1" # Not available on macos-12 - # - "Xcode_13.0" # Not available on macos-12 - - "Xcode_13.1" - - "Xcode_13.2.1" - # - "Xcode_13.3.1" # macos-12 only + # - "Xcode_11.7" # Not available on macos-12 + # - "Xcode_12.4" # Not available on macos-12 + # - "Xcode_12.5.1" # Not available on macos-12 + # # - "Xcode_13.0" # Not available on macos-12 + # - "Xcode_13.1" + # - "Xcode_13.2.1" + - "Xcode_13.3.1" # macos-12 only # - "Xcode_13.4.1" # macos-12 only steps: - uses: actions/checkout@v3 @@ -242,24 +199,34 @@ jobs: - name: Configure run: >- - ./build_locally.sh --cxx --debug-cmake --test --ccache --only-pytest --no-gitee --debug + ./build_locally.sh --debug-cmake --ccache --only-pytest --no-gitee --debug --configure-only -c --clean-3rdparty --prefix="${{ github.workspace }}/install" --cmake-no-registry - name: Build - run: ./build_locally.sh --cxx --debug-cmake --test --ccache + run: ./build_locally.sh --debug-cmake --ccache - name: Install run: ./build_locally.sh --install # NB: no need to pass the other parameters - - name: Run C++ tests + - name: Test tests/st run: | - cd build - ctest --output-on-failure + pwd + source venv/bin/activate + export PYTHONPATH=`pwd`:$PYTHONPATH + which python + which python3 + which pip + echo $PYTHONPATH + pip install -r requirements_test.txt + pip install pytest + python3 -c "import mindquantum as mq;print(mq.qft(range(3)))" + pytest tests/st -rs # ============================================================================ gcc: + if: ${{ false }} runs-on: ubuntu-latest strategy: fail-fast: false @@ -278,6 +245,7 @@ jobs: - name: Get history and tags for SCM versioning to work run: | + git config --global --add safe.directory /__w/mindquantum/mindquantum git fetch --prune --unshallow git fetch --depth=1 origin +refs/tags/*:refs/tags/* @@ -325,21 +293,16 @@ jobs: - name: Configure run: >- - ./build_locally.sh --cxx --debug-cmake --test --ccache --only-pytest --no-gitee --debug + ./build_locally.sh --debug-cmake --ccache --only-pytest --no-gitee --debug --configure-only -c --logging --clean-3rdparty --prefix="${{ github.workspace }}/install" --cmake-no-registry -- -DENABLE_STACK_PROTECTION=ON - name: Build - run: ./build_locally.sh --cxx --debug-cmake --test --ccache + run: ./build_locally.sh --debug-cmake --ccache - name: Install run: ./build_locally.sh --install # NB: no need to pass the other parameters - - name: Run C++ tests - run: | - cd build - catchsegv ctest --output-on-failure - - name: Run debugger in case of failure if: ${{ failure() }} run: | @@ -394,9 +357,25 @@ jobs: !build/tests/**/Makefile !build/tests/**/*.* + - name: Test tests/st + shell: bash + run: | + pwd + source venv/bin/activate + export PYTHONPATH=`pwd`:$PYTHONPATH + which python + which python3 + which pip + echo $PYTHONPATH + pip install -r requirements_test.txt + pip install pytest + python3 -c "import mindquantum as mq;print(mq.qft(range(3)))" + pytest tests/st -rs + # ============================================================================ clang: + if: ${{ false }} runs-on: ubuntu-latest strategy: fail-fast: false @@ -419,10 +398,21 @@ jobs: steps: - uses: actions/checkout@v3 + - name: install git + run: | + apt-get update && apt-get install -y git + + - name: install libomp-${{ matrix.clang }}-dev + run: | + apt-get update && apt-get install -y libomp-${{ matrix.clang }}-dev + - name: Get history and tags for SCM versioning to work run: | - git fetch --prune --unshallow - git fetch --depth=1 origin +refs/tags/*:refs/tags/* + ls -alth + # pwd + # git config --global --add safe.directory /__w/mindquantum/mindquantum + # git fetch --prune --unshallow + # git fetch --depth=1 origin +refs/tags/*:refs/tags/* - name: Prepare env run: > @@ -469,7 +459,7 @@ jobs: - name: Configure (Clang) if: matrix.clang != '8' run: >- - ./build_locally.sh --cxx --debug-cmake --test --ccache --only-pytest --no-gitee --debug + ./build_locally.sh --debug-cmake --ccache --only-pytest --no-gitee --debug --configure-only -c --clean-3rdparty --prefix="${{ github.workspace }}/install" --cmake-no-registry -- -DENABLE_STACK_PROTECTION=ON @@ -477,21 +467,16 @@ jobs: - name: Configure (Clang 8) if: matrix.clang == '8' run: >- - ./build_locally.sh --cxx --debug-cmake --test --ccache --only-pytest --no-gitee + ./build_locally.sh --debug-cmake --ccache --only-pytest --no-gitee --configure-only -c --clean-3rdparty --prefix="${{ github.workspace }}/install" --cmake-no-registry -- -DENABLE_STACK_PROTECTION=ON - name: Build - run: ./build_locally.sh --cxx --debug-cmake --test --ccache + run: ./build_locally.sh --debug-cmake --ccache - name: Install run: ./build_locally.sh --install # NB: no need to pass the other parameters - - name: Run C++ tests - run: | - cd build - catchsegv ctest --output-on-failure - - name: Run debugger in case of failure if: ${{ failure() }} run: | @@ -543,9 +528,25 @@ jobs: !build/tests/**/Makefile !build/tests/**/*.* + - name: Test tests/st + shell: bash + run: | + pwd + source venv/bin/activate + export PYTHONPATH=`pwd`:$PYTHONPATH + which python + which python3 + which pip + echo $PYTHONPATH + pip install -r requirements_test.txt + pip install pytest + python3 -c "import mindquantum as mq;print(mq.qft(range(3)))" + pytest tests/st -rs + # ============================================================================ msvc: + if: ${{ false }} runs-on: windows-latest name: "MSVC • x64" steps: @@ -607,22 +608,17 @@ jobs: CC: cl CXX: cl run: >- - ./build_locally.ps1 -Cxx -DebugCmake -Ninja -Test -CCache -OnlyPytest -NoGitee + ./build_locally.ps1 -DebugCmake -Ninja -CCache -OnlyPytest -NoGitee -ConfigureOnly -C -Clean3rdParty -Prefix "${{ github.workspace }}/install" -CMakeNoRegistry -DUSE_PARALLEL_STL=OFF - name: Build - run: ./build_locally.ps1 -Cxx -DebugCmake -Ninja -Test -CCache + run: ./build_locally.ps1 -DebugCmake -Ninja -CCache - name: Install run: ./build_locally.ps1 -Install - # - name: Run C++ tests - # run: | - # cd build - # ctest --output-on-failure - - name: Print CCache statistics run: | ccache -sv @@ -637,6 +633,7 @@ jobs: # ============================================================================ clang-cl: + if: ${{ false }} runs-on: windows-latest name: "Clang-Cl • x64" steps: @@ -699,22 +696,17 @@ jobs: CC: clang-cl CXX: clang-cl run: >- - ./build_locally.ps1 -Cxx -DebugCmake -Ninja -Test -CCache -OnlyPytest -NoGitee + ./build_locally.ps1 -DebugCmake -Ninja -CCache -OnlyPytest -NoGitee -ConfigureOnly -C -Clean3rdParty -Prefix "${{ github.workspace }}/install" -CMakeNoRegistry -Verbose -DUSE_PARALLEL_STL=OFF - name: Build - run: ./build_locally.ps1 -Cxx -DebugCmake -Ninja -Test -CCache -Verbose + run: ./build_locally.ps1 -DebugCmake -Ninja -CCache -Verbose - name: Install run: ./build_locally.ps1 -Install - - name: Run C++ tests - run: | - cd build - ctest --output-on-failure - - name: Print CCache statistics run: | ccache -sv @@ -729,13 +721,12 @@ jobs: # ============================================================================ mingw64: + if: ${{ false }} runs-on: windows-2022 strategy: fail-fast: false name: "MINGW64 • x64" - env: - BOOST_VERSION: 1.78.0 - BOOST_PATH: ${{github.workspace}}/boost/boost + steps: - uses: actions/checkout@v3 @@ -798,45 +789,23 @@ jobs: "CC='$Env:CC'" >> $Env:GITHUB_ENV "CXX='$Env:CXX'" >> $Env:GITHUB_ENV - # - name: Cache boost - # uses: actions/cache@v3 - # id: cache-boost - # with: - # path: ${{ env.BOOST_PATH }} - # key: boost-${{ env.BOOST_VERSION }} - - - name: Download and install Boost - uses: MarkusJx/install-boost@v2.4.3 - if: steps.cache-boost.outputs.cache-hit != 'true' - id: install-boost - with: - boost_version: ${{ env.BOOST_VERSION }} - platform_version: 2022 - toolset: mingw - - name: Configure - env: - BOOST_ROOT: ${{ env.BOOST_PATH }} run: >- - ./build_locally.ps1 -Cxx -DebugCmake -Ninja -Test -OnlyPytest -NoGitee + ./build_locally.ps1 -DebugCmake -Ninja -OnlyPytest -NoGitee -ConfigureOnly -C -Clean3rdParty -Prefix "${{ github.workspace }}/install" -CMakeNoRegistry --% -G "MinGW Makefiles" -DUSE_PARALLEL_STL=OFF - name: Build - run: ./build_locally.ps1 -Cxx -DebugCmake -Ninja -Test + run: ./build_locally.ps1 -DebugCmake -Ninja - name: Install run: ./build_locally.ps1 -Install - - name: Run C++ tests - run: | - cd build - ctest --output-on-failure - # ============================================================================ msys2: + if: ${{ false }} runs-on: windows-latest strategy: fail-fast: false @@ -863,7 +832,6 @@ jobs: patch make mingw-w64-clang-x86_64-toolchain - mingw-w64-clang-x86_64-libssp mingw-w64-clang-x86_64-cmake mingw-w64-clang-x86_64-ccache mingw-w64-clang-x86_64-gmp @@ -952,7 +920,7 @@ jobs: CC: ${{ matrix.CC }} CXX: ${{ matrix.CXX }} run: >- - ./build_locally.sh --cxx --debug-cmake --test --ccache -v --only-pytest --no-gitee + ./build_locally.sh --debug-cmake --ccache -v --only-pytest --no-gitee --configure-only -c --clean-3rdparty --prefix="$PWD/install" --cmake-no-registry -- -G "MSYS Makefiles" @@ -962,7 +930,7 @@ jobs: env: CC: ${{ matrix.CC }} CXX: ${{ matrix.CXX }} - run: ./build_locally.sh --cxx --debug-cmake --test --ccache + run: ./build_locally.sh --debug-cmake --ccache - name: Install shell: msys2 {0} @@ -985,152 +953,8 @@ jobs: # ============================================================================ - cygwin: - runs-on: windows-latest - name: "Cygwin • x64" - env: - CYGWIN_NOWINPATH: 1 # only have cygwin's executables on PATH - CHERE_INVOKING: 1 # prevent profile script to change directory - CCACHE_VERSION: 4.6.1 - steps: - - run: git config --global core.autocrlf input - - - uses: actions/checkout@v3 - - - name: Get history and tags for SCM versioning to work - run: | - git fetch --prune --unshallow - git fetch --depth=1 origin +refs/tags/*:refs/tags/* - - - name: Setup Cygwin - uses: cygwin/cygwin-install-action@v3 - id: setup-cygwin - continue-on-error: true - with: - packages: >- - cygwin cygwin-devel - autoconf automake coreutils m4 make cmake patch git - gawk sed libtool gettext wget curl grep dos2unix - gzip bzip2 tar xz - binutils gcc-core gcc-g++ - libgmp-devel libzstd-devel - python3 python3-devel python3-pip python3-virtualenv - - - name: Setup Cygwin (2nd try) - uses: cygwin/cygwin-install-action@v3 - if: steps.setup-cygwin.outcome == 'failure' - with: - packages: >- - cygwin cygwin-devel - autoconf automake coreutils m4 make cmake patch git - gawk sed libtool gettext wget curl grep dos2unix - gzip bzip2 tar xz - binutils gcc-core gcc-g++ - libgmp-devel libzstd-devel - python3 python3-devel python3-pip python3-virtualenv - - - name: Get Date - id: get-date - shell: bash --login -eo pipefail -o igncr {0} - run: echo "date=$(date -Iseconds)" >> $GITHUB_OUTPUT - - - name: Restore cache for CCache - if: env.ACT != 'true' - id: ccache-cache - uses: martijnhols/actions-cache/restore@v3.0.11b - with: - path: ccache - key: cygwin-ccache-${{ steps.get-date.outputs.date }} - restore-keys: cygwin-ccache- - - - name: Install CCache - shell: bash --login -eo pipefail -o igncr {0} - run: | - export PATH="$PATH:$PWD/ccache/bin" - if ! command -v ccache >/dev/null 2>&1 || [[ \ - "$(ccache --version | head -1)" != "ccache version ${CCACHE_VERSION}" ]]; then - echo "Building CCache ${CCACHE_VERSION} from source" - wget https://github.com/ccache/ccache/releases/download/v${CCACHE_VERSION}/ccache-${CCACHE_VERSION}.tar.gz - tar xf ccache-${CCACHE_VERSION}.tar.gz - cmake -S ccache-${CCACHE_VERSION} -B ccache-${CCACHE_VERSION}/build \ - -DENABLE_TESTING=OFF -DENABLE_DOCUMENTATION=OFF \ - -DCCACHE_DEV_MODE=OFF -DHIREDIS_FROM_INTERNET=ON \ - -DHAVE_ASM_SSE41=OFF -DHAVE_ASM_AVX2=OFF -DHAVE_ASM_AVX512=OFF \ - -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX="$PWD/ccache" - make -C ccache-${CCACHE_VERSION}/build -j$(nproc) install VERBOSE=1 - else - echo 'Skip building CCcache' - fi - - - name: Configure CCache - shell: bash --login -eo pipefail -o igncr {0} - run: | - export PATH="$PATH:$PWD/ccache/bin" - ccache --set-config=cache_dir="$PWD/ccache" - ccache --set-config=max_size=75M - ccache --set-config=compression=true - ccache -pz - ccache -sv - - - name: Cache Python virtualenv - if: env.ACT != 'true' - uses: actions/cache@v3 - with: - path: venv - key: cygwin-python-venv-${{ hashFiles('build_locally.sh', 'scripts/build/**.sh') }}-${{ secrets.cache_ver }} - - - name: Cache compiled third-party libraries - if: env.ACT != 'true' - uses: actions/cache@v3 - with: - path: build/.mqlibs - key: cygwin-third-party-libs-${{ hashFiles('third_party/**') }}-${{ secrets.cache_ver }} - - - name: Configure - env: - PATH: C:\cygwin\bin - shell: bash --login -eo pipefail -o igncr {0} - run: | - export PATH="$PATH:$PWD/ccache/bin" - ./build_locally.sh --cxx --debug-cmake --test --ccache -v --only-pytest --no-gitee \ - --configure-only -c --clean-3rdparty --prefix=$PWD/install \ - --cmake-no-registry - ${{ matrix.cmake_generator }} - - - name: Build - shell: bash --login -eo pipefail -o igncr {0} - run: | - export PATH="$PATH:$PWD/ccache/bin" - ./build_locally.sh --cxx --debug-cmake --test --ccache - - - name: Install - shell: bash --login -eo pipefail -o igncr {0} - run: ./build_locally.sh --install - - - name: Run C++ tests - run: | - cd build - ctest --output-on-failure - - - name: Print CCache statistics - shell: bash --login -eo pipefail -o igncr {0} - run: | - export PATH="$PATH:$PWD/ccache/bin" - ccache -sv - - - name: Save cache for CCache - if: env.ACT != 'true' - uses: martijnhols/actions-cache/save@v3.0.11b - with: - path: ccache - key: cygwin-ccache-${{ steps.get-date.outputs.date }} - - - name: Restore PATH for git - run: Add-Content -Path $env:GITHUB_PATH -Value "C:\Program Files\Git\bin" - - # ============================================================================ - cuda: + if: ${{ false }} runs-on: ubuntu-latest strategy: fail-fast: false @@ -1192,23 +1016,35 @@ jobs: - name: Configure run: >- - ./build_locally.sh --cxx --debug-cmake --gpu --test --ccache --only-pytest --no-gitee + ./build_locally.sh --debug-cmake --gpu --ccache --only-pytest --no-gitee --configure-only -c --clean-3rdparty --prefix="${{ github.workspace }}/install" --cmake-no-registry - name: Build - run: ./build_locally.sh --cxx --debug-cmake --gpu --test --ccache + run: ./build_locally.sh --debug-cmake --gpu --ccache - name: Install run: ./build_locally.sh --install - - name: Run C++ tests + - name: Test tests/st + shell: bash run: | - make -C build test + pwd + source venv/bin/activate + export PYTHONPATH=`pwd`:$PYTHONPATH + which python + which python3 + which pip + echo $PYTHONPATH + pip install -r requirements_test.txt + pip install pytest + python3 -c "import mindquantum as mq;print(mq.qft(range(3)))" + pytest tests/st -rs # ============================================================================ nvhpc: + if: ${{ false }} runs-on: ubuntu-latest strategy: fail-fast: false @@ -1273,102 +1109,12 @@ jobs: - name: Configure run: >- - ./build_locally.sh --cxx --debug-cmake --gpu --test --ccache --only-pytest --no-gitee + ./build_locally.sh --debug-cmake --gpu --ccache --only-pytest --no-gitee --configure-only -c --clean-3rdparty --prefix="${{ github.workspace }}/install" --cmake-no-registry - name: Build - run: ./build_locally.sh --cxx --debug-cmake --gpu --test --ccache + run: ./build_locally.sh --debug-cmake --gpu --ccache - name: Install run: ./build_locally.sh --install - - - name: Run C++ tests - run: | - cd build - catchsegv ctest --output-on-failure - - # ============================================================================ - - # NB: Disabled due to compilation error in tweedledum library - # intel: - # runs-on: ubuntu-latest - # strategy: - # fail-fast: false - # matrix: - # - name: ICX-ICPX - # cc: icx - # cxx: icpx - # apt_pkg: intel-oneapi-compiler-dpcpp-cpp-and-cpp-classic - # - name: DPC++ - # cc: dpcpp - # cxx: dpcpp - # apt_pkg: intel-oneapi-compiler-dpcpp-cpp - - # name: "Intel ${{ matrix.name }} • x64" - # env: - # CC: ${{ matrix.cc }} - # CXX: ${{ matrix.cxx }} - # steps: - # - uses: actions/checkout@v3 - - # - name: Get history and tags for SCM versioning to work - # run: | - # git fetch --prune --unshallow - # git fetch --depth=1 origin +refs/tags/*:refs/tags/* - - # - name: Setup Intel APT - # run: | - # wget https://apt.repos.intel.com/intel-gpg-keys/GPG-PUB-KEY-INTEL-SW-PRODUCTS-2023.PUB - # sudo apt-key add GPG-PUB-KEY-INTEL-SW-PRODUCTS-2023.PUB - # echo "deb https://apt.repos.intel.com/oneapi all main" | sudo tee /etc/apt/sources.list.d/oneAPI.list - # sudo apt-get update -o Dir::Etc::sourcelist="sources.list.d/oneAPI.list" -o APT::Get::List-Cleanup="0" - - # - name: Prepare env - # run: > - # apt-get update && apt-get install -y python3-dev python3-pip - # python3-setuptools python3-wheel python3-venv - # ${{ matrix.apt_pkg }} - # --no-install-recommends - - # - name: Setup CCache - # uses: hendrikmuhs/ccache-action@v1.2.5 - # with: - # key: nvhpc-${{ matrix.nvhpc }}-ccache - # max-size: 75M - - # - name: Cache Python virtualenv - # if: env.ACT != 'true' - # uses: actions/cache@v3 - # with: - # path: venv - # key: intel-python-venv-${{ hashFiles('build_locally.sh', 'scripts/build/**.sh') }}-${{ secrets.cache_ver }} - - # - name: Cache compiled third-party libraries - # if: env.ACT != 'true' - # uses: actions/cache@v3 - # with: - # path: build/.mqlibs - # key: >- - # intel-${{ matrix.cc }}-${{ matrix.cxx }}-clang-third-party-libs-${{ hashFiles('third_party/**') }} - # -${{ secrets.cache_ver }} - - # - name: Configure - # run: | - # source /opt/intel/oneapi/compiler/latest/env/vars.sh - # if [ -f /opt/intel/oneapi/tbb/latest/env/vars.sh ]; then - # source /opt/intel/oneapi/tbb/latest/env/vars.sh - # fi - # ./build_locally.sh --cxx --debug-cmake --test --gpu --no-gitee \ - # --configure-only -c --clean-3rdparty --prefix="${{ github.workspace }}/install" - - # - name: Build - # run: | - # source /opt/intel/oneapi/compiler/latest/env/vars.sh - # if [ -f /opt/intel/oneapi/tbb/latest/env/vars.sh ]; then - # source /opt/intel/oneapi/tbb/latest/env/vars.sh - # fi - # ./build_locally.sh --cxx --debug-cmake --test --gpu - - # - name: Install - # run: ./build_locally.sh --install diff --git a/.jenkins/check/config/filter_cppcheck.txt b/.jenkins/check/config/filter_cppcheck.txt index fb3c7ba08..88fd54aeb 100644 --- a/.jenkins/check/config/filter_cppcheck.txt +++ b/.jenkins/check/config/filter_cppcheck.txt @@ -18,44 +18,33 @@ "mindquantum/ccsrc/python/mqbackend/lib/binding.cc" "duplicateExpression" "mindquantum/ccsrc/python/math/lib/bind_math.cpp" "duplicateExpression" -"mindquantum/ccsrc/include/experimental/decompositions/decomposition_atom.hpp:41" "noExplicitConstructor" -"mindquantum/ccsrc/include/experimental/ops/parametric/gate_base.hpp" "noExplicitConstructor" -"mindquantum/ccsrc/python/mqbackend/include/python/ops/basic_gate.hpp" "noExplicitConstructor" - -"mindquantum/ccsrc/include/config/config.hpp" "noValidConfiguration" -"mindquantum/ccsrc/include/config/details/cxx20_compatibility.hpp" "noValidConfiguration" -"mindquantum/ccsrc/include/config/type_traits.hpp" "noValidConfiguration" -"mindquantum/ccsrc/include/experimental/ops/parametric/angle_base.hpp" "noValidConfiguration" -"mindquantum/ccsrc/include/experimental/ops/parametric/angle_gates.hpp" "noValidConfiguration" +"mindquantum/ccsrc/python/mqbackend/include/python/ops/basic_gate.h" "noExplicitConstructor" + +"mindquantum/ccsrc/include/config/config.h" "noValidConfiguration" +"mindquantum/ccsrc/include/config/details/cxx20_compatibility.h" "noValidConfiguration" +"mindquantum/ccsrc/include/config/type_traits.h" "noValidConfiguration" "mindquantum/tests/decompositions/test_apply_atoms.cpp" "noValidConfiguration" -"mindquantum/ccsrc/include/experimental/decompositions/decomposition_atom.hpp" "operatorEqVarError" -"mindquantum/ccsrc/include/config/details/cxx20_compatibility.hpp" "preprocessorErrorDirective" -"mindquantum/ccsrc/include/experimental/decompositions/rules/config.hpp" "preprocessorErrorDirective" -"mindquantum/ccsrc/include/experimental/ops/parametric/angle_base.hpp" "preprocessorErrorDirective" -"mindquantum/ccsrc/python/core/include/python/details/define_binary_operator_helpers.hpp" "preprocessorErrorDirective" -"mindquantum/ccsrc/python/experimental/lib/ops/ops.cpp" "preprocessorErrorDirective" +"mindquantum/ccsrc/include/config/details/cxx20_compatibility.h" "preprocessorErrorDirective" "mindquantum/tests/decompositions/test_apply_atoms.cpp" "preprocessorErrorDirective" "mindquantum/tests/ops/test_angle_parametric_gates.cpp" "preprocessorErrorDirective" -"mindquantum/ccsrc/lib/experimental/decompositions/atom_storage.cpp" "stlIfFind" -"mindquantum/ccsrc/lib/experimental/decompositions/gate_decomposer.cpp" "stlIfFind" "mindquantum/ccsrc/lib/simulator/vector/detail/cpu_common/cpu_vector_core_policy.cpp" "syntaxError" -"mindquantum/ccsrc/include/core/parameter_resolver_external_ops.hpp:90" "syntaxError" -"mindquantum/ccsrc/include/core/sparse/algo.hpp:73" "syntaxError" -"mindquantum/ccsrc/include/ops/gates/terms_operator_base_external_ops.hpp:92" "syntaxError" +"mindquantum/ccsrc/include/core/parameter_resolver_external_ops.h:90" "syntaxError" +"mindquantum/ccsrc/include/core/sparse/algo.h:73" "syntaxError" +"mindquantum/ccsrc/include/ops/gates/terms_operator_base_external_ops.h:92" "syntaxError" "mindquantum/ccsrc/python/mqbackend/lib/binding.cc:184" "syntaxError" -"mindquantum/ccsrc/python/mqbackend/lib/details/define_terms_ops.hpp" "syntaxError" +"mindquantum/ccsrc/python/mqbackend/lib/details/define_terms_ops.h" "syntaxError" "mindquantum/ccsrc/lib/simulator/densitymatrix/detail/cpu_common/cpu_densitymatrix_core_policy.cpp" "syntaxError" "mindquantum/ccsrc/lib/simulator/densitymatrix/detail/cpu_common/cpu_densitymatrix_core_condition.cpp" "syntaxError" "mindquantum/ccsrc/lib/simulator/densitymatrix/detail/cpu_common/cpu_densitymatrix_core_gate_expect.cpp" "syntaxError" -"mindquantum/ccsrc/include/core/numba_wrapper.hpp" "uninitMemberVar" +"mindquantum/ccsrc/include/core/numba_wrapper.h" "uninitMemberVar" -"mindquantum/ccsrc/include/core/sparse/paulimat.hpp" "unknownMacro" -"mindquantum/ccsrc/include/core/sparse/paulimat.hpp:58" "unknownMacro" +"mindquantum/ccsrc/include/core/sparse/paulimat.h" "unknownMacro" +"mindquantum/ccsrc/include/core/sparse/paulimat.h:58" "unknownMacro" "mindquantum/ccsrc/lib/simulator/vector/detail/cpu_avx_double/cpu_vector_core_gate_expect.cpp" "unknownMacro" "mindquantum/ccsrc/lib/simulator/vector/detail/cpu_avx_double/cpu_vector_core_matrix_gate.cpp" "unknownMacro" "mindquantum/ccsrc/lib/simulator/vector/detail/cpu_common/cpu_vector_core_condition.cpp" "unknownMacro" @@ -76,21 +65,12 @@ "mindquantum/ccsrc/lib/simulator/densitymatrix/detail/cpu_common/cpu_densitymatrix_core_swap_like.cpp" "unknownMacro" "mindquantum/ccsrc/lib/simulator/densitymatrix/detail/cpu_common/cpu_densitymatrix_core_gate_expect.cpp" "unknownMacro" "mindquantum/ccsrc/lib/simulator/densitymatrix/detail/cpu_common/cpu_densitymatrix_core_matrix_gate.cpp" "unknownMacro" -"mindquantum/ccsrc/include/simulator/vector/detail/cpu_vector_policy.hpp" "unknownMacro" -"mindquantum/ccsrc/include/simulator/densitymatrix/detail/cpu_densitymatrix_policy.hpp" "unknownMacro" - -"mindquantum/ccsrc/lib/experimental/decompositions/time_evolution.cpp" "unreadVariable" - -"mindquantum/ccsrc/include/experimental/ops/gates/details/coeff_policy.hpp:29" "unusedStructMember" - -"mindquantum/ccsrc/include/experimental/ops/parametric/param_names.hpp" "unusedStructMember" -"mindquantum/ccsrc/include/experimental/ops/gates/details/coeff_policy.hpp" "unusedStructMember" +"mindquantum/ccsrc/include/simulator/vector/detail/cpu_vector_policy.h" "unknownMacro" +"mindquantum/ccsrc/include/simulator/densitymatrix/detail/cpu_densitymatrix_policy.h" "unknownMacro" -"mindquantum/ccsrc/include/config/tsl_ordered_map.hpp" "useStlAlgorithm" -"mindquantum/ccsrc/include/experimental/core/control.hpp:79" "useStlAlgorithm" -"mindquantum/ccsrc/include/ops/gates/terms_coeff_dict.hpp" "useStlAlgorithm" +"mindquantum/ccsrc/include/config/tsl_ordered_map.h" "useStlAlgorithm" +"mindquantum/ccsrc/include/ops/gates/terms_coeff_dict.h" "useStlAlgorithm" "mindquantum/ccsrc/include/ops/gates/terms_operator_base.tpp" "useStlAlgorithm" -"mindquantum/ccsrc/lib/experimental/simulator/projectq_simulator.cpp" "useStlAlgorithm" "mindquantum/tests/core/test_circuit_block.cpp" "ctuOneDefinitionRuleViolation" diff --git a/.jenkins/check/config/filter_cpplint.txt b/.jenkins/check/config/filter_cpplint.txt index 5eb70aff5..91e99af89 100644 --- a/.jenkins/check/config/filter_cpplint.txt +++ b/.jenkins/check/config/filter_cpplint.txt @@ -14,10 +14,6 @@ "mindquantum/tests" "runtime/explicit" "mindquantum/tests" "runtime/references" -"mindquantum/ccsrc/cxx_experimental" "readability/braces" -"mindquantum/ccsrc/cxx_experimental" "runtime/references" -"mindquantum/ccsrc/cxx_experimental" "whitespace/forcolon" -"mindquantum/ccsrc/cxx_experimental" "whitespace/newline" "mindquantum/ccsrc" "build/include_subdir" "mindquantum/ccsrc/gate" "build/include_subdir" @@ -27,42 +23,26 @@ "mindquantum/ccsrc/projector" "build/include_subdir" "mindquantum/ccsrc/sparse" "build/include_subdir" -"mindquantum/ccsrc/python/experimental/lib/core/logging.cpp" "build/namespaces_literals" "mindquantum/ccsrc/python/mqbackend/lib/logging.cpp" "build/namespaces_literals" -"mindquantum/ccsrc/python/experimental/lib/core/logging.cpp" "runtime/references" "mindquantum/ccsrc/python/mqbackend/lib/logging.cpp" "runtime/references" "mindquantum/ccsrc/python/mqbackend/lib/binding.cc" "runtime/references" "mindquantum/ccsrc/python/mqbackend/lib/build_env.cpp" "runtime/references" -"mindquantum/ccsrc/cxx_experimental/include/ops/parametric" "runtime/explicit" -"mindquantum/ccsrc/cxx_experimental/include/ops/parametric" "runtime/indentation_namespace" -"mindquantum/ccsrc/cxx_experimental/include/ops/parametric" "whitespace/parens" -"mindquantum/ccsrc/cxx_experimental/include/core/circuit_block.hpp" "build/include" -"mindquantum/ccsrc/cxx_experimental/include/decompositions/atom_storage.hpp" "build/include" -"mindquantum/ccsrc/cxx_experimental/include/decompositions/decomposition_rule.hpp" "build/include" -"mindquantum/ccsrc/cxx_experimental/include/decompositions/details/gate_decomposition_rule_cxx17.hpp" "build/include" -"mindquantum/ccsrc/cxx_experimental/include/decompositions/details/gate_decomposition_rule_cxx20.hpp" "build/include" -"mindquantum/ccsrc/cxx_experimental/include/decompositions/gate_decomposer.hpp" "build/include" -"mindquantum/ccsrc/cxx_experimental/include/decompositions/non_gate_decomposition_rule.hpp" "build/include" -"mindquantum/ccsrc/cxx_experimental/include/decompositions/parametric_atom.hpp" "build/include" -"mindquantum/ccsrc/cxx_experimental/include/decompositions/trivial_atom.hpp" "build/include" -"mindquantum/ccsrc/cxx_experimental/include/ops/parametric/register_gate_type.hpp" "build/include" -"mindquantum/ccsrc/cxx_experimental/include/ops/parametric/substitutions.hpp" "build/include" -"mindquantum/ccsrc/cxx_experimental/include/simulator/simulator_base.hpp" "build/include" -"mindquantum/ccsrc/cxx_experimental/include/decompositions/decomposition_atom.hpp" "readability/casting" -"mindquantum/ccsrc/cxx_experimental/include/decompositions/details/decomposition_param.hpp" "whitespace/line_length" -"mindquantum/ccsrc/cxx_experimental/include/decompositions/decomposition_atom.hpp" "whitespace/semicolon" -"mindquantum/ccsrc/cxx_experimental/include/decompositions/decomposition_rule.hpp" "whitespace/semicolon" -"mindquantum/ccsrc/cxx_experimental/include/decompositions/details/decomposition_param.hpp" "whitespace/semicolon" -"mindquantum/ccsrc/cxx_experimental/include/ops/parametric/register_gate_type.hpp" "whitespace/semicolon" -"mindquantum/ccsrc/include/simulator/vector/detail/cpu_vector_policy.hpp" "readability/casting" -"mindquantum/ccsrc/include/core/parameter_resolver.hpp" "build/include" +"mindquantum/ccsrc/include/simulator/vector/detail/cpu_vector_policy.h" "readability/casting" +"mindquantum/ccsrc/include/core/parameter_resolver.h" "build/include" -"mindquantum/ccsrc/include/simulator/alignedallocator.hpp" "whitespace/parens" +"mindquantum/ccsrc/include/simulator/alignedallocator.h" "whitespace/parens" "mindquantum/ccsrc/lib/math/operators/transform/bravyi_kitaev_superfast.cpp" "runtime/references" "mindquantum/ccsrc/python/math/lib/bind_math.cpp" "runtime/references" "mindquantum/ccsrc/lib/simulator/vector/detail/cpu_common/cpu_vector_core_policy.cpp" "runtime/references" "mindquantum/ccsrc/lib/simulator/vector/detail/gpu/gpu_vector_core_policy.cu" "runtime/references" -"mindquantum/ccsrc/include/simulator/vector/detail/cpu_vector_policy.hpp" "runtime/references" -"mindquantum/ccsrc/include/math/operators/qubit_operator_view.hpp" "runtime/references" +"mindquantum/ccsrc/include/simulator/vector/detail/cpu_vector_policy.h" "runtime/references" +"mindquantum/ccsrc/include/math/operators/qubit_operator_view.h" "runtime/references" +"mindquantum/tests/cmake-ldtest/shared_test.cpp" "build/include_subdir" +"mindquantum/ccsrc/include/config/format/std_complex.h" "runtime/references" +"mindquantum/ccsrc/include/device/mapping.h" "runtime/references" +"mindquantum/ccsrc/include/config/format/std_optional.h" "runtime/references" +"mindquantum/ccsrc/include/config/tsl_ordered_map.h" "runtime/references" +"mindquantum/ccsrc/include/math/operators/fermion_operator_view.h" "runtime/references" +"mindquantum/tests/cmake-ldtest/shared_lib.cpp" "build/include_subdir" diff --git a/.jenkins/check/config/whitelizard.txt b/.jenkins/check/config/whitelizard.txt index 613b9cb2a..8846d6b79 100644 --- a/.jenkins/check/config/whitelizard.txt +++ b/.jenkins/check/config/whitelizard.txt @@ -21,15 +21,12 @@ mindquantum/mindquantum/simulator/mqsim.py:grad_ops mindquantum/mindquantum/simulator/simulator.py:get_expectation_with_grad mindquantum/mindquantum/third_party/unitary_cc.py:uccsd_singlet_generator mindquantum/mindquantum/io/display/circuit_text_drawer.py:brick_model -mindquantum/mindquantum/experimental/_symengine_utilities.py:symbols mindquantum/algorithm/compiler/decompose/universal_decompose/two_qubit_decompose.py:kak_decompose -mindquantum/ccsrc/include/ops/gates.hpp:mindquantum::GetGateByName +mindquantum/ccsrc/include/ops/gates.h:mindquantum::GetGateByName mindquantum/ccsrc/include/ops/gates/qubit_operator.tpp:mindquantum::ops::QubitOperator::sparse_matrix mindquantum/ccsrc/include/ops/gates/qubit_operator.tpp:mindquantum::ops::mindquantum::ops::QubitOperator::get_op_matrix.QubitOperator::sparse_matrix mindquantum/ccsrc/mindquantum/src/binding.cc:mindquantum::PYBIND11_MODULE -mindquantum/ccsrc/python/experimental/lib/core/symengine.cpp:mindquantum::python::init_symengine_basic_types -mindquantum/ccsrc/python/experimental/lib/ops/ops.cpp:init_mindquantum_ops mindquantum/ccsrc/python/mqbackend/lib/binding.cc:PYBIND11_MODULE mindquantum/ccsrc/python/mqbackend/lib/fermion_operators.cpp:init_fermion_operators mindquantum/ccsrc/python/mqbackend/lib/qubit_operators.cpp:init_qubit_operators @@ -38,9 +35,9 @@ mindquantum/ccsrc/python/mqbackend/lib/binding.cc:BindOther mindquantum/ccsrc/python/mqbackend/lib/binding.cc:init_fermion_operators mindquantum/ccsrc/python/mqbackend/lib/binding.cc:init_qubit_operators mindquantum/ccsrc/lib/simulator/vector/detail/runtime/cmd.cpp:mindquantum::sim::rt::cmd -mindquantum/ccsrc/include/math/tensor/ops_cpu/advance_math.hpp:tensor::ops::cpu::ElementFunc +mindquantum/ccsrc/include/math/tensor/ops_cpu/advance_math.h:tensor::ops::cpu::ElementFunc mindquantum/mindquantum/core/parameterresolver/parameterresolver.py:__init__ -mindquantum/ccsrc/python/math/lib/bind_math.cpp:BindQubitOperator +mindquantum/ccsrc/python/math/lib/bind_math.cpp:mindquantum::python::BindQubitOperator ccsrc/lib/simulator/vector/detail/cpu_avx_double/cpu_vector_core_gate_expect.cpp:mindquantum::sim::vector::detail::CPUVectorPolicyAvxDouble::ExpectDiffSingleQubitMatrix TEST_CASE diff --git a/.whitelizard.txt b/.whitelizard.txt index bd1176e3f..3180f6387 100644 --- a/.whitelizard.txt +++ b/.whitelizard.txt @@ -21,16 +21,14 @@ mindquantum/simulator/mqsim.py:grad_ops mindquantum/simulator/simulator.py:get_expectation_with_grad mindquantum/third_party/unitary_cc.py:uccsd_singlet_generator mindquantum/io/display/circuit_text_drawer.py:brick_model -mindquantum/experimental/_symengine_utilities.py:symbols mindquantum/core/parameterresolver/parameterresolver.py:__init__ mindquantum/algorithm/compiler/decompose/universal_decompose/two_qubit_decompose.py:kak_decompose +mindquantum/simulator/mqsim.py:get_expectation_with_grad.grad_ops -ccsrc/include/ops/gates.hpp:mindquantum::GetGateByName +ccsrc/include/ops/gates.h:mindquantum::GetGateByName ccsrc/include/ops/gates/qubit_operator.tpp:mindquantum::ops::QubitOperator::sparse_matrix ccsrc/include/ops/gates/qubit_operator.tpp:mindquantum::ops::mindquantum::ops::QubitOperator::get_op_matrix.QubitOperator::sparse_matrix ccsrc/mindquantum/src/binding.cc:mindquantum::PYBIND11_MODULE -ccsrc/python/experimental/lib/core/symengine.cpp:mindquantum::python::init_symengine_basic_types -ccsrc/python/experimental/lib/ops/ops.cpp:init_mindquantum_ops ccsrc/python/mqbackend/lib/binding.cc:init_qubit_operators ccsrc/python/mqbackend/lib/binding.cc:init_fermion_operators ccsrc/python/mqbackend/lib/binding.cc:BindOther @@ -38,8 +36,8 @@ ccsrc/python/mqbackend/lib/fermion_operators.cpp:init_fermion_operators ccsrc/python/mqbackend/lib/qubit_operators.cpp:init_qubit_operators ccsrc/python/mqbackend/lib/terms_operators.cpp:init_terms_operators ccsrc/lib/simulator/vector/detail/runtime/cmd.cpp:mindquantum::sim::rt::cmd -ccsrc/python/math/lib/bind_math.cpp:BindQubitOperator -ccsrc/include/math/tensor/ops_cpu/advance_math.hpp:tensor::ops::cpu::ElementFunc +ccsrc/python/math/lib/bind_math.cpp:mindquantum::python::BindQubitOperator +ccsrc/include/math/tensor/ops_cpu/advance_math.h:tensor::ops::cpu::ElementFunc ccsrc/lib/simulator/vector/detail/cpu_avx_double/cpu_vector_core_gate_expect.cpp:mindquantum::sim::vector::detail::CPUVectorPolicyAvxDouble::ExpectDiffSingleQubitMatrix TEST_CASE mindquantum::sim::vector::detail::VectorState::ApplyGate diff --git a/CMakeLists.txt b/CMakeLists.txt index cab237acb..f2cb82ecd 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -57,7 +57,7 @@ set(MQ_INSTALL_DOCDIR "${CMAKE_INSTALL_DATADIR}/doc/mindquantum") set(MQ_INSTALL_CMAKEDIR "${MQ_INSTALL_DATADIR}/cmake") set(MQ_INSTALL_3RDPARTYDIR "${MQ_INSTALL_LIBDIR}/third_party") -add_compile_options(-Wall -Wextra -Wfloat-equal) +# add_compile_options(-Wall -Wextra -Wfloat-equal) foreach( _type diff --git a/INSTALL.md b/INSTALL.md index e6a254a91..fad8fa108 100644 --- a/INSTALL.md +++ b/INSTALL.md @@ -97,7 +97,6 @@ Here is an exhaustive list of all CMake options available for customization | DISABLE_FORTRAN_COMPILER | Forcefully disable the Fortran compiler for some 3rd party libraries | ON | | ENABLE_CMAKE_DEBUG | Enable verbose output to debug CMake issues | OFF | | ENABLE_CUDA | Enable the use of CUDA code | OFF | -| ENABLE_CXX_EXPERIMENTAL | Enable the building of the (new) experimental C++ backend | OFF | | ENABLE_GITEE | Use Gitee instead of GitHub for (some) third-party dependencies | OFF | | ENABLE_MD | Use /MD, /MDd flags when compiling (MSVC only) | OFF | | ENABLE_MT | Use /MT, /MTd flags when compiling (MSVC only) | OFF | diff --git a/INSTALL_cn.md b/INSTALL_cn.md index 66d2d8b0e..1fb8b3925 100644 --- a/INSTALL_cn.md +++ b/INSTALL_cn.md @@ -96,7 +96,6 @@ MQ_DELOCATE_WHEEL=1 python3 -m build . | DISABLE_FORTRAN_COMPILER | 对于一些第三方库,强制禁止 Fortran 编译器 | ON | | ENABLE_CMAKE_DEBUG | 启用详细输出来调试CMAKE | OFF | | ENABLE_CUDA | 启用使用CUDA代码 | OFF | -| ENABLE_CXX_EXPERIMENTAL | 启用(新的)实验C++后端的构建 | OFF | | ENABLE_GITEE | 使用gitee代替github作为(某些)第三方依赖 | OFF | | ENABLE_MD | 编译时使用 /MD, /MDd 标志 (仅MSVC) | OFF | | ENABLE_MT | 编译时使用 /MT, /MTd 标志 (仅MSVC) | OFF | diff --git a/build.bat b/build.bat index 8bfe608b4..9f39505da 100644 --- a/build.bat +++ b/build.bat @@ -162,11 +162,6 @@ rem ============================================================================ shift & shift & goto :initial ) - if /I "%1" == "/Cxx" ( - set enable_cxx=1 - shift & goto :initial - ) - if /I "%1" == "/Debug" ( set build_type=Debug shift & goto :initial @@ -372,7 +367,6 @@ call %SCRIPTDIR%\dos\build_cmake_option.bat CLEAN_3RDPARTY_INSTALL_DIR !do_clean call %SCRIPTDIR%\dos\build_cmake_option.bat ENABLE_ANALYZER !enable_analyzer! call %SCRIPTDIR%\dos\build_cmake_option.bat ENABLE_CMAKE_DEBUG !cmake_debug_mode! call %SCRIPTDIR%\dos\build_cmake_option.bat ENABLE_CUDA !enable_gpu! -call %SCRIPTDIR%\dos\build_cmake_option.bat ENABLE_CXX_EXPERIMENTAL !enable_cxx! call %SCRIPTDIR%\dos\build_cmake_option.bat ENABLE_GITEE !enable_gitee! call %SCRIPTDIR%\dos\build_cmake_option.bat ENABLE_LOGGING !enable_logging! call %SCRIPTDIR%\dos\build_cmake_option.bat ENABLE_LOGGING_DEBUG_LEVEL !logging_enable_debug! @@ -527,7 +521,6 @@ rem ============================================================================ echo /CleanBuildDir Delete build directory before building echo /CleanCache Re-run CMake with a clean CMake cache echo /CleanVenv Delete Python virtualenv before building - echo /Cxx (experimental) Enable MindQuantum C++ support echo /Debug Build in debug mode echo /Delocate Delocate the binary wheels after build is finished echo (enabled by default; pass /NoDelocate to disable) diff --git a/build.ps1 b/build.ps1 index f7a128411..b99c4125e 100644 --- a/build.ps1 +++ b/build.ps1 @@ -252,7 +252,6 @@ $cmake_option_names = @{ cmake_debug_mode = 'ENABLE_CMAKE_DEBUG' do_clean_3rdparty = 'CLEAN_3RDPARTY_INSTALL_DIR' enable_analyzer = 'ENABLE_ANALYZER' - enable_cxx = 'ENABLE_CXX_EXPERIMENTAL' enable_gitee = 'ENABLE_GITEE' enable_gpu = 'ENABLE_CUDA' enable_logging = 'ENABLE_LOGGING' @@ -519,9 +518,6 @@ Do not use the CMake registry to find packages .PARAMETER Config Path to INI configuration file with default values for the parameters -.PARAMETER Cxx -(experimental) Enable MindQuantum C++ support - .PARAMETER Debug Build in debug mode diff --git a/build.sh b/build.sh index ac0f5b50e..ab8b1e040 100755 --- a/build.sh +++ b/build.sh @@ -31,7 +31,6 @@ if [[ "${DEVCLOUD_CI:-0}" == "1" ]]; then echo "Detected MindSpore/MindQuantum CI" _IS_MINDSPORE_CI=1 fi -export PIP_INDEX_URL="https://mirrors.aliyun.com/pypi/simple" # ============================================================================== # Load common bash helper functions @@ -222,7 +221,6 @@ declare_AA cmake_option_names set_AA cmake_option_names cmake_debug_mode ENABLE_CMAKE_DEBUG set_AA cmake_option_names do_clean_3rdparty CLEAN_3RDPARTY_INSTALL_DIR set_AA cmake_option_names enable_analyzer ENABLE_ANALYZER -set_AA cmake_option_names enable_cxx ENABLE_CXX_EXPERIMENTAL set_AA cmake_option_names enable_gitee ENABLE_GITEE set_AA cmake_option_names enable_gpu ENABLE_CUDA set_AA cmake_option_names enable_logging ENABLE_LOGGING diff --git a/build_locally.bat b/build_locally.bat index 0f281f2e8..8f58ba9b2 100644 --- a/build_locally.bat +++ b/build_locally.bat @@ -132,11 +132,6 @@ rem ============================================================================ shift & shift & goto :initial ) - if /I "%1" == "/Cxx" ( - set enable_cxx=1 - shift & goto :initial - ) - if /I "%1" == "/Debug" ( set build_type=Debug shift & goto :initial @@ -343,7 +338,6 @@ call %SCRIPTDIR%\dos\build_locally_cmake_option.bat CLEAN_3RDPARTY_INSTALL_DIR ! call %SCRIPTDIR%\dos\build_locally_cmake_option.bat ENABLE_ANALYZER !enable_analyzer! call %SCRIPTDIR%\dos\build_locally_cmake_option.bat ENABLE_CMAKE_DEBUG !cmake_debug_mode! call %SCRIPTDIR%\dos\build_locally_cmake_option.bat ENABLE_CUDA !enable_gpu! -call %SCRIPTDIR%\dos\build_locally_cmake_option.bat ENABLE_CXX_EXPERIMENTAL !enable_cxx! call %SCRIPTDIR%\dos\build_locally_cmake_option.bat ENABLE_DOCUMENTATION !do_docs! call %SCRIPTDIR%\dos\build_locally_cmake_option.bat ENABLE_GITEE !enable_gitee! call %SCRIPTDIR%\dos\build_locally_cmake_option.bat ENABLE_LOGGING !enable_logging! @@ -538,7 +532,6 @@ exit /B 0 echo /CleanCache Re-run CMake with a clean CMake cache echo /CleanVenv Delete Python virtualenv before building echo /ConfigureOnly Stop after the CMake configure and generation steps (ie. before building MindQuantum) - echo /Cxx (experimental) Enable MindQuantum C++ support echo /Debug Build in debug mode echo /DebugCMake Enable debugging mode for CMake configuration step echo /Doc, /Docs Setup the Python virtualenv for building the documentation and ask CMake to build the diff --git a/build_locally.ps1 b/build_locally.ps1 index 200d42625..7863bfbba 100644 --- a/build_locally.ps1 +++ b/build_locally.ps1 @@ -240,7 +240,6 @@ $cmake_args = @('-DIN_PLACE_BUILD:BOOL=ON' "-DENABLE_ANALYZER:BOOL={0}" -f $CMAKE_BOOL[$enable_analyzer] "-DENABLE_CMAKE_DEBUG:BOOL={0}" -f $CMAKE_BOOL[$cmake_debug_mode] "-DENABLE_CUDA:BOOL={0}" -f $CMAKE_BOOL[$enable_gpu] - "-DENABLE_CXX_EXPERIMENTAL:BOOL={0}" -f $CMAKE_BOOL[$enable_cxx] "-DENABLE_DOCUMENTATION:BOOL={0}" -f $CMAKE_BOOL[$do_docs] "-DENABLE_GITEE:BOOL={0}" -f $CMAKE_BOOL[$enable_gitee] "-DENABLE_LOGGING:BOOL={0}" -f $CMAKE_BOOL[$enable_logging] @@ -439,9 +438,6 @@ Path to INI configuration file with default values for the parameters .PARAMETER ConfigureOnly Stop after the CMake configure and generation steps (ie. before building MindQuantum) -.PARAMETER Cxx -(experimental) Enable MindQuantum C++ support - .PARAMETER Debug Build in debug mode diff --git a/build_locally.sh b/build_locally.sh index 1ac7b5783..21afc7468 100755 --- a/build_locally.sh +++ b/build_locally.sh @@ -168,7 +168,6 @@ cmake_args=(-DIN_PLACE_BUILD:BOOL=ON -DENABLE_ANALYZER:BOOL="${CMAKE_BOOL[$enable_analyzer]}" -DENABLE_CMAKE_DEBUG:BOOL="${CMAKE_BOOL[$cmake_debug_mode]}" -DENABLE_CUDA:BOOL="${CMAKE_BOOL[$enable_gpu]}" - -DENABLE_CXX_EXPERIMENTAL:BOOL="${CMAKE_BOOL[$enable_cxx]}" -DENABLE_DOCUMENTATION:BOOL="${CMAKE_BOOL[$do_docs]}" -DENABLE_GITEE:BOOL="${CMAKE_BOOL[$enable_gitee]}" -DENABLE_LOGGING:BOOL="${CMAKE_BOOL[$enable_logging]}" diff --git a/ccsrc/CMakeLists.txt b/ccsrc/CMakeLists.txt index 26d24f1d9..dac8baf3b 100644 --- a/ccsrc/CMakeLists.txt +++ b/ccsrc/CMakeLists.txt @@ -35,30 +35,6 @@ target_link_libraries( # ============================================================================== -if(ENABLE_CXX_EXPERIMENTAL) - add_library(mq_cxx_nextgen STATIC) - set_target_properties(mq_cxx_nextgen PROPERTIES POSITION_INDEPENDENT_CODE TRUE) - append_to_property(mq_install_targets GLOBAL mq_cxx_nextgen) - target_compile_features(mq_cxx_nextgen PUBLIC $,cxx_std_20,cxx_std_17>) - force_at_least_cxx17_workaround(mq_cxx_nextgen) - - target_link_libraries( - mq_cxx_nextgen - PUBLIC ${MQ_OPENMP_TARGET} - Threads::Threads - cxx20_compat - cmake_config - include_lib - mindquantum::json - mindquantum::symengine - mindquantum::tweedledum - mq_base - mq_projectq_exp - mindquantum_setup) -endif() - -# ============================================================================== - add_subdirectory(include) add_subdirectory(lib) add_subdirectory(python) diff --git a/ccsrc/include/CMakeLists.txt b/ccsrc/include/CMakeLists.txt index 7b38c51f2..ab5f35048 100644 --- a/ccsrc/include/CMakeLists.txt +++ b/ccsrc/include/CMakeLists.txt @@ -19,19 +19,19 @@ # lint_cmake: -whitespace/indent set(MQ_BASE_HEADERS - config/popcnt.hpp - config/config.hpp - config/type_traits.hpp - core/sparse/algo.hpp - core/sparse/csrhdmatrix.hpp - core/sparse/paulimat.hpp - core/sparse/sparse_utils.hpp - core/mq_base_types.hpp - core/utils.hpp - ops/basic_gate.hpp - ops/gates.hpp - ops/hamiltonian.hpp - ops/projector.hpp) + config/popcnt.h + config/config.h + config/type_traits.h + core/sparse/algo.h + core/sparse/csrhdmatrix.h + core/sparse/paulimat.h + core/sparse/sparse_utils.h + core/mq_base_types.h + core/utils.h + ops/basic_gate.h + ops/gates.h + ops/hamiltonian.h + ops/projector.h) target_sources(mq_base PRIVATE $) target_include_directories(mq_base PUBLIC $ $) @@ -52,10 +52,3 @@ install( PATTERN "CPPLINT.cfg" EXCLUDE) # ============================================================================= - -if(ENABLE_CXX_EXPERIMENTAL) - add_subdirectory(experimental) - install(DIRECTORY ${CMAKE_CURRENT_LIST_DIR}/experimental DESTINATION ${MQ_INSTALL_INCLUDEDIR}/) -endif() - -# ============================================================================= diff --git a/ccsrc/include/config/common_type.hpp b/ccsrc/include/config/common_type.h similarity index 79% rename from ccsrc/include/config/common_type.hpp rename to ccsrc/include/config/common_type.h index 7c171dcf6..b80f9229c 100644 --- a/ccsrc/include/config/common_type.hpp +++ b/ccsrc/include/config/common_type.h @@ -1,23 +1,22 @@ -// Copyright 2022 -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. +/** + * Copyright (c) Huawei Technologies Co., Ltd. 2022. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ #ifndef MQ_CONFIG_COMMON_TYPE_HPP #define MQ_CONFIG_COMMON_TYPE_HPP -#include -#include - // ============================================================================= namespace mindquantum::traits { diff --git a/ccsrc/include/config/complex_cast.hpp b/ccsrc/include/config/complex_cast.h similarity index 60% rename from ccsrc/include/config/complex_cast.hpp rename to ccsrc/include/config/complex_cast.h index fd2ed39a7..7ae097486 100644 --- a/ccsrc/include/config/complex_cast.hpp +++ b/ccsrc/include/config/complex_cast.h @@ -1,16 +1,18 @@ -// Copyright 2022 -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. +/** + * Copyright (c) Huawei Technologies Co., Ltd. 2022. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ #ifndef MQ_CONFIG_COMPLEX_CAST_HPP #define MQ_CONFIG_COMPLEX_CAST_HPP @@ -19,7 +21,7 @@ #include #include -#include "config/type_traits.hpp" +#include "config/type_traits.h" namespace mindquantum { template diff --git a/ccsrc/include/config/concepts.hpp b/ccsrc/include/config/concepts.h similarity index 55% rename from ccsrc/include/config/concepts.hpp rename to ccsrc/include/config/concepts.h index 5b8130d42..59fe65525 100644 --- a/ccsrc/include/config/concepts.hpp +++ b/ccsrc/include/config/concepts.h @@ -1,16 +1,18 @@ -// Copyright 2022 -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. +/** + * Copyright (c) Huawei Technologies Co., Ltd. 2022. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ #ifndef MQ_CONFIG_CONCEPTS_HPP #define MQ_CONFIG_CONCEPTS_HPP @@ -18,8 +20,8 @@ #include #include -#include "config/config.hpp" -#include "config/type_traits.hpp" +#include "config/config.h" +#include "config/type_traits.h" namespace mindquantum::concepts { template diff --git a/ccsrc/include/config/config.hpp b/ccsrc/include/config/config.h similarity index 67% rename from ccsrc/include/config/config.hpp rename to ccsrc/include/config/config.h index b034e6408..e33f167eb 100644 --- a/ccsrc/include/config/config.hpp +++ b/ccsrc/include/config/config.h @@ -1,30 +1,32 @@ -// Copyright 2022 -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. +/** + * Copyright (c) Huawei Technologies Co., Ltd. 2022. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ #ifndef MQ_CONFIG_CONFIG_HPP #define MQ_CONFIG_CONFIG_HPP -#include "config/cmake_config.hpp" +#include "config/cmake_config.h" #ifdef __CUDACC__ -# include "config/cuda20_config.hpp" +# include "config/cuda20_config.h" #else -# include "config/cxx20_config.hpp" +# include "config/cxx20_config.h" #endif // __CUDACC__ -#include "config/details/clang_version.hpp" -#include "config/details/cxx20_compatibility.hpp" -#include "config/details/macros.hpp" -#include "config/type_traits.hpp" +#include "config/details/clang_version.h" +#include "config/details/cxx20_compatibility.h" +#include "config/details/macros.h" +#include "config/type_traits.h" // ============================================================================= @@ -60,9 +62,9 @@ #ifndef MQ_IS_CLANG_VERSION_LESS # define MQ_IS_CLANG_VERSION_LESS(major, minor) \ - (defined __clang__) && (MQ_CLANG_MAJOR < major) && (MQ_CLANG_MINOR < minor) + (defined __clang__) && (MQ_CLANG_MAJOR < (major)) && (MQ_CLANG_MINOR < (minor)) # define MQ_IS_CLANG_VERSION_LESS_EQUAL(major, minor) \ - (defined __clang__) && (MQ_CLANG_MAJOR <= major) && (MQ_CLANG_MINOR <= minor) + (defined __clang__) && (MQ_CLANG_MAJOR <= (major)) && (MQ_CLANG_MINOR <= (minor)) #endif // MQ_IS_CLANG_VERSION_LESS /*! diff --git a/ccsrc/include/config/constexpr_type_name.hpp b/ccsrc/include/config/constexpr_type_name.h similarity index 81% rename from ccsrc/include/config/constexpr_type_name.hpp rename to ccsrc/include/config/constexpr_type_name.h index 087d9395a..f017a4a7f 100644 --- a/ccsrc/include/config/constexpr_type_name.hpp +++ b/ccsrc/include/config/constexpr_type_name.h @@ -1,16 +1,18 @@ -// Copyright 2022 -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. +/** + * Copyright (c) Huawei Technologies Co., Ltd. 2022. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ #ifndef MQ_CONFIG_CONSTEXPR_TYPE_NAME #define MQ_CONFIG_CONSTEXPR_TYPE_NAME @@ -18,7 +20,7 @@ #include #include -#include "config/config.hpp" +#include "config/config.h" // ============================================================================= diff --git a/ccsrc/include/config/conversion.hpp b/ccsrc/include/config/conversion.h similarity index 52% rename from ccsrc/include/config/conversion.hpp rename to ccsrc/include/config/conversion.h index 1e4eff627..ef6063f13 100644 --- a/ccsrc/include/config/conversion.hpp +++ b/ccsrc/include/config/conversion.h @@ -1,16 +1,18 @@ -// Copyright 2022 -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. +/** + * Copyright (c) Huawei Technologies Co., Ltd. 2022. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ #ifndef MQ_CONFIG_CONVERSION_HPP #define MQ_CONFIG_CONVERSION_HPP diff --git a/ccsrc/include/config/details/binary_operators_helpers.hpp b/ccsrc/include/config/details/binary_operators_helpers.hpp deleted file mode 100644 index 07279aa0c..000000000 --- a/ccsrc/include/config/details/binary_operators_helpers.hpp +++ /dev/null @@ -1,194 +0,0 @@ -// Copyright 2022 -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef MQ_CONFIG_BINARY_OPERATORS_HELPERS_HPP -#define MQ_CONFIG_BINARY_OPERATORS_HELPERS_HPP - -#include -#include - -#include "config/common_type.hpp" -#include "config/config.hpp" - -namespace mindquantum::config::details { -struct plus_equal { - template - static constexpr auto apply(lhs_t& lhs, rhs_t&& rhs) { - return lhs += std::forward(rhs); - } -}; -struct minus_equal { - template - static constexpr auto apply(lhs_t& lhs, rhs_t&& rhs) { - return lhs -= std::forward(rhs); - } -}; -struct multiplies_equal { - template - static constexpr auto apply(lhs_t& lhs, rhs_t&& rhs) { - return lhs *= std::forward(rhs); - } -}; - -struct divides_equal { - template - static constexpr auto apply(lhs_t& lhs, rhs_t&& rhs) { - return lhs /= std::forward(rhs); - } -}; - -template -auto r_value_optimisation(lhs_t&& lhs, rhs_t&& rhs) { - if constexpr (std::is_same_v>) { - // If terms_op is an r-value, we can safely modify and return it instead of creating a temporary - func_t::apply(lhs, std::forward(rhs)); - return std::forward(lhs); - } else { - std::remove_cvref_t tmp{lhs}; - func_t::apply(tmp, std::forward(rhs)); - return tmp; - } -} - -//! Helper function to define an inplace arithmetic operator -/*! - * Both LHS and RHS types will be passed through trait::type in order to compute the common type as: - * \c common_type::type, trait_t::type>. - * - * If both LHS and RHS need to be converted, \c trait::new_type_t will be computed for both LHS and RHS. - * Both of these need to result in the same type. - * - * \tparam func_t Type of in-place operator to use (e.g. \c mindquantum::config::plus_equal) - * \tparam trait_t Type trait used to calculate the common type (if any) between LHS and RHS - * \param lhs LHS of the in-place binary operator - * \param rhs RHS of the in-place binary operator - * \return \c lhs \c += \c rhs, the type of which might be \c lhs_t, \c rhs_t or \c trait_t::new_type - * - * \note You might want to ensure that std::remove_cvref_t is used within the \c trait_t template class - */ -template typename trait_t, typename lhs_t, typename rhs_t> -auto arithmetic_op_impl(lhs_t&& lhs, rhs_t&& rhs) { - using left_t = typename trait_t::type; - using right_t = typename trait_t::type; - using common_t = mindquantum::traits::common_type_t; - - // See which of LHS or RHS we need to promote - if constexpr (std::is_same_v) { - return config::details::r_value_optimisation(std::forward(lhs), std::forward(rhs)); - } else if constexpr (std::is_same_v) { - return config::details::r_value_optimisation(std::forward(rhs), std::forward(lhs)); - } else { - /* - * In this case, we need to convert both LHS and RHS (e.g. T> T>) - * -> make sure that both LHS and RHS would lead to same type (e.g. both FermionOperator) - */ - using lhs_new_t = typename trait_t::template new_type_t; - using rhs_new_t = typename trait_t::template new_type_t; - static_assert(std::is_same_v); - lhs_new_t tmp{lhs}; - func_t::apply(tmp, std::forward(rhs)); - return tmp; - } -} - -//! Helper function to define an inplace arithmetic operator -/*! - * Only the LHS type will be passed through trait::type in order to compute the common type, which is then calculated - * as: \c common_type::type, rhs_t>. - * - * If both LHS and RHS need to be converted, \c trait::new_type_t will be computed for both LHS and RHS. - * Both of these need to result in the same type. - * - * \tparam func_t Type of in-place operator to use (e.g. \c mindquantum::config::plus_equal) - * \tparam trait_t Type trait used to calculate the common type (if any) between LHS and RHS - * \param lhs LHS of the in-place binary operator - * \param rhs RHS of the in-place binary operator - * \return \c lhs \c += \c rhs, the type of which might be \c lhs_t, \c rhs_t or \c trait_t::new_type - */ -template typename trait_t, typename lhs_t, typename scalar_t> -auto arithmetic_scalar_op_impl(lhs_t&& lhs, scalar_t&& scalar) { - using terms_op_t = std::remove_cvref_t; - using common_t - = mindquantum::traits::common_type_t::type, std::remove_cvref_t>; - if constexpr (std::is_same_v::type>) { - return config::details ::r_value_optimisation(std::forward(lhs), std::forward(scalar)); - } else { - return config::details ::r_value_optimisation( - typename trait_t::template new_type_t{lhs}, std::forward(scalar)); - } -} -} // namespace mindquantum::config::details - -// ============================================================================= - -#define MQ_BINOP_COMMA , -#define MQ_BINOP_IMPL_(op_impl, op_impl_t, lhs, rhs) \ - config::details::op_impl(std::forward(lhs), std::forward(rhs)) - -// ----------------------------------------------------------------------------- - -#if MQ_HAS_CONCEPTS -# define MQ_DEFINE_BINOP_SCALAR_LEFT_(op, op_impl, traits_t, lhs_concept, rhs_concept) \ - template \ - auto operator op(scalar_t&& scalar, rhs_t&& rhs) { \ - return MQ_BINOP_IMPL_(arithmetic_scalar_op_impl, op_impl MQ_BINOP_COMMA traits_t, rhs, scalar); \ - } -# define MQ_DEFINE_BINOP_SCALAR_RIGHT_(op, op_impl, traits_t, lhs_concept, rhs_concept) \ - template \ - auto operator op(lhs_t&& lhs, scalar_t&& scalar) { \ - return MQ_BINOP_IMPL_(arithmetic_scalar_op_impl, op_impl MQ_BINOP_COMMA traits_t, lhs, scalar); \ - } -# define MQ_DEFINE_BINOP_TERMS_(op, op_impl, traits_t, lhs_concept, rhs_concept) \ - template \ - auto operator op(lhs_t&& lhs, rhs_t&& rhs) { \ - return MQ_BINOP_IMPL_(arithmetic_op_impl, op_impl MQ_BINOP_COMMA traits_t, lhs, rhs); \ - } -#else -# define MQ_BINOP_COMPLETE_IMPL_(terms_op, lhs_terms_op, rhs_terms_op, lhs_concept, rhs_concept) \ - static_assert(lhs_concept || rhs_concept); \ - if constexpr (lhs_concept && rhs_concept) { \ - return terms_op; \ - } else if constexpr (lhs_concept) { \ - return lhs_terms_op; \ - } else { \ - return rhs_terms_op; \ - } -# define MQ_DEFINE_BINOP_COMMUTATIVE_IMPL(op, op_impl, traits_t, enabling_traits_v, lhs_concept, rhs_concept) \ - template >> \ - auto operator op(lhs_t&& lhs, rhs_t&& rhs) { \ - MQ_BINOP_COMPLETE_IMPL_( \ - (MQ_BINOP_IMPL_(arithmetic_op_impl, op_impl MQ_BINOP_COMMA traits_t, lhs, rhs)), \ - (MQ_BINOP_IMPL_(arithmetic_scalar_op_impl, op_impl MQ_BINOP_COMMA traits_t, lhs, rhs)), \ - (MQ_BINOP_IMPL_(arithmetic_scalar_op_impl, op_impl MQ_BINOP_COMMA traits_t, rhs, lhs)), \ - lhs_concept, rhs_concept) \ - } -# define MQ_DEFINE_BINOP_NON_COMMUTATIVE_IMPL(op, op_impl, op_inv, traits_t, enabling_traits_v, lhs_concept, \ - rhs_concept) \ - template >> \ - auto operator op(lhs_t&& lhs, rhs_t&& rhs) { \ - MQ_BINOP_COMPLETE_IMPL_( \ - (MQ_BINOP_IMPL_(arithmetic_op_impl, op_impl MQ_BINOP_COMMA traits_t, lhs, rhs)), \ - (MQ_BINOP_IMPL_(arithmetic_scalar_op_impl, op_impl MQ_BINOP_COMMA traits_t, lhs, rhs)), (op_inv), \ - lhs_concept, rhs_concept) \ - } -# define MQ_DEFINE_BINOP_SCALAR_RIGHT_ONLY_IMPL(op, op_impl, traits_t, enabling_traits_v) \ - template >> \ - auto operator op(lhs_t&& lhs, scalar_t&& scalar) { \ - return MQ_BINOP_IMPL_(arithmetic_scalar_op_impl, op_impl MQ_BINOP_COMMA traits_t, lhs, scalar); \ - } -#endif // MQ_HAS_CONCEPTS - -// ============================================================================= - -#endif /* MQ_CONFIG_BINARY_OPERATORS_HELPERS_HPP */ diff --git a/ccsrc/include/config/details/clang_version.hpp b/ccsrc/include/config/details/clang_version.h similarity index 66% rename from ccsrc/include/config/details/clang_version.hpp rename to ccsrc/include/config/details/clang_version.h index 8bae03544..bcc79517e 100644 --- a/ccsrc/include/config/details/clang_version.hpp +++ b/ccsrc/include/config/details/clang_version.h @@ -1,16 +1,18 @@ -// Copyright 2021 -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. +/** + * Copyright (c) Huawei Technologies Co., Ltd. 2021. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ #ifndef MQ_CONFIG_CLANG_VERSION_HPP #define MQ_CONFIG_CLANG_VERSION_HPP diff --git a/ccsrc/include/config/details/cxx20_compatibility.hpp b/ccsrc/include/config/details/cxx20_compatibility.h similarity index 53% rename from ccsrc/include/config/details/cxx20_compatibility.hpp rename to ccsrc/include/config/details/cxx20_compatibility.h index fa03336f5..cfc0d9dd6 100644 --- a/ccsrc/include/config/details/cxx20_compatibility.hpp +++ b/ccsrc/include/config/details/cxx20_compatibility.h @@ -1,16 +1,18 @@ -// Copyright 2021 -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. +/** + * Copyright (c) Huawei Technologies Co., Ltd. 2021. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ #ifndef CORE_CXX20_COMPATIBILITY_HPP #define CORE_CXX20_COMPATIBILITY_HPP @@ -62,7 +64,7 @@ concept default_initializable = constructible_from&& requires { template concept convertible_to = is_convertible_v&& requires(add_rvalue_reference_t (&f)()) { static_cast(f()); -}; +} template concept move_constructible = constructible_from&& convertible_to; @@ -72,45 +74,6 @@ concept copy_constructible = move_constructible&& constructible_from&& constructible_from&& convertible_to&& constructible_from&& convertible_to; -// template < class T, class U > -// concept common_reference_with = -// same_as, common_reference_t> -// && convertible_to> -// && convertible_to>; - -// template< class T > -// concept swappable = requires(T& a, T& b) { ranges::swap(a, b); }; - -// template< class T, class U > -// concept swappable_with = -// common_reference_with -// && requires(T&& t, U&& u) { -// ranges::swap(forward(t), forward(t)); -// ranges::swap(forward(u), forward(u)); -// ranges::swap(forward(t), forward(u)); -// ranges::swap(forward(u), forward(t)); -// }; - -// template< class LHS, class RHS > -// concept assignable_from = -// is_lvalue_reference_v -// && common_reference_with&, -// const remove_reference_t&> -// && requires(LHS lhs, RHS&& rhs) { { lhs = forward(rhs) } -> same_as; }; - -// template < class T > -// concept movable = -// is_object_v -// && move_constructible -// && assignable_from -// && swappable; - -// template -// concept copyable = copy_constructible -// && movable -// && assignable_from -// && assignable_from -// && assignable_from; // clang-format on #endif // MQ_HAS_CONCEPTS && !MQ_HAS_CONCEPT_LIBRARY diff --git a/ccsrc/include/config/details/macros.hpp b/ccsrc/include/config/details/macros.h similarity index 74% rename from ccsrc/include/config/details/macros.hpp rename to ccsrc/include/config/details/macros.h index 13bb136f4..5bb4a597b 100644 --- a/ccsrc/include/config/details/macros.hpp +++ b/ccsrc/include/config/details/macros.h @@ -1,16 +1,18 @@ -// Copyright 2020 -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. +/** + * Copyright (c) Huawei Technologies Co., Ltd. 2020. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ #ifndef CORE_DETAILS_MACROS_HPP #define CORE_DETAILS_MACROS_HPP diff --git a/ccsrc/include/config/detected.hpp b/ccsrc/include/config/detected.h similarity index 80% rename from ccsrc/include/config/detected.hpp rename to ccsrc/include/config/detected.h index ccc7cc6af..5d90a857f 100644 --- a/ccsrc/include/config/detected.hpp +++ b/ccsrc/include/config/detected.h @@ -1,21 +1,23 @@ -// Copyright 2021 -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. +/** + * Copyright (c) Huawei Technologies Co., Ltd. 2021. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ #ifndef MQ_CONFIG_DETECTED_HPP #define MQ_CONFIG_DETECTED_HPP -#include "config/config.hpp" +#include "config/config.h" #ifdef HAS_STD_DETECTED_TS2 # include diff --git a/ccsrc/include/config/format/eigen_matrices.h b/ccsrc/include/config/format/eigen_matrices.h new file mode 100644 index 000000000..c81fa4116 --- /dev/null +++ b/ccsrc/include/config/format/eigen_matrices.h @@ -0,0 +1,32 @@ +/** + * Copyright (c) Huawei Technologies Co., Ltd. 2022. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FORMAT_EIGEN_MATRICES_HPP +#define FORMAT_EIGEN_MATRICES_HPP + +#include +#include + +#include +#include + +template +struct fmt::formatter> : fmt::ostream_formatter {}; + +template +struct fmt::formatter> : fmt::ostream_formatter {}; + +#endif /* FORMAT_EIGEN_MATRICES_HPP */ diff --git a/ccsrc/include/config/format/eigen_matrices.hpp b/ccsrc/include/config/format/eigen_matrices.hpp deleted file mode 100644 index 2eb56091e..000000000 --- a/ccsrc/include/config/format/eigen_matrices.hpp +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright 2022 -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef FORMAT_EIGEN_MATRICES_HPP -#define FORMAT_EIGEN_MATRICES_HPP - -#include -#include - -#include -#include - -template -struct fmt::formatter> : fmt::ostream_formatter {}; - -template -struct fmt::formatter> : fmt::ostream_formatter {}; - -#endif /* FORMAT_EIGEN_MATRICES_HPP */ diff --git a/ccsrc/include/config/format/std_complex.hpp b/ccsrc/include/config/format/std_complex.h similarity index 78% rename from ccsrc/include/config/format/std_complex.hpp rename to ccsrc/include/config/format/std_complex.h index 73bc52a2b..587f9a574 100644 --- a/ccsrc/include/config/format/std_complex.hpp +++ b/ccsrc/include/config/format/std_complex.h @@ -1,16 +1,18 @@ -// Copyright 2022 -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. +/** + * Copyright (c) Huawei Technologies Co., Ltd. 2022. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ #ifndef MQ_FORMAT_COMPLEX_HPP #define MQ_FORMAT_COMPLEX_HPP diff --git a/ccsrc/include/config/format/std_optional.h b/ccsrc/include/config/format/std_optional.h new file mode 100644 index 000000000..3f7c9bcc9 --- /dev/null +++ b/ccsrc/include/config/format/std_optional.h @@ -0,0 +1,36 @@ +/** + * Copyright (c) Huawei Technologies Co., Ltd. 2022. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FORMAT_STD_OPTIONAL_HPP +#define FORMAT_STD_OPTIONAL_HPP + +#include + +#include +#include + +template +struct fmt::formatter> : fmt::formatter { + template + auto format(const std::optional& opt, format_context_t& ctx) { + if (opt) { + return fmt::formatter::format(*opt, ctx); + } + return fmt::format_to(ctx.out(), ""); + } +}; + +#endif /* FORMAT_STD_OPTIONAL_HPP */ diff --git a/ccsrc/include/config/format/std_optional.hpp b/ccsrc/include/config/format/std_optional.hpp deleted file mode 100644 index 73b421d62..000000000 --- a/ccsrc/include/config/format/std_optional.hpp +++ /dev/null @@ -1,34 +0,0 @@ -// Copyright 2022 -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef FORMAT_STD_OPTIONAL_HPP -#define FORMAT_STD_OPTIONAL_HPP - -#include - -#include -#include - -template -struct fmt::formatter> : fmt::formatter { - template - auto format(const std::optional& opt, format_context_t& ctx) { - if (opt) { - return fmt::formatter::format(*opt, ctx); - } - return fmt::format_to(ctx.out(), ""); - } -}; - -#endif /* FORMAT_STD_OPTIONAL_HPP */ diff --git a/ccsrc/include/config/format/symengine.hpp b/ccsrc/include/config/format/symengine.hpp deleted file mode 100644 index b0450c972..000000000 --- a/ccsrc/include/config/format/symengine.hpp +++ /dev/null @@ -1,106 +0,0 @@ -// Copyright 2022 -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef FORMAT_SYMENGINE_BASIC_HPP -#define FORMAT_SYMENGINE_BASIC_HPP - -#include - -#include -#include -#include - -#include -#include -#include - -namespace mindquantum::format::details { -template -std::string dumps(SymEngine::RCP obj) { - std::ostringstream oss; - cereal::JSONOutputArchive{oss}(obj); // NOLINT(whitespace/braces) - return oss.str(); -} -template -auto loads(const std::string& string_data) { - SymEngine::RCP symengine_expr; - std::istringstream iss{string_data}; - cereal::JSONInputArchive{iss}(symengine_expr); // NOLINT(whitespace/braces) - return symengine_expr; -} -} // namespace mindquantum::format::details - -//! Custom formatter for a SymEngine::RCP -template -struct fmt::formatter, char_type> { - using basic_t = SymEngine::RCP; - - bool json_output = false; - - FMT_CONSTEXPR auto parse(format_parse_context& ctx) -> decltype(ctx.begin()) { - auto it = ctx.begin(); - if (*it == 'j') { - json_output = true; - ++it; - } - const auto end = ctx.end(); - - if (it != end && *it != '}') { - ctx.error_handler().on_error("invalid type specifier"); - } - - return it; - } - - template - auto format(const basic_t& symengine_expr, format_context_t& ctx) const -> decltype(ctx.out()) { - if (json_output) { - return fmt::format_to(ctx.out(), "{}", mindquantum::format::details::dumps(symengine_expr)); - } - return fmt::format_to(ctx.out(), "{}", SymEngine::str(*symengine_expr)); - } -}; - -//! Custom formatter for a SymEngine::Expression -template -struct fmt::formatter { - using expr_t = SymEngine::Expression; - - FMT_CONSTEXPR auto parse(format_parse_context& ctx) -> decltype(ctx.begin()) { - return ctx.begin(); - } - - template - auto format(const expr_t& symengine_expr, format_context_t& ctx) const -> decltype(ctx.out()) { - return fmt::format_to(ctx.out(), "{}", SymEngine::str(symengine_expr)); - } -}; - -// ============================================================================= - -//! Custom JSON serialization for SymEngine::RCP -template <> -struct nlohmann::adl_serializer> { - static void to_json(json& json_data, const SymEngine::RCP& symengine_expr) { - json_data = fmt::format("{:j}", symengine_expr); - // TODO(dnguyen): This would probably better, but I don't know how to best de-serializing below - // json_data = nlohmann::json::parse(fmt::format("{}", symengine_expr)); - } - - static void from_json(const json& json_data, SymEngine::RCP& symengine_expr) { - symengine_expr = mindquantum::format::details::loads(json_data.get()); - } -}; - -#endif /* FORMAT_SYMENGINE_BASIC_HPP */ diff --git a/ccsrc/include/config/logging.hpp b/ccsrc/include/config/logging.h similarity index 78% rename from ccsrc/include/config/logging.hpp rename to ccsrc/include/config/logging.h index 98124e1e6..23cbf7e92 100644 --- a/ccsrc/include/config/logging.hpp +++ b/ccsrc/include/config/logging.h @@ -1,16 +1,18 @@ -// Copyright 2022 -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. +/** + * Copyright (c) Huawei Technologies Co., Ltd. 2022. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ #ifndef MQ_LOGGING_HPP #define MQ_LOGGING_HPP diff --git a/ccsrc/include/config/openmp.h b/ccsrc/include/config/openmp.h new file mode 100644 index 000000000..03d02229d --- /dev/null +++ b/ccsrc/include/config/openmp.h @@ -0,0 +1,30 @@ +/** + * Copyright (c) Huawei Technologies Co., Ltd. 2022. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef MQ_CONFIG_OPENMP_HPP +#define MQ_CONFIG_OPENMP_HPP + +#include + +namespace omp { +#ifdef _MSC_VER +using idx_t = int64_t; +#else +using idx_t = uint64_t; +#endif // _MSC_VER +} // namespace omp + +#endif /* MQ_CONFIG_OPENMP_HPP */ diff --git a/ccsrc/include/config/openmp.hpp b/ccsrc/include/config/openmp.hpp deleted file mode 100644 index 2ff723de0..000000000 --- a/ccsrc/include/config/openmp.hpp +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright 2022 -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef MQ_CONFIG_OPENMP_HPP -#define MQ_CONFIG_OPENMP_HPP - -#include - -namespace omp { -#ifdef _MSC_VER -using idx_t = int64_t; -#else -using idx_t = uint64_t; -#endif // _MSC_VER -} // namespace omp - -#endif /* MQ_CONFIG_OPENMP_HPP */ diff --git a/ccsrc/include/config/parser/boost_x3_error_handler.hpp b/ccsrc/include/config/parser/boost_x3_error_handler.h similarity index 87% rename from ccsrc/include/config/parser/boost_x3_error_handler.hpp rename to ccsrc/include/config/parser/boost_x3_error_handler.h index 5fa81fa79..709eefb72 100644 --- a/ccsrc/include/config/parser/boost_x3_error_handler.hpp +++ b/ccsrc/include/config/parser/boost_x3_error_handler.h @@ -1,16 +1,18 @@ -// Copyright 2022 -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. +/** + * Copyright (c) Huawei Technologies Co., Ltd. 2022. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ #ifndef BOOST_X3_ERROR_HANDLER_HPP #define BOOST_X3_ERROR_HANDLER_HPP @@ -20,15 +22,15 @@ #include #include -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include -#include +#include -#include "config/logging.hpp" +#include "config/logging.h" namespace mindquantum::parser { template diff --git a/ccsrc/include/config/popcnt.hpp b/ccsrc/include/config/popcnt.h similarity index 95% rename from ccsrc/include/config/popcnt.hpp rename to ccsrc/include/config/popcnt.h index 2286b02e9..609a5bbd7 100644 --- a/ccsrc/include/config/popcnt.hpp +++ b/ccsrc/include/config/popcnt.h @@ -1,5 +1,5 @@ /** - * Copyright 2021 Huawei Technologies Co., Ltd + * Copyright (c) Huawei Technologies Co., Ltd. 2021. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/ccsrc/include/config/real_cast.hpp b/ccsrc/include/config/real_cast.h similarity index 79% rename from ccsrc/include/config/real_cast.hpp rename to ccsrc/include/config/real_cast.h index e1d00ef73..d3c17f729 100644 --- a/ccsrc/include/config/real_cast.hpp +++ b/ccsrc/include/config/real_cast.h @@ -1,16 +1,18 @@ -// Copyright 2022 -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. +/** + * Copyright (c) Huawei Technologies Co., Ltd. 2022. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ #ifndef MQ_CONFIG_REAL_CAST_HPP #define MQ_CONFIG_REAL_CAST_HPP @@ -22,8 +24,8 @@ #include #include -#include "config/config.hpp" -#include "config/type_traits.hpp" +#include "config/config.h" +#include "config/type_traits.h" namespace mindquantum { template diff --git a/ccsrc/include/config/tsl_ordered_map.hpp b/ccsrc/include/config/tsl_ordered_map.h similarity index 79% rename from ccsrc/include/config/tsl_ordered_map.hpp rename to ccsrc/include/config/tsl_ordered_map.h index ea06821c0..66eac5c92 100644 --- a/ccsrc/include/config/tsl_ordered_map.hpp +++ b/ccsrc/include/config/tsl_ordered_map.h @@ -1,16 +1,18 @@ -// Copyright 2022 -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. +/** + * Copyright (c) Huawei Technologies Co., Ltd. 2022. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ #ifndef MQ_CONFIG_TSL_ORDERED_MAP_HPP #define MQ_CONFIG_TSL_ORDERED_MAP_HPP @@ -23,7 +25,7 @@ #include #include -#include "config/config.hpp" +#include "config/config.h" namespace tsl { template diff --git a/ccsrc/include/config/type_promotion.hpp b/ccsrc/include/config/type_promotion.h similarity index 80% rename from ccsrc/include/config/type_promotion.hpp rename to ccsrc/include/config/type_promotion.h index 3b65c2a11..21384abc0 100644 --- a/ccsrc/include/config/type_promotion.hpp +++ b/ccsrc/include/config/type_promotion.h @@ -1,16 +1,18 @@ -// Copyright 2022 -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. +/** + * Copyright (c) Huawei Technologies Co., Ltd. 2022. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ #ifndef MQ_CONFIG_TYPE_PROMOTION_HPP #define MQ_CONFIG_TYPE_PROMOTION_HPP @@ -19,8 +21,8 @@ #include #include -#include "config/config.hpp" -#include "config/type_traits.hpp" +#include "config/config.h" +#include "config/type_traits.h" namespace mindquantum { namespace traits { @@ -123,13 +125,6 @@ struct ComplexCast { } }; -// template -// struct ComplexCast && !traits::is_complex_v>> { -// static auto apply(const src& value) { -// return value; -// } -// }; - template struct ComplexCast::up_cast_t, des>>> { static auto apply(const std::complex& value) { diff --git a/ccsrc/include/config/type_traits.hpp b/ccsrc/include/config/type_traits.h similarity index 85% rename from ccsrc/include/config/type_traits.hpp rename to ccsrc/include/config/type_traits.h index 97edff877..09c066fca 100644 --- a/ccsrc/include/config/type_traits.hpp +++ b/ccsrc/include/config/type_traits.h @@ -1,16 +1,18 @@ -// Copyright 2022 -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. +/** + * Copyright (c) Huawei Technologies Co., Ltd. 2022. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ #ifndef MQ_CONFIG_TRAITS_HPP #define MQ_CONFIG_TRAITS_HPP @@ -19,9 +21,8 @@ #include #include -#include "config/config.hpp" - -#include "details/cxx20_compatibility.hpp" +#include "config/config.h" +#include "details/cxx20_compatibility.h" namespace mindquantum::traits { template diff --git a/ccsrc/include/core/mq_base_types.hpp b/ccsrc/include/core/mq_base_types.h similarity index 91% rename from ccsrc/include/core/mq_base_types.hpp rename to ccsrc/include/core/mq_base_types.h index b19d9dd49..e40002be4 100644 --- a/ccsrc/include/core/mq_base_types.hpp +++ b/ccsrc/include/core/mq_base_types.h @@ -1,5 +1,5 @@ /** - * Copyright 2021 Huawei Technologies Co., Ltd + * Copyright (c) Huawei Technologies Co., Ltd. 2021. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,11 +15,6 @@ */ #ifndef MINDQUANTUM_BASE_TYPES_HPP_ #define MINDQUANTUM_BASE_TYPES_HPP_ -// #ifndef MQONLY -// #include "backend/kernel_compiler/cpu/quantum/quantum_simulator/popcnt.h" -// #else -// #include "./popcnt.hpp" -// #endif #include @@ -34,14 +29,17 @@ namespace mindquantum { #define PRECISION 1e-8 -#define COS1_2(theta) static_cast(cos(theta / 2)) -#define SIN1_2(theta) static_cast(sin(theta / 2)) +#define COS1_2(theta) static_cast(cos((theta) / 2)) +#define SIN1_2(theta) static_cast(sin((theta) / 2)) #define ITER(p, obj) \ - auto p = obj.begin(); \ - p != obj.end(); \ - p++ - -using Index = int64_t; + auto(p) = (obj).begin(); \ + (p) != (obj).end(); \ + (p)++ + +using Index = std::size_t; +using qbit_t = int64_t; +using qbits_t = std::vector; +using index_t = std::size_t; template using VT = std::vector; diff --git a/ccsrc/include/core/numba_wrapper.hpp b/ccsrc/include/core/numba_wrapper.h similarity index 50% rename from ccsrc/include/core/numba_wrapper.hpp rename to ccsrc/include/core/numba_wrapper.h index 216e52097..e9060e181 100644 --- a/ccsrc/include/core/numba_wrapper.hpp +++ b/ccsrc/include/core/numba_wrapper.h @@ -1,16 +1,18 @@ -// Copyright 2022 -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. +/** + * Copyright (c) Huawei Technologies Co., Ltd. 2022. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ #ifndef MQ_CORE_NUMBER_WRAPPER_HPP_ #define MQ_CORE_NUMBER_WRAPPER_HPP_ @@ -19,20 +21,18 @@ #include #include -#include "config/type_promotion.hpp" - -#include "math/tensor/matrix.hpp" -#include "math/tensor/ops.hpp" -#include "math/tensor/ops_cpu/memory_operator.hpp" -#include "math/tensor/tensor.hpp" -#include "math/tensor/traits.hpp" +#include "config/type_promotion.h" +#include "math/tensor/matrix.h" +#include "math/tensor/ops.h" +#include "math/tensor/ops_cpu/memory_operator.h" +#include "math/tensor/tensor.h" +#include "math/tensor/traits.h" namespace mindquantum { struct NumbaMatFunWrapper { using mat_t = void (*)(double, std::complex*); NumbaMatFunWrapper() = default; NumbaMatFunWrapper(uint64_t addr, int dim, tensor::TDtype dtype = tensor::TDtype::Complex128) - : dim(dim), dtype(dtype) { - fun = reinterpret_cast(addr); + : fun(reinterpret_cast(addr)), dim(dim), dtype(dtype) { } auto operator()(double coeff) const { diff --git a/ccsrc/include/core/sparse/algo.hpp b/ccsrc/include/core/sparse/algo.h similarity index 81% rename from ccsrc/include/core/sparse/algo.hpp rename to ccsrc/include/core/sparse/algo.h index 30747b0e6..f5a3c542f 100644 --- a/ccsrc/include/core/sparse/algo.hpp +++ b/ccsrc/include/core/sparse/algo.h @@ -1,5 +1,5 @@ /** - * Copyright 2021 Huawei Technologies Co., Ltd + * Copyright (c) Huawei Technologies Co., Ltd. 2021. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,12 +18,12 @@ #include -#include "config/type_promotion.hpp" - -#include "core/sparse/csrhdmatrix.hpp" -#include "core/sparse/paulimat.hpp" -#include "core/sparse/sparse_utils.hpp" -#include "core/utils.hpp" +#include "config/openmp.h" +#include "config/type_promotion.h" +#include "core/sparse/csrhdmatrix.h" +#include "core/sparse/paulimat.h" +#include "core/sparse/sparse_utils.h" +#include "core/utils.h" namespace mindquantum::sparse { template @@ -73,7 +73,7 @@ std::shared_ptr> PauliMatToCsrHdMatrix(std::shared_ptrp_; THRESHOLD_OMP( MQ_DO_PRAGMA(omp parallel for schedule(static) reduction(+ : nnz)), dim, 1UL << nQubitTh, - for (Index i = 0; i < dim; i++) { + for (omp::idx_t i = 0; i < static_cast(dim); i++) { if (i <= col[i]) { nnz++; } @@ -127,7 +127,7 @@ std::shared_ptr> SparseHamiltonian(const VT> &hams, VT>> sp_hams(hams.size()); THRESHOLD_OMP_FOR( - n_qubits, nQubitTh, for (Index i = 0; i < static_cast(hams.size()); i++) { + n_qubits, nQubitTh, for (omp::idx_t i = 0; i < static_cast(hams.size()); i++) { auto pm = GetPauliMat(hams[i], n_qubits); sp_hams[i] = PauliMatToCsrHdMatrix(pm); pm->Reset(); @@ -137,7 +137,7 @@ std::shared_ptr> SparseHamiltonian(const VT> &hams, Index half = tot / 2 + tot % 2; THRESHOLD_OMP( MQ_DO_PRAGMA(omp parallel for schedule(static) num_threads(half)), n_qubits, nQubitTh, - for (Index i = half; i < tot; i++) { + for (omp::idx_t i = static_cast(half); i < tot; i++) { sp_hams[i - half] = Csr_Plus_Csr(sp_hams[i - half], sp_hams[i]); sp_hams[i]->Reset(); }) @@ -151,14 +151,13 @@ T2 *Csr_Dot_Vec(std::shared_ptr> a, T2 *vec) { auto dim = a->dim_; auto c_vec = reinterpret_cast>(vec); auto new_vec = reinterpret_cast>(malloc(sizeof(CT) * dim)); - // auto nnz = a->nnz_; auto data = a->data_; auto indptr = a->indptr_; auto indices = a->indices_; THRESHOLD_OMP_FOR( - dim, 1UL << nQubitTh, for (Index i = 0; i < dim; i++) { + dim, 1UL << nQubitTh, for (omp::idx_t i = 0; i < static_cast(dim); i++) { CT sum = {0.0, 0.0}; - for (Index j = indptr[i]; j < indptr[i + 1]; j++) { + for (omp::idx_t j = indptr[i]; j < static_cast(indptr[i + 1]); j++) { sum += data[j] * c_vec[indices[j]]; } new_vec[i] = sum; @@ -177,7 +176,7 @@ CT ExpectationOfCsr(std::shared_ptr> a, T2 *bra, T2 *ket) { T2 res_real = 0, res_imag = 0; THRESHOLD_OMP( MQ_DO_PRAGMA(omp parallel for reduction(+:res_real, res_imag) schedule(static)), dim, 1UL << nQubitTh, - for (Index i = 0; i < dim; i++) { + for (omp::idx_t i = 0; i < static_cast(dim); i++) { CT sum = {0.0, 0.0}; for (Index j = indptr[i]; j < indptr[i + 1]; j++) { sum += data[j] * c_ket[indices[j]]; @@ -194,7 +193,6 @@ T2 *Csr_Dot_Vec(std::shared_ptr> a, std::shared_ptrdim_; auto c_vec = reinterpret_cast>(vec); auto new_vec = reinterpret_cast>(malloc(sizeof(CT) * dim)); - // auto nnz = a->nnz_; auto data = a->data_; auto indptr = a->indptr_; auto indices = a->indices_; @@ -203,12 +201,12 @@ T2 *Csr_Dot_Vec(std::shared_ptr> a, std::shared_ptrindices_; THRESHOLD_OMP_FOR( - dim, 1UL << nQubitTh, for (Index i = 0; i < dim; i++) { + dim, 1UL << nQubitTh, for (omp::idx_t i = 0; i < static_cast(dim); i++) { CT sum = {0.0, 0.0}; - for (Index j = indptr[i]; j < indptr[i + 1]; j++) { + for (omp::idx_t j = indptr[i]; j < static_cast(indptr[i + 1]); j++) { sum += data[j] * c_vec[indices[j]]; } - for (Index j = indptr_b[i]; j < indptr_b[i + 1]; j++) { + for (omp::idx_t j = indptr_b[i]; j < static_cast(indptr_b[i + 1]); j++) { sum += data_b[j] * c_vec[indices_b[j]]; } new_vec[i] = sum; @@ -231,18 +229,18 @@ CT ExpectationOfCsr(std::shared_ptr> a, std::shared_ptr sum = {0.0, 0.0}; - for (Index j = indptr[i]; j < indptr[i + 1]; j++) { - sum += data[j] * c_ket[indices[j]]; - } - for (Index j = indptr_b[i]; j < indptr_b[i + 1]; j++) { - sum += data_b[j] * c_ket[indices_b[j]]; - } - auto tmp = std::conj(c_bra[i]) * sum; - res_real += std::real(tmp); - res_imag += std::imag(tmp); - }) + for (omp::idx_t i = 0; i < static_cast(dim); i++) { + CT sum = {0.0, 0.0}; + for (omp::idx_t j = indptr[i]; j < static_cast(indptr[i + 1]); j++) { + sum += data[j] * c_ket[indices[j]]; + } + for (omp::idx_t j = indptr_b[i]; j < static_cast(indptr_b[i + 1]); j++) { + sum += data_b[j] * c_ket[indices_b[j]]; + } + auto tmp = std::conj(c_bra[i]) * sum; + res_real += std::real(tmp); + res_imag += std::imag(tmp); + }) return {res_real, res_imag}; } } // namespace mindquantum::sparse diff --git a/ccsrc/include/core/sparse/csrhdmatrix.hpp b/ccsrc/include/core/sparse/csrhdmatrix.h similarity index 96% rename from ccsrc/include/core/sparse/csrhdmatrix.hpp rename to ccsrc/include/core/sparse/csrhdmatrix.h index a29f376b8..8046bb859 100644 --- a/ccsrc/include/core/sparse/csrhdmatrix.hpp +++ b/ccsrc/include/core/sparse/csrhdmatrix.h @@ -1,5 +1,5 @@ /** - * Copyright 2021 Huawei Technologies Co., Ltd + * Copyright (c) Huawei Technologies Co., Ltd. 2021. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,7 +16,7 @@ #ifndef MINDQUANTUM_SPARSE_CSR_HD_MATRIX_H_ #define MINDQUANTUM_SPARSE_CSR_HD_MATRIX_H_ -#include "core/utils.hpp" +#include "core/utils.h" namespace mindquantum::sparse { template diff --git a/ccsrc/include/core/sparse/paulimat.hpp b/ccsrc/include/core/sparse/paulimat.h similarity index 87% rename from ccsrc/include/core/sparse/paulimat.hpp rename to ccsrc/include/core/sparse/paulimat.h index ee1fdb22e..b89178f9e 100644 --- a/ccsrc/include/core/sparse/paulimat.hpp +++ b/ccsrc/include/core/sparse/paulimat.h @@ -1,5 +1,5 @@ /** - * Copyright 2021 Huawei Technologies Co., Ltd + * Copyright (c) Huawei Technologies Co., Ltd. 2021. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,7 +16,7 @@ #ifndef MINDQUANTUM_SPARSE_PAULI_MAT_H_ #define MINDQUANTUM_SPARSE_PAULI_MAT_H_ -#include "core/utils.hpp" +#include "core/utils.h" namespace mindquantum { namespace sparse { @@ -53,11 +53,11 @@ struct PauliMat { auto mask = GetPauliMask(pt.first); auto mask_f = mask.mask_x | mask.mask_y; THRESHOLD_OMP_FOR( - dim_, 1UL << nQubitTh, for (Index i = 0; i < dim_; i++) { + dim_, 1UL << nQubitTh, for (omp::idx_t i = 0; i < static_cast(dim_); i++) { auto j = (i ^ mask_f); col_[i] = j; - auto axis2power = CountOne(i & mask.mask_z); // -1 - auto axis3power = CountOne(i & mask.mask_y); // -1j + auto axis2power = CountOne(static_cast(i & mask.mask_z)); // -1 + auto axis3power = CountOne(static_cast(i & mask.mask_y)); // -1j // (-1)^a2*(-1j)^a3*(1j)^a1=(1j)^2a2*(1j)^3a3*(1j)^a1=(1j)^(a1+2*a2+3*a3) coeff_[j] = static_cast((mask.num_y + 2 * axis3power + 2 * axis2power) & 3); }) diff --git a/ccsrc/include/core/sparse/sparse_utils.hpp b/ccsrc/include/core/sparse/sparse_utils.h similarity index 96% rename from ccsrc/include/core/sparse/sparse_utils.hpp rename to ccsrc/include/core/sparse/sparse_utils.h index c36e184b5..0ef70161e 100644 --- a/ccsrc/include/core/sparse/sparse_utils.hpp +++ b/ccsrc/include/core/sparse/sparse_utils.h @@ -1,5 +1,5 @@ /** - * Copyright 2021 Huawei Technologies Co., Ltd + * Copyright (c) Huawei Technologies Co., Ltd. 2021. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,7 +19,7 @@ #include #include -#include "core/utils.hpp" +#include "core/utils.h" namespace mindquantum { namespace sparse { diff --git a/ccsrc/include/core/utils.hpp b/ccsrc/include/core/utils.h similarity index 81% rename from ccsrc/include/core/utils.hpp rename to ccsrc/include/core/utils.h index 6456ce0fc..67b39cf15 100644 --- a/ccsrc/include/core/utils.hpp +++ b/ccsrc/include/core/utils.h @@ -1,5 +1,5 @@ /** - * Copyright 2021 Huawei Technologies Co., Ltd + * Copyright (c) Huawei Technologies Co., Ltd. 2021. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -29,10 +29,10 @@ #include #include -#include "config/config.hpp" -#include "config/popcnt.hpp" - -#include "core/mq_base_types.hpp" +#include "config/config.h" +#include "config/openmp.h" +#include "config/popcnt.h" +#include "core/mq_base_types.h" namespace mindquantum { #ifndef MQ_DO_PRAGMA @@ -57,7 +57,7 @@ CT ComplexInnerProduct(const ST *v1, const ST *v2, Index len) { auto size = len / 2; THRESHOLD_OMP( MQ_DO_PRAGMA(omp parallel for reduction(+ : real_part, imag_part)), len, 2UL << nQubitTh, - for (Index i = 0; i < size; i++) { + for (omp::idx_t i = 0; i < static_cast(size); i++) { real_part += v1[2 * i] * v2[2 * i] + v1[2 * i + 1] * v2[2 * i + 1]; imag_part += v1[2 * i] * v2[2 * i + 1] - v1[2 * i + 1] * v2[2 * i]; }) @@ -73,7 +73,7 @@ CT ComplexInnerProductWithControl(const ST *v1, const ST *v2, Index len, Inde auto size = len / 2; THRESHOLD_OMP( MQ_DO_PRAGMA(omp parallel for reduction(+ : real_part, imag_part)), len, 2UL << nQubitTh, - for (Index i = 0; i < size; i++) { + for (omp::idx_t i = 0; i < static_cast(size); i++) { if ((i & ctrl_mask) == ctrl_mask) { real_part += v1[2 * i] * v2[2 * i] + v1[2 * i + 1] * v2[2 * i + 1]; imag_part += v1[2 * i] * v2[2 * i + 1] - v1[2 * i + 1] * v2[2 * i]; @@ -100,26 +100,39 @@ inline uint32_t CountOne(int32_t n) { inline uint64_t CountOne(int64_t n) { return CountOne(uint64_t(n)); } +inline uint32_t CountLeadingZero(uint32_t n) { + return __lzcnt(n); +} +inline uint64_t CountLeadingZero(uint64_t n) { + return __lzcnt64(n); +} +inline uint32_t CountLeadingZero(int32_t n) { + return __lzcnt(uint32_t(n)); +} +inline uint64_t CountLeadingZero(int64_t n) { + return __lzcnt64(uint64_t(n)); +} #else -// inline int CountOne(uint64_t n) { -// uint8_t *p = reinterpret_cast(&n); -// return POPCNTTABLE[p[0]] + POPCNTTABLE[p[1]] + POPCNTTABLE[p[2]] + -// POPCNTTABLE[p[3]] + POPCNTTABLE[p[4]] + POPCNTTABLE[p[5]] + -// POPCNTTABLE[p[6]] + POPCNTTABLE[p[7]]; -// } - -// inline int CountOne32(uint32_t n) { -// uint8_t *p = reinterpret_cast(&n); -// return POPCNTTABLE[p[0]] + POPCNTTABLE[p[1]] + POPCNTTABLE[p[2]] + -// POPCNTTABLE[p[3]]; -// } + inline uint32_t CountOne(uint32_t n) { return __builtin_popcount(n); } -inline uint64_t CountOne(int64_t n) { +inline uint64_t CountOne(uint64_t n) { return __builtin_popcount(n); } +inline uint32_t CountLeadingZero(uint32_t n) { + return __builtin_clzll(n); +} +inline uint64_t CountLeadingZero(uint64_t n) { + return __builtin_clzll(n); +} +inline uint32_t CountLeadingZero(int32_t n) { + return __builtin_clzll(uint32_t(n)); +} +inline uint64_t CountLeadingZero(int64_t n) { + return __builtin_clzll(uint64_t(n)); +} #endif // _MSC_VER template @@ -161,5 +174,7 @@ void PrintVec(T *vec, size_t len) { std::cout << c_vec[i] << std::endl; } } + +void safe_copy(void *dest, size_t dest_size, const void *src, size_t count); } // namespace mindquantum #endif // MINDQUANTUM_UTILS_HPP_ diff --git a/ccsrc/include/device/mapping.hpp b/ccsrc/include/device/mapping.h similarity index 89% rename from ccsrc/include/device/mapping.hpp rename to ccsrc/include/device/mapping.h index 5f8b407ab..e8da06288 100644 --- a/ccsrc/include/device/mapping.hpp +++ b/ccsrc/include/device/mapping.h @@ -1,16 +1,18 @@ -// Copyright 2023 -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. +/** + * Copyright (c) Huawei Technologies Co., Ltd. 2023. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ #ifndef MINDQUANTUM_DEVICE_MAPPING_HPP_ #define MINDQUANTUM_DEVICE_MAPPING_HPP_ @@ -21,10 +23,10 @@ #include #include -#include "device/mapping.hpp" -#include "device/topology.hpp" -#include "ops/basic_gate.hpp" -#include "ops/gate_id.hpp" +#include "device/mapping.h" +#include "device/topology.h" +#include "ops/basic_gate.h" +#include "ops/gate_id.h" namespace mindquantum::mapping { struct Gate { std::string type; // gate's type, such as CNOT or X diff --git a/ccsrc/include/device/topology.hpp b/ccsrc/include/device/topology.h similarity index 83% rename from ccsrc/include/device/topology.hpp rename to ccsrc/include/device/topology.h index 71c03bb4d..5f21b8e5a 100644 --- a/ccsrc/include/device/topology.hpp +++ b/ccsrc/include/device/topology.h @@ -1,16 +1,18 @@ -// Copyright 2023 -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. +/** + * Copyright (c) Huawei Technologies Co., Ltd. 2023. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ #ifndef MINDQUANTUM_DEVICE_TOPOLOGY_HPP_ #define MINDQUANTUM_DEVICE_TOPOLOGY_HPP_ diff --git a/ccsrc/include/experimental/CMakeLists.txt b/ccsrc/include/experimental/CMakeLists.txt deleted file mode 100644 index 3440e39c9..000000000 --- a/ccsrc/include/experimental/CMakeLists.txt +++ /dev/null @@ -1,31 +0,0 @@ -# ============================================================================== -# -# Copyright 2021 -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# ============================================================================== - -# lint_cmake: -whitespace/indent - -target_compile_definitions(mq_cxx_nextgen PUBLIC MINDQUANTUM_CXX_EXPERIMENTAL) -target_link_libraries(mq_cxx_nextgen PUBLIC include_lib mindquantum::cereal mindquantum::pybind11_module - mindquantum::tweedledum mq_base) - -# ------------------------------------------------------------------------------ - -install(DIRECTORY ${CMAKE_CURRENT_LIST_DIR}/core ${CMAKE_CURRENT_LIST_DIR}/decompositions - ${CMAKE_CURRENT_LIST_DIR}/mapping ${CMAKE_CURRENT_LIST_DIR}/ops ${CMAKE_CURRENT_LIST_DIR}/simulator - DESTINATION ${MQ_INSTALL_INCLUDEDIR}/experimental) - -# ============================================================================== diff --git a/ccsrc/include/experimental/CPPLINT.cfg b/ccsrc/include/experimental/CPPLINT.cfg deleted file mode 100644 index 79ab8fcd4..000000000 --- a/ccsrc/include/experimental/CPPLINT.cfg +++ /dev/null @@ -1 +0,0 @@ -filter=-runtime/references diff --git a/ccsrc/include/experimental/core/CPPLINT.cfg b/ccsrc/include/experimental/core/CPPLINT.cfg deleted file mode 100644 index f212ad35f..000000000 --- a/ccsrc/include/experimental/core/CPPLINT.cfg +++ /dev/null @@ -1 +0,0 @@ -filter=-runtime/references,-build/include diff --git a/ccsrc/include/experimental/core/circuit_block.hpp b/ccsrc/include/experimental/core/circuit_block.hpp deleted file mode 100644 index 8f43f7c82..000000000 --- a/ccsrc/include/experimental/core/circuit_block.hpp +++ /dev/null @@ -1,372 +0,0 @@ -// Copyright 2020 -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef CIRCUIT_BLOCK_HPP -#define CIRCUIT_BLOCK_HPP - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include - -#include - -#include "experimental/core/config.hpp" -#include "experimental/core/types.hpp" - -#if MQ_HAS_CONCEPTS -# include "experimental/core/concepts.hpp" -#endif // MQ_HAS_CONCEPTS - -#ifdef UNIT_TESTS -class UnitTestAccessor; -#endif // UNIT_TESTS - -namespace mindquantum { -#if MQ_HAS_CONCEPTS -namespace concepts { -using device_t = tweedledum::Device; -using circuit_t = tweedledum::Circuit; -using placement_t = tweedledum::Placement; -using mapping_t = tweedledum::Mapping; - -template -concept cold_start_t = requires(func_t func, device_t device, circuit_t circuit) { - { func(device, circuit) } -> std::same_as>; -}; // NOLINT(readability/braces) -template -concept hot_start_t = requires(func_t func, device_t device, circuit_t circuit, placement_t placement) { - { func(device, circuit, placement) } -> std::same_as>; -}; // NOLINT(readability/braces) -} // namespace concepts -#endif // MQ_HAS_CONCEPTS - -//! External qubit ID -class QubitID { - public: - using cbit_t = tweedledum::Cbit; - using qubit_t = tweedledum::Qubit; - - //! Constructor - /*! - * \param id External qubit ID - */ - constexpr explicit QubitID(qubit_id_t id) : id_(id) { - } - - //! Simple getter - /*! - * \return Numeric value of ID - */ - MQ_NODISCARD constexpr qubit_id_t get() const { - return qubit_id_t(*this); - } - - //! Conversion operator - /*! - * \return Numeric value of ID - */ - explicit constexpr operator qubit_id_t() const { - return id_; - } - - //! Conversion operator - /*! - * \return Numeric value of ID as a Tweedledum Qubit - */ - explicit constexpr operator qubit_t() const { - return qubit_t(id_); - } - - //! Conversion operator - /*! - * \return Numeric value of ID as a Tweedledum Qubit - */ - explicit constexpr operator cbit_t() const { - return cbit_t(id_); - } - - //! Less operator - /*! - * \return True if numerical values is less than \c other - */ - MQ_NODISCARD constexpr bool operator<(const QubitID& other) const { - return id_ < other.id_; - } - - //! Less operator - /*! - * \return True if numerical values is less than \c other - */ - MQ_NODISCARD constexpr bool operator<(qubit_id_t id) const { - return id_ < id; - } - - //! Equality operator - /*! - * \return True if this is equal to \c other - */ - MQ_NODISCARD constexpr bool operator==(const QubitID& other) const { - return id_ == other.id_; - } - - //! Equality operator - /*! - * \return True if this is equal to \c other - */ - MQ_NODISCARD constexpr bool operator==(qubit_id_t id) const { - return id_ == id; - } - - private: - qubit_id_t id_; -}; - -bool operator<(qubit_id_t id, const QubitID& qubit); - -//! A quantum circuit block -/*! - * A circuit block is a quantum circuit (ie. a list of quantum/classical gates applied to some qubits) that may or may - * not be applied to some physical qubits. - * - * In addition to being a quantum circuit, a circuit block also keep tracks of any qubit mapping that has been performed - * and makes sure that the mapping stays consistent when executing a list of quantum circuits. - */ -class CircuitBlock { - public: - using cbit_t = tweedledum::Cbit; - using qubit_t = tweedledum::Qubit; - using inst_ref_t = tweedledum::InstRef; - using instruction_t = tweedledum::Instruction; - using device_t = tweedledum::Device; - using placement_t = tweedledum::Placement; - using mapping_t = tweedledum::Mapping; - using circuit_t = tweedledum::Circuit; - using ext_id_t = QubitID; - using td_qid_t = qubit_t; - using td_cid_t = cbit_t; - using id_map_ext_to_int_t = std::map>, std::less<>>; - using id_map_qint_to_ext_t = std::map>; - using id_map_cint_to_ext_t = std::map>; - - static constexpr struct chained_t { - } chain_ctor{}; - - //! Constructor - CircuitBlock(); - - //! Chaining constructor - /*! - * Create a new block that has \c parent as parent. - * - * \param parent Parent circuit block - */ - CircuitBlock(const CircuitBlock& parent, chained_t); - - //! Chaining constructor - /*! - * Create a new block that has \c parent as parent but excludes some wires - * - * \param parent Parent circuit block - * \param exclude_ids Qubit IDs from parent block to ignore when constructing the new block - */ - CircuitBlock(const CircuitBlock& parent, const std::vector& exclude_ids, chained_t); - - // ----------------------------------------------- - - //! Simple accessor for the size of the underlying circuit - auto size() const { - return std::size(circuit_); - } - - //! Check whether a mapping was performed - bool has_mapping() const; - - //! Check whether a qubit with corresponding ID is known - /*! - * \param qubit_id External qubit ID - * \return True if an internal ID is associated with \c qubit_id - */ - bool has_qubit(ext_id_t qubit_id) const; - - //! Check whether a cbit with corresponding ID is known - /*! - * \param qubit_id External qubit ID - * \return True if an internal ID is associated with \c qubit_id - */ - bool has_cbit(ext_id_t qubit_id) const; - - //! Simple accessor for the underlying External IDs - std::vector ext_ids() const; - - //! Simple accessor for the underlying internal IDs (qubits only) - std::vector td_ids() const; - - //! Simple accessor for the underlying internal IDs (qubits only) - std::vector qubits() const { - return td_ids(); - } - - // ----------------------------------------------- - - //! Add a qubit to the circuit - /*! - * \param qubit_id (External) qubit ID to add - * \return True if qubit could be added, false otherwise - */ - bool add_qubit(ext_id_t qubit_id); - - // ----------------------------------------------- - - //! Convert internal qubit IDs to External IDs - /*! - * \param ref Internal ID (Tweedledum qubit) - * \return Corresponding External ID - * \throw std::out_of_range if no External ID is known \c ref - */ - qubit_id_t translate_id(const td_qid_t& ref) const; - - //! Convert internal cbit IDs to External IDs - /*! - * \param ref Internal ID (Tweedledum cbit) - * \return Corresponding External ID - * \throw std::out_of_range if no External ID is known \c ref - */ - qubit_id_t translate_id(const td_cid_t& ref) const; - - //! Convert internal qubit IDs to External IDs (Tweedledum type as return value) - /*! - * \param ref Internal ID (Tweedledum wire reference) - * \return Corresponding External ID (as Tweedledum wire reference) - * \throw std::out_of_range if no External ID is known \c ref - */ - td_qid_t translate_id_td(const td_qid_t& ref) const; - - //! Convert internal cbit IDs to External IDs (Tweedledum type as return value) - /*! - * \param ref Internal ID (Tweedledum wire reference) - * \return Corresponding External ID (as Tweedledum wire reference) - * \throw std::out_of_range if no External ID is known \c ref - */ - td_cid_t translate_id_td(const td_cid_t& ref) const; - - //! Convert internal External IDs to qubit IDs - /*! - * \param qubit_id External qubit ID - * \return Corresponding internal ID - * \throw std::out_of_range if no internal ID is known for \c qubit_id - */ - td_qid_t translate_id(const ext_id_t& qubit_id) const; - - // ----------------------------------------------- - - //! Add an operation to the underlying circuit - /*! - * \param optor Operator to apply - * \param control_qubits List of External qubit IDs representing controls - * \param target_qubits List of External qubit IDs representing targets - */ - template - inst_ref_t apply_operator(OpT&& optor, const qubit_ids_t& control_qubits, const qubit_ids_t& target_qubits); - - //! Add an operation to the underlying circuit - /*! - * \param optor Operator to apply - * \param control_qubits List of External qubit IDs representing controls - * \param target_qubits List of External qubit IDs representing targets - */ - inst_ref_t apply_operator(const instruction_t& optor, const qubit_ids_t& control_qubits, - const qubit_ids_t& target_qubits); - - //! Apply a measurement on a qubit - /*! - * \param id External qubit ID - */ - inst_ref_t apply_measurement(qubit_id_t id); - - // ----------------------------------------------- - - //! Apply a mapping to the underlying circuit - /*! - * \param device Hardware device the mapping is applied to - * \param cold_start Callable to do a "cold start" mapping (ie. first mapping) - * \param hot_start Callable to do a "hot start" mapping (ie. subsqeuent mapping) - * - * \note The signature of the callables are: - * - void (*) (td::MapState&); - */ -#if MQ_HAS_CONCEPTS - template -#else - template -#endif // MQ_HAS_CONCEPTS - void apply_mapping(const device_t& device, const Fn& cold_start, const Gn& hot_start); - - // ----------------------------------------------- - - //! Iterate over all operations - template - void foreach_instruction(Fn&& fn) const; - - //! Iterate over all operations in reverse order - template - void foreach_r_instruction(Fn&& fn) const; - - //! Apply a transform to the circuit - /*! - * \tparam Fn Needs to be a callable type with one of the following - * signatures: - * - void (*) (const td::Circuit&); - * - td::Circuit (*) (const td::Circuit&);
- * - * \note The first signature does not modify the underlying network, - * while the second assigns the result of the transformation - * to the underlying network. - */ - template - void transform(const Fn& fn); - - private: -#ifdef UNIT_TESTS - friend class ::UnitTestAccessor; -#endif // UNIT_TESTS - - std::vector translate_ext_ids_(const qubit_ids_t& control_qubits, const qubit_ids_t& target_qubits); - void update_mappings_(const std::vector& old_to_new); - - const device_t* device_; - circuit_t circuit_; - - id_map_ext_to_int_t ext_to_td_; - id_map_qint_to_ext_t qtd_to_ext_; - id_map_cint_to_ext_t ctd_to_ext_; - - std::optional mapping_; -}; -} // namespace mindquantum - -#include "circuit_block.tpp" // NOLINT(build/include) - -#endif /* CIRCUIT_BLOCK_HPP */ diff --git a/ccsrc/include/experimental/core/circuit_block.tpp b/ccsrc/include/experimental/core/circuit_block.tpp deleted file mode 100644 index 0e96d7102..000000000 --- a/ccsrc/include/experimental/core/circuit_block.tpp +++ /dev/null @@ -1,167 +0,0 @@ -// Copyright 2020 -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef CIRCUIT_BLOCK_TPP -#define CIRCUIT_BLOCK_TPP - -#ifndef CIRCUIT_BLOCK_HPP -# error This file must only be included by circuit_block.hpp! -#endif // !CIRCUIT_MANAGER_HPP - -#include -#include -#include - -// clang-format off -// NB: This is mainly for syntax checkers and completion helpers as this file is only intended to be included directly -// by circuit_manager.hpp -#include "experimental/core/circuit_block.hpp" -// clang-format on - -#include -#include - -#include "experimental/mapping/partial_placer.hpp" - -// ============================================================================= - -//! Custom formatter for a QubitID -template -struct fmt::formatter { - FMT_CONSTEXPR auto parse(format_parse_context& ctx) -> decltype(ctx.begin()) { - return ctx.begin(); - } - - template - auto format(const mindquantum::QubitID& qubit_id, format_context_t& ctx) const -> decltype(ctx.out()) { - return fmt::format_to(ctx.out(), "Q[{}]", static_cast(qubit_id)); - } -}; - -// ============================================================================= - -namespace mindquantum { -template -auto CircuitBlock::apply_operator(OpT&& optor, const qubit_ids_t& control_qubits, const qubit_ids_t& target_qubits) - -> inst_ref_t { - return circuit_.apply_operator(std::forward(optor), translate_ext_ids_(control_qubits, target_qubits)); -} -} // namespace mindquantum - -// ============================================================================= - -namespace mindquantum { -#if MQ_HAS_CONCEPTS -template -#else -template -#endif // MQ_HAS_CONCEPTS -void CircuitBlock::apply_mapping(const device_t& device, const Fn& cold_start, const Gn& hot_start) { - // clang-format off - using mapping_ret_t = std::pair; - static_assert(std::is_invocable_r_v); - static_assert(std::is_invocable_r_v); - // clang-format on - - assert(device.num_qubits() > 0); - if (!device_) { - device_ = &device; - } else { - // TODO(dnguyen): Better error handling - assert(&device == device_); - } - - const auto n_qubits_orig = circuit_.num_qubits(); - - circuit_t mapped; - - // --------------------------- - /* Calculate the mapping - * - * This results in a circuit with the operations in reverse order since the instructions are stored in a - * single-linked list with back pointers. - */ - if (!has_mapping()) { - std::tie(mapped, mapping_) = cold_start(*device_, circuit_); - } else { - auto& mapping = mapping_.value(); - mapping.placement.reset(); - - std::vector new_qubits; - auto has_new_qubits = false; - for (auto v(0UL); v < std::size(mapping.placement.v_to_phy()); ++v) { - const auto phy = mapping.init_placement.v_to_phy(v); - if (phy != qubit_t::invalid()) { - mapping.placement.map_v_phy(v, phy); - } else { - new_qubits.emplace_back(v); - } - } - - if (!std::empty(new_qubits)) { - mapping::PartialPlacer placer(*device_, mapping.placement); - placer.run(new_qubits); - } - - mapping_t new_mapping(mapping.init_placement); - std::tie(mapped, new_mapping) = hot_start(device, circuit_, mapping.placement); - - assert(mapping.init_placement == new_mapping.init_placement); - mapping.placement = new_mapping.placement; - } - - circuit_ = std::move(mapped); - - // --------------------------- - // Recalculate the new internal mappings since wire IDs in circuit_ will now be physical IDs - // NB: this ignores "ghost" qubits - std::vector old_to_mapped(circuit_.num_wires(), qubit_t::invalid()); - circuit_.foreach_qubit([&old_to_mapped = old_to_mapped, &placement = mapping_->placement](const qubit_t& qubit) { - old_to_mapped[qubit] = placement.v_to_phy(qubit); - }); - - update_mappings_(old_to_mapped); -} -} // namespace mindquantum - -// ============================================================================= - -namespace mindquantum { -template -void CircuitBlock::foreach_instruction(Fn&& fn) const { - circuit_.foreach_instruction(std::forward(fn)); -} - -template -void CircuitBlock::foreach_r_instruction(Fn&& fn) const { - circuit_.foreach_r_instruction(std::forward(fn)); -} - -template -void CircuitBlock::transform(const Fn& fn) { - // clang-format off - static_assert(std::is_invocable_r_v || - std::is_invocable_r_v); - // clang-format on - if constexpr (std::is_invocable_r_v) { - circuit_ = fn(circuit_); - } else { - fn(circuit_); - } -} -} // namespace mindquantum - -// ============================================================================= - -#endif /* CIRCUIT_BLOCK_TPP */ diff --git a/ccsrc/include/experimental/core/compute.hpp b/ccsrc/include/experimental/core/compute.hpp deleted file mode 100644 index 4cbb51f12..000000000 --- a/ccsrc/include/experimental/core/compute.hpp +++ /dev/null @@ -1,168 +0,0 @@ -// Copyright 2020 -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef COMPUTE_HPP -#define COMPUTE_HPP - -#include -#include - -#include -#include - -#include "experimental/core/types.hpp" -#include "experimental/ops/gates/invalid.hpp" - -namespace mindquantum::cengines { -//! Circuit wrapper class that implements the compute-uncompute pattern -class ComputeCircuit { - public: - //! Constructor - /*! - * \param original A quantum circuit - */ - explicit ComputeCircuit(circuit_t& original) // NOLINT(runtime/references) - : original_(original) - , do_compute_(true) - , no_bits_added_(true) - , compute_(tweedledum::shallow_duplicate(original)) { - } - - //! Destructor - /*! - * Only when the ComputeCircuit object is being destroyed are the instructions added to it so far will be - * transferred to the original quantum circuit object. - */ - ~ComputeCircuit() { - no_bits_added_ &= (original_.num_qubits() == non_compute_.num_qubits() - && original_.num_cbits() == non_compute_.num_cbits()); - if (!no_bits_added_) { - add_missing_qubits_cbits_(non_compute_, original_); - } - compute_.foreach_instruction( - [&original = original_](const instruction_t& inst) { original.apply_operator(inst); }); - non_compute_.foreach_instruction( - [&original = original_](const instruction_t& inst) { original.apply_operator(inst); }); - compute_.foreach_r_instruction([&original = original_](const instruction_t& inst) { - if (const auto& op = inst.adjoint(); op) { - original.apply_operator(op.value(), inst.qubits(), inst.cbits()); - } else { - original.apply_operator(ops::Invalid(inst.num_qubits()), inst.qubits(), inst.cbits()); - } - }); - } - - ComputeCircuit(const ComputeCircuit&) = delete; - ComputeCircuit(ComputeCircuit&&) = default; - ComputeCircuit& operator=(const ComputeCircuit&) = delete; - ComputeCircuit& operator=(ComputeCircuit&&) = delete; - - //! For internal-use only - void done_compute() { - do_compute_ = false; - no_bits_added_ = (original_.num_qubits() == compute_.num_qubits() - && original_.num_cbits() == compute_.num_cbits()); - non_compute_ = tweedledum::shallow_duplicate(compute_); - } - - //! Read-write getter to the circuit storing the \e computed instructions - circuit_t& compute() { - return compute_; - } - - //! Read-write getter to the circuit storing the instructions between the compute and uncompute regions - circuit_t& non_compute() { - return non_compute_; - } - - private: - static void add_missing_qubits_cbits_(const circuit_t& reference, - circuit_t& circuit) { // NOLINT(runtime/references) - reference.foreach_qubit([&circuit](const qubit_t& qubit, std::string_view name) { - if (qubit >= circuit.num_qubits()) { -#ifndef NDEBUG - const auto new_qubit = -#endif // NDEBUG - circuit.create_qubit(name); - -#ifndef NDEBUG - assert(qubit == new_qubit); -#endif // NDEBUG - } - }); - - reference.foreach_cbit([&circuit](const cbit_t& cbit, std::string_view name) { - if (cbit > circuit.num_cbits()) { -#ifndef NDEBUG - const auto new_cbit = -#endif // NDEBUG - circuit.create_cbit(name); -#ifndef NDEBUG - assert(cbit == new_cbit); -#endif // NDEBUG - } - }); - } - - circuit_t& original_; - bool do_compute_; - bool no_bits_added_; - circuit_t compute_; - circuit_t non_compute_; -}; - -namespace details { -//! Helper class to implement WITH_COMPUTE statements in C++ -class ComputeCircuitProxy { - public: - //! Constructor - /*! - * \param compute ComputCircuit object to wrap. - */ - explicit ComputeCircuitProxy(ComputeCircuit& compute) : compute_(compute) { - } - - //! Destructor - ~ComputeCircuitProxy() { - compute_.done_compute(); - } - - ComputeCircuitProxy(const ComputeCircuitProxy&) = delete; - ComputeCircuitProxy(ComputeCircuitProxy&&) = delete; - ComputeCircuitProxy& operator=(const ComputeCircuitProxy&) = delete; - ComputeCircuitProxy& operator=(ComputeCircuitProxy&&) = delete; - - //! Read-write getter to the circuit storing the \e computed instructions - // NOLINTNEXTLINE(google-explicit-constructor,hicpp-explicit-conversions) - operator circuit_t&() & { - return compute_.compute(); - } - - private: - ComputeCircuit& compute_; -}; -} // namespace details -} // namespace mindquantum::cengines - -// NOLINTNEXTLINE(cppcoreguidelines-macro-usage,readability/braces) -#define MQ_WITH_COMPUTE_IMPL(original, name, unique_name) \ - mindquantum::cengines::ComputeCircuit unique_name{original}; \ - mindquantum::circuit_t&(name) ((unique_name).non_compute()); \ - if (mindquantum::cengines::details::ComputeCircuitProxy proxy{(unique_name)}; true) { \ - auto&(unique_name) = static_cast(proxy); -// NOLINTNEXTLINE(cppcoreguidelines-macro-usage) -#define MQ_WITH_COMPUTE(original, name) MQ_WITH_COMPUTE_IMPL(original, name, MQ_UNIQUE_NAME(name)) -// NOLINTNEXTLINE(cppcoreguidelines-macro-usage) -#define MQ_WITH_COMPUTE_END } -#endif /* COMPUTE_HPP */ diff --git a/ccsrc/include/experimental/core/concepts.hpp b/ccsrc/include/experimental/core/concepts.hpp deleted file mode 100644 index 882705eee..000000000 --- a/ccsrc/include/experimental/core/concepts.hpp +++ /dev/null @@ -1,34 +0,0 @@ -// Copyright 2021 -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef CORE_CONCEPTS_HPP -#define CORE_CONCEPTS_HPP - -#include - -#include "config/concepts.hpp" - -#include "experimental/core/config.hpp" -#include "experimental/core/traits.hpp" -#include "experimental/core/types.hpp" - -namespace mindquantum { -class CircuitBlock; -} // namespace mindquantum - -namespace mindquantum::concepts { -template -concept CircuitLike = (concepts::same_decay_as || concepts::same_decay_as); -} // namespace mindquantum::concepts -#endif /* CORE_CONCEPTS_HPP */ diff --git a/ccsrc/include/experimental/core/config.hpp b/ccsrc/include/experimental/core/config.hpp deleted file mode 100644 index 5bdc32f27..000000000 --- a/ccsrc/include/experimental/core/config.hpp +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright 2020 -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef CORE_CONFIG_HPP -#define CORE_CONFIG_HPP - -#include - -#include "config/config.hpp" -#include "config/logging.hpp" - -#include "experimental/core/types.hpp" - -// ============================================================================= - -#if MQ_HAS_CONCEPTS -# define MQ_REQUIRES(x) requires(x) -#else -# define MQ_REQUIRES(x) -#endif // MQ_HAS_CONCEPTS - -/*! - * \def MQ_REQUIRES - * Add a C++20 requires() clause to a function if supported by the compiler. - */ - -#endif /* CORE_CONFIG_HPP */ diff --git a/ccsrc/include/experimental/core/control.hpp b/ccsrc/include/experimental/core/control.hpp deleted file mode 100644 index a81cd6a71..000000000 --- a/ccsrc/include/experimental/core/control.hpp +++ /dev/null @@ -1,106 +0,0 @@ -// Copyright 2021 -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef CONTROLCIRCUIT_HPP -#define CONTROLCIRCUIT_HPP - -#include -#include - -#include - -#include "experimental/core/config.hpp" -#include "experimental/core/types.hpp" - -namespace mindquantum::cengines { -class ControlledCircuit { - public: - ControlledCircuit(circuit_t& original, const qubits_t& controls) // NOLINT(runtime/references) - : processed_(empty(controls)) - , original_(original) - , circuit_(empty(controls) ? circuit_t{} : tweedledum::shallow_duplicate(original)) - , controls_(controls) { - } - - ~ControlledCircuit() { - apply(); - } - - ControlledCircuit(const ControlledCircuit&) = delete; - ControlledCircuit(ControlledCircuit&&) = default; - ControlledCircuit& operator=(const ControlledCircuit&) = delete; - ControlledCircuit& operator=(ControlledCircuit&&) = delete; - - void apply() { - if (!processed_) { - assert(!empty(controls_)); - processed_ = true; - - circuit_.foreach_qubit([&original = original_](const qubit_t& qubit, std::string_view name) { - if (qubit >= original.num_qubits()) { -#ifndef NDEBUG - const auto new_qubit = -#endif // NDEBUG - original.create_qubit(name); - -#ifndef NDEBUG - assert(qubit == new_qubit); -#endif // NDEBUG - } - }); - - circuit_.foreach_cbit([&original = original_](const cbit_t& cbit, std::string_view name) { - if (cbit > original.num_cbits()) { -#ifndef NDEBUG - const auto new_cbit = -#endif // NDEBUG - original.create_cbit(name); -#ifndef NDEBUG - assert(cbit == new_cbit); -#endif // NDEBUG - } - }); - - circuit_.foreach_instruction([&original = original_, &controls = controls_](const instruction_t& inst) { - auto qubits = controls; - for (const auto& qubit : inst.qubits()) { - qubits.emplace_back(qubit); - } - original.apply_operator(inst, qubits, inst.cbits()); - }); - } - } - - explicit operator circuit_t&() { - if (empty(controls_)) { - return original_; - } - return circuit_; - } - - private: - bool processed_; - circuit_t& original_; - circuit_t circuit_; - const qubits_t& controls_; -}; -} // namespace mindquantum::cengines - -// NOLINTNEXTLINE(cppcoreguidelines-macro-usage) -#define MQ_WITH_CONTROL_IMPL(original, name, unique_name, controls) \ - mindquantum::cengines::ControlledCircuit unique_name{original, controls}; \ - if (mindquantum::circuit_t & (name) = static_cast((unique_name)); true) -// NOLINTNEXTLINE(cppcoreguidelines-macro-usage) -#define MQ_WITH_CONTROL(original, name, controls) MQ_WITH_CONTROL_IMPL(original, name, MQ_UNIQUE_NAME(name), controls) -#endif /* CONTROLCIRCUIT_HPP */ diff --git a/ccsrc/include/experimental/core/dagger.hpp b/ccsrc/include/experimental/core/dagger.hpp deleted file mode 100644 index db0d97827..000000000 --- a/ccsrc/include/experimental/core/dagger.hpp +++ /dev/null @@ -1,96 +0,0 @@ -// Copyright 2020 -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef DAGGERCIRCUIT_HPP -#define DAGGERCIRCUIT_HPP - -#include -#include -#include - -#include -#include - -namespace mindquantum { -namespace td = tweedledum; - -class DaggeredCircuit { - public: - using instruction_t = td::Instruction; - using instruction_ref_t = td::InstRef; - using qubit_t = tweedledum::Qubit; - using cbit_t = tweedledum::Cbit; - using circuit_t = tweedledum::Circuit; - - explicit DaggeredCircuit(circuit_t& original) - : processed_(false), original_(original), circuit_(tweedledum::shallow_duplicate(original)) { - } - - ~DaggeredCircuit() { - apply(); - } - - void apply() { - if (!processed_) { - processed_ = true; - - circuit_.foreach_qubit([&original = original_](const qubit_t& qubit, std::string_view name) { - if (qubit >= original.num_qubits()) { -#ifndef NDEBUG - const auto new_qubit = -#endif // NDEBUG - original.create_qubit(name); - -#ifndef NDEBUG - assert(qubit == new_qubit); -#endif // NDEBUG - } - }); - - circuit_.foreach_cbit([&original = original_](const cbit_t& cbit, std::string_view name) { - if (cbit > original.num_cbits()) { -#ifndef NDEBUG - const auto new_cbit = -#endif // NDEBUG - original.create_cbit(name); -#ifndef NDEBUG - assert(cbit == new_cbit); -#endif // NDEBUG - } - }); - - // Execute commands in reverse order while inverting all commands - circuit_.foreach_r_instruction([&original = original_](const instruction_t& inst) { - auto op = inst.adjoint(); - if (op) { - original.apply_operator(*op, inst.qubits(), inst.cbits()); - } else { - // TODO(dnguyen): Think of error handling! - } - }); - } - } - - operator circuit_t&() { - return circuit_; - } - - private: - bool processed_; - circuit_t& original_; - circuit_t circuit_; -}; -} // namespace mindquantum - -#endif /* DAGGERCIRCUIT_HPP */ diff --git a/ccsrc/include/experimental/core/details/visitor.hpp b/ccsrc/include/experimental/core/details/visitor.hpp deleted file mode 100644 index 920ee76b8..000000000 --- a/ccsrc/include/experimental/core/details/visitor.hpp +++ /dev/null @@ -1,56 +0,0 @@ -// Copyright 2020 -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef VISITOR_HPP -#define VISITOR_HPP - -namespace mindquantum { -//! Helper class to generate visitors for std::variant -/*! - * This performs some "black magick" in order to allow users to create a - * visitor class consisting only of lambdas at the call site. - * - * It uses four key language features: - * - variadic templates (C++11) - * - aggregate initialization (C++11) - * - pack expansion of using directice (C++17) - * - custom template argument deduction rules (C++17) - * - * For example, the following would create an instance of a \c overload - * class with two overload for operator(): one taking an \c int and one - * taking a \c double. - * - * \code - * overload{ - * [] (int i) { std::cout << "int: " << i; }, - * [] (double d::cout << "double: " << d; }, - * } - * \endcode - */ -template -struct overload : Ts... { - using Ts::operator()...; -}; - -#if !MQ_HAS_IMPLICIT_TEMPLATE_DEDUCTION_GUIDES -//! Template deduction guide for the overload struct -/*! - * \note Not needed anymore for C++20 - */ -template -overload(Ts...) -> overload; -#endif /* MQ_HAS_IMPLICIT_TEMPLATE_DEDUCTION_GUIDES */ -} // namespace mindquantum - -#endif /* VISITOR_HPP */ diff --git a/ccsrc/include/experimental/core/engine_concepts.hpp b/ccsrc/include/experimental/core/engine_concepts.hpp deleted file mode 100644 index 5641e3b5c..000000000 --- a/ccsrc/include/experimental/core/engine_concepts.hpp +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright 2021 -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef ENGINE_CONCEPTS_HPP -#define ENGINE_CONCEPTS_HPP - -#include - -#include -#include -#include - -#include "experimental/core/concepts.hpp" - -namespace mindquantum::concepts { -template -concept Mapper = requires(mapper_t mapper, tweedledum::Device device, tweedledum::Circuit circuit, - tweedledum::Placement placement) { - { mapper.device() } -> same_decay_as; - { mapper.cold_start(device, circuit) } -> std::same_as>; - // clang-format off - { mapper.hot_start(device, circuit, placement) } -> std::same_as>; - // clang-format on -}; // NOLINT(readability/braces) -} // namespace mindquantum::concepts - -#endif /* ENGINE_CONCEPTS_HPP */ diff --git a/ccsrc/include/experimental/core/gate_concepts.hpp b/ccsrc/include/experimental/core/gate_concepts.hpp deleted file mode 100644 index 8a581ca0d..000000000 --- a/ccsrc/include/experimental/core/gate_concepts.hpp +++ /dev/null @@ -1,117 +0,0 @@ -// Copyright 2021 -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef GATE_CONCEPTS_HPP -#define GATE_CONCEPTS_HPP - -#include -#include -#include -#include -#include - -#include - -#include - -#include "experimental/core/operator_traits.hpp" -#include "experimental/ops/parametric/config.hpp" - -#if MQ_HAS_CONCEPTS -# include "experimental/core/concepts.hpp" -#endif // MQ_HAS_CONCEPTS - -namespace mindquantum::concepts { -#if MQ_HAS_CONCEPTS -template -concept Gate = requires(op_t optor) { - { op_t::kind() } -> std::same_as; -}; // NOLINT(readability/braces) - -template -concept FixedNumTargetGate = requires(op_t optor) { - requires Gate; - requires std::default_initializable; - // clang-format off - requires std::greater<>{}(traits::num_targets, 0); - // clang-format on -}; // NOLINT(readability/braces) - -template -concept VariableNumTargetGate = requires(op_t optor) { - requires Gate; - requires std::constructible_from; -}; // NOLINT(readability/braces) - -template -concept SingleDoubleGate = requires(op_t optor) { - requires Gate; - { optor.param() } -> same_decay_as; -}; // NOLINT(readability/braces) - -template -concept MultiDoubleGate = requires(op_t optor) { - requires Gate; - // TODO(damien): Perhaps store the number of parameters as a static constexpr class variable? - { optor.params() } -> same_decay_as>; -}; // NOLINT(readability/braces) - -template -concept AngleGate = requires(op_t optor) { - requires Gate; - requires std::constructible_from; - { optor.angle() } -> same_decay_as; -}; // NOLINT(readability/braces) - -template -concept ParametricGate = requires(op_t optor, SymEngine::map_basic_basic subs) { - requires Gate; - requires std::same_as; - requires Gate; - requires std::integral; - requires std::greater<> { - } - (op_t::num_params, 0); - - { optor.param(0UL) } -> same_decay_as; - { optor.params() } -> same_decay_as; - { optor.eval(subs) } -> same_decay_as; - { optor.eval_full(subs) } -> same_decay_as; - { optor.eval_smart(subs) } -> same_decay_as; -}; // NOLINT(readability/braces) - -template -concept NonParametricGate = requires(op_t optor) { - requires Gate; - requires !ParametricGate; -}; // NOLINT(readability/braces) - -//! Helper typedef -template -using param_eval_t = typename std::tuple_element_t<0, param_t>::param_type::type; - -template -concept SingleParameterGate = requires(op_t optor) { - requires ParametricGate; - // clang-format off - requires std::equal_to<>{}(op_t::num_params, 1); - // clang-format on - // // Make sure that the parameter evaluates to what we expect - // requires std::same_as, evaluated_t>; -}; // NOLINT(readability/braces) -#else -#endif // MQ_HAS_CONCEPTS -} // namespace mindquantum::concepts - -#endif /* GATE_CONCEPTS_HPP */ diff --git a/ccsrc/include/experimental/core/gate_traits.hpp b/ccsrc/include/experimental/core/gate_traits.hpp deleted file mode 100644 index d895e3122..000000000 --- a/ccsrc/include/experimental/core/gate_traits.hpp +++ /dev/null @@ -1,131 +0,0 @@ -// Copyright 2021 -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef GATE_TRAITS_HPP -#define GATE_TRAITS_HPP - -#include -#include -#include -#include - -#include - -#if MQ_HAS_CONCEPTS -# include "experimental/core/gate_concepts.hpp" -#endif // MQ_HAS_CONCEPTS - -#if MQ_HAS_CONSTEXPR_STD_VECTOR -# define CONSTEXPR constexpr -#else -# define CONSTEXPR -#endif // MQ_HAS_CONSTEXPR_STD_VECTOR - -namespace mindquantum::traits { -#if MQ_HAS_CONCEPTS -template -struct gate_traits { - using non_param_type = op_t; -}; - -template -struct gate_traits { - using non_param_type = op_t; - - static constexpr auto param(const tweedledum::Operator& op) -> double { - return op.cast().param(); - } -}; - -template -struct gate_traits { - using non_param_type = op_t; - - static CONSTEXPR auto param(const tweedledum::Operator& op) -> std::vector { - return op.cast().params(); - } -}; - -template -struct gate_traits { - using non_param_type = op_t; - - static constexpr auto param(const tweedledum::Operator& op) -> double { - return op.cast().angle(); - } -}; - -template -struct gate_traits { - using non_param_type = typename op_t::non_param_type; - - static CONSTEXPR auto param(const tweedledum::Operator& op) -> ops::parametric::param_list_t { - return op.cast().params(); - } -}; -#else -namespace details { -template -struct has_angle : std::false_type {}; - -template -struct has_angle().angle())>> : std::true_type {}; - -template -struct has_single_param : std::false_type {}; - -template -struct has_single_param().param())>> : std::true_type {}; - -template -struct has_multi_param : std::false_type {}; - -template -struct has_multi_param().params())>> : std::true_type {}; - -template -struct param_traits { - static auto apply(const op_t& optor) { - if constexpr (has_single_param::value) { - return optor.param(); - } else if constexpr (has_multi_param::value) { - return optor.params(); - } else if constexpr (has_angle::value) { - return optor.angle(); - } else { - return optor.params(); - } - } -}; - -template -struct param_traits_return_type { - using type = decltype(param_traits::apply(std::declval())); -}; -} // namespace details - -template -struct gate_traits { - using non_param_type = op_t; - - static constexpr auto param(const tweedledum::Operator& op) -> - typename details::param_traits_return_type::type { - return details::param_traits::apply(op.cast()); - } -}; -#endif // MQ_HAS_CONCEPTS -} // namespace mindquantum::traits - -#undef CONSTEXPR -#endif /* GATE_TRAITS_HPP */ diff --git a/ccsrc/include/experimental/core/operator_traits.hpp b/ccsrc/include/experimental/core/operator_traits.hpp deleted file mode 100644 index 2f6a11356..000000000 --- a/ccsrc/include/experimental/core/operator_traits.hpp +++ /dev/null @@ -1,147 +0,0 @@ -// Copyright 2021 -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef OPERATOR_TRAITS_HPP -#define OPERATOR_TRAITS_HPP - -#include -#include -#include -#include -#include - -#include "experimental/core/config.hpp" -#include "experimental/core/traits.hpp" - -namespace mindquantum::traits { -// ------------------------------------------------------------------------- -// Helper traits to handle atoms that need to cover multiple kind of atoms - -namespace impl { -template -constexpr bool kind_match(const ref_kind_t& ref_kind, kinds_t&&... kinds) -#if MQ_HAS_CONCEPTS - requires(sizeof...(kinds_t) > 0) -#endif // MQ_HAS_CONCEPTS -{ -#if !MQ_HAS_CONCEPTS - static_assert(sizeof...(kinds_t) > 0); -#endif // MQ_HAS_CONCEPTS - return ((ref_kind == std::forward(kinds)) || ...); -} - -template -struct tuple_kind_match; - -template -struct tuple_kind_match> { - static constexpr bool apply(const ref_kind_t& ref_kind) { - return kind_match(ref_kind, operators_t::kind()...); - } -}; -} // namespace impl - -template -constexpr bool kind_compare(std::string_view kind) { - using kinds_t = typename atom_t::kinds_t; - static_assert(is_tuple_v); - return impl::tuple_kind_match::apply(kind); -} - -// ========================================================================= - -// If operator_t::num_targets exists, integral constant set to that number, else 0 -template -struct static_variable_num_targets : std::integral_constant {}; - -/* NB: Really we should be able to get away with decltype(op_t::num_targets > 0) - * However, if -fms-extensions is given with GCC, then the above would not work for SFINAE anymore. This looks - * to be because some implicit conversion to integral is turned on by that flag if `op_t::num_targets` - * is a function pointer. The comparison with 0 seems to avoid that issue. - */ -template -struct static_variable_num_targets 0)>> - : std::integral_constant {}; - -// ------------------------------------------------------------------------- - -// If op_t::num_targets() exists, integral constant set to that number, else 0 -template -struct static_method_num_targets : std::integral_constant {}; - -template -#if MQ_HAS_CONCEPTS -struct static_method_num_targets 0)>> - : std::integral_constant { -}; -#else -struct static_method_num_targets 0)>> - : std::integral_constant { -}; -#endif // MQ_HAS_CONCEPTS - -// ------------------------------------------------------------------------- - -// Map Eigen matrix types to number of qubits (0 if unknown) -template -struct matrix_const_num_rows : std::integral_constant {}; - -template -struct matrix_const_num_rows> - : std::integral_constant> 1UL)> {}; - -// If op_t has a matrix() method, deduce number of qubits from that, else 0 -template -struct matrix_fixed_num_qubits : std::integral_constant {}; - -template -struct matrix_fixed_num_qubits().matrix())>> - : matrix_const_num_rows().matrix())>>::type {}; - -// ------------------------------------------------------------------------- - -template -struct has_const_num_targets : std::true_type {}; - -template -struct has_const_num_targets> : std::false_type {}; - -template -inline constexpr auto has_const_num_targets_v = has_const_num_targets::value; - -// ------------------------------------------------------------------------- - -/* Deduce the number of qubits, either from: - * - op_t::num_targets (static constexpr attribute) - * - op_t::num_targets() (static potentially constexpr method) - * - return type of op_t::matrix() if constant number of rows - * - else 0 - */ -// clang-format off - template - inline constexpr auto num_targets = std::conditional_t< - (static_variable_num_targets::value > 0), - typename static_variable_num_targets::type, - std::conditional_t<(static_method_num_targets::value > 0), - typename static_method_num_targets::type, - std::conditional_t<(matrix_fixed_num_qubits::value > 0), - typename matrix_fixed_num_qubits::type, - std::integral_constant>> - >::value; -// clang-format on - -// ========================================================================= -} // namespace mindquantum::traits - -#endif /* OPERATOR_TRAITS_HPP */ diff --git a/ccsrc/include/experimental/core/traits.hpp b/ccsrc/include/experimental/core/traits.hpp deleted file mode 100644 index a1a0b634e..000000000 --- a/ccsrc/include/experimental/core/traits.hpp +++ /dev/null @@ -1,26 +0,0 @@ -// Copyright 2021 -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef CORE_TRAITS_HPP -#define CORE_TRAITS_HPP - -#include -#include - -#include "config/config.hpp" -#include "config/type_traits.hpp" - -#include "experimental/core/config.hpp" - -#endif /* CORE_TRAITS_HPP */ diff --git a/ccsrc/include/experimental/core/types.hpp b/ccsrc/include/experimental/core/types.hpp deleted file mode 100644 index 0c8102a26..000000000 --- a/ccsrc/include/experimental/core/types.hpp +++ /dev/null @@ -1,41 +0,0 @@ -// Copyright 2022 -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef CORE_TYPES_HPP -#define CORE_TYPES_HPP - -#include - -#include -#include -#include -#include -#include - -namespace mindquantum { -using qubit_id_t = uint32_t; -using qubit_ids_t = std::vector; - -using qubit_t = tweedledum::Qubit; -using qubits_t = std::vector; -using cbit_t = tweedledum::Cbit; -using cbits_t = std::vector; - -using operator_t = tweedledum::Operator; -using instruction_t = tweedledum::Instruction; -using inst_ref_t = tweedledum::InstRef; -using circuit_t = tweedledum::Circuit; -} // namespace mindquantum - -#endif /* CORE_TYPES_HPP */ diff --git a/ccsrc/include/experimental/decompositions.hpp b/ccsrc/include/experimental/decompositions.hpp deleted file mode 100644 index 05f5809a8..000000000 --- a/ccsrc/include/experimental/decompositions.hpp +++ /dev/null @@ -1,79 +0,0 @@ -// Copyright 2020 -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef DECOMPOSITIONS_HPP -#define DECOMPOSITIONS_HPP -#include -#include - -namespace mindquantum::decompositions { -using circuit_t = tweedledum::Circuit; -using instruction_t = tweedledum::Instruction; - -void decompose_cnot2cz(circuit_t& result, const instruction_t& inst); -//! Decompose CNOT gate, M for 'Minus' because ends with Ry(-pi/2) -void decompose_cnot2rxx_M(circuit_t& result, const instruction_t& inst); -//! Decompose CNOT gate, M for 'Minus' because ends with Ry(+pi/2) -void decompose_cnot2rxx_P(circuit_t& result, const instruction_t& inst); - -//! Decompose multi-controlled gates -void decompose_cnu2toffoliandcu(circuit_t& result, const instruction_t& inst); - -//! Decompose entangle into h and cnot/cx gates -void decompose_entangle(circuit_t& result, const instruction_t& inst); - -//! Decompose controlled global phase gates into (controlled) R/r1 -/*! - * Shaves off one control qubit when applied - */ -void decompose_ph2r(circuit_t& result, const instruction_t& inst); - -//! Delete all phase/ph gates without controls -void decompose_PhNoCtrl(circuit_t& result, const instruction_t& inst); - -//! Decompose H gate, M for 'Minus' because ends with Ry(-pi/2) -void decompose_h2rx_M(circuit_t& result, const instruction_t& inst); -//! Decompose H gate, N for 'Neutral' -void decompose_h2rx_N(circuit_t& result, const instruction_t& inst); - -//! Decompose QFT (Quantum Fourier Transform) into h and controlled R (cr1) -void decompose_qft2crandhadamard(circuit_t& result, const instruction_t& inst); - -//! Decompose (controlled) Qubit Operator into (controlled) Paulis -void decompose_qubitop2onequbit(circuit_t& result, const instruction_t& inst); - -void decompose_rx2rz(circuit_t& result, const instruction_t& inst); -void decompose_ry2rz(circuit_t& result, const instruction_t& inst); - -void decompose_rz2rx_P(circuit_t& result, const instruction_t& inst); -void decompose_rz2rx_M(circuit_t& result, const instruction_t& inst); - -//! Decompose (controlled) phase-shift gate using z-rotation and global phase -void decompose_r2rzandph(circuit_t& result, const instruction_t& inst); - -//! Decompose sqrtswap into controlled x and sqrtx -void decompose_sqrtswap2cnot(circuit_t& result, const instruction_t& inst); - -//! Decompose swap into controlled x gates -void decompose_swap2cnot(circuit_t& result, const instruction_t& inst); - -bool recognize_time_evolution_commuting(const instruction_t& inst); -void decompose_time_evolution_commuting(circuit_t& result, const instruction_t& inst); -bool recognize_time_evolution_individual_terms(const instruction_t& inst); -void decompose_time_evolution_individual_terms(circuit_t& result, const instruction_t& inst); - -//! Decompose toffoli gate (ccx) into cx, t, tdg and h gates -void decompose_toffoli2cnotandtgate(circuit_t& result, const instruction_t& inst); -} // namespace mindquantum::decompositions -#endif /* DECOMPOSITIONS_HPP */ diff --git a/ccsrc/include/experimental/decompositions/CPPLINT.cfg b/ccsrc/include/experimental/decompositions/CPPLINT.cfg deleted file mode 100644 index dbbe70151..000000000 --- a/ccsrc/include/experimental/decompositions/CPPLINT.cfg +++ /dev/null @@ -1 +0,0 @@ -filter=-readability/braces,-build/include,-runtime/references diff --git a/ccsrc/include/experimental/decompositions/atom_meta.hpp b/ccsrc/include/experimental/decompositions/atom_meta.hpp deleted file mode 100644 index ae9699719..000000000 --- a/ccsrc/include/experimental/decompositions/atom_meta.hpp +++ /dev/null @@ -1,53 +0,0 @@ -// Copyright 2021 -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef ATOM_META_HPP -#define ATOM_META_HPP - -#include "experimental/decompositions/config.hpp" -#include "experimental/decompositions/parametric_atom.hpp" -#include "experimental/decompositions/trivial_atom.hpp" - -namespace mindquantum::traits { -#if MQ_HAS_CONCEPTS -template -struct atom_control_type; -template -struct atom_control_type { - using control_type = decompositions::TrivialSimpleAtom; -}; -template -struct atom_control_type { - using control_type = decompositions::ParametricSimpleAtom; -}; -#else -template -struct atom_control_type { - using control_type = decompositions::TrivialSimpleAtom; -}; -template -struct atom_control_type> { - using control_type = decompositions::ParametricSimpleAtom; -}; -#endif // MQ_HAS_CONCEPTS -} // namespace mindquantum::traits - -namespace mindquantum::decompositions::atoms { -template -using Control = typename traits::atom_control_type::control_type; -template -using C = Control; -} // namespace mindquantum::decompositions::atoms - -#endif /* ATOM_META_HPP */ diff --git a/ccsrc/include/experimental/decompositions/atom_storage.hpp b/ccsrc/include/experimental/decompositions/atom_storage.hpp deleted file mode 100644 index 88654fa61..000000000 --- a/ccsrc/include/experimental/decompositions/atom_storage.hpp +++ /dev/null @@ -1,200 +0,0 @@ -// Copyright 2021 -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef ATOM_STORAGE_HPP -#define ATOM_STORAGE_HPP - -#include -#include -#include -#include -#include -#include -#include - -#include "experimental/core/config.hpp" -#include "experimental/decompositions/config.hpp" -#include "experimental/decompositions/decomposition_atom.hpp" - -#if MQ_HAS_CONCEPTS -# include "experimental/core/concepts.hpp" -#endif // MQ_HAS_CONCEPTS - -#ifdef UNIT_TESTS -class UnitTestAccessor; -#endif // UNIT_TESTS - -namespace mindquantum::concepts { -#if MQ_HAS_CONCEPTS -template -concept atom_compatible_t = requires(atom_t) { - // clang-format off - { atom_t::kind() } -> std::same_as; - { atom_t::num_controls() } -> std::same_as; - // clang-format on -}; -#else -template -struct atom_compatible_t : std::false_type {}; - -template -struct atom_compatible_t>> - : std::true_type {}; -#endif // MQ_HAS_CONCEPTS -} // namespace mindquantum::concepts - -namespace mindquantum::decompositions { -namespace details { -template -struct is_pair : std::false_type {}; - -template -struct is_pair> : std::true_type {}; - -struct atom_less { - using is_transparent = void; - - template >::value && !is_pair>::value>> - constexpr auto operator()(T&& lhs, U&& rhs) const { - return std::forward(lhs) < std::forward(rhs); - } - - template - constexpr auto operator()(const std::pair& lhs, const std::pair& rhs) const { - if (lhs.first < rhs.first) { - return true; - } - return (lhs.first == rhs.first) && (lhs.second < rhs.second); - } -}; - -template -constexpr auto kind_lookup(const T& lhs, const std::pair& rhs) { - return lhs < rhs.first; -} -} // namespace details - -class AtomStorage { - public: - using atom_t = DecompositionAtom; - using map_t = std::map, atom_t, details::atom_less>; - - // Read-only accessors - - //! Return the number of decomposition atoms in the storage - /*! - * \return Pointer to inserted element, pointer to compatible element or nullptr. - */ - MQ_NODISCARD auto size() const noexcept { - // TODO(dnguyen): take general decompositions into account? If not need to change name! - return std::size(atoms_); - } - - //! Check whether a matching (gate) atom can be found in the storage - /*! - * The comparison is performed based on the value of \c o_atom_t::num_controls(), \c o_atom_t::name(), as well - * as taking \c o_atom_t::kinds_t into account. The matching for the kind is performed by calling \c - * atom->is_kind(type::kind()) for each operator contained in \c o_atom_t::kinds_t. - * - * \tparam o_atom_t Type of atom to look for - * \return True/false depending on whether the atom can be found or not - * \sa has_atom(num_control_t num_controls, std::string_view name) const - */ - template - MQ_NODISCARD bool has_atom() const noexcept; - - //! Check whether a matching (gate) atom can be found in the storage - /*! - * \note This method does not take general decompositions into account. - * - * \param kind Kind of atom to look for - * \param num_controls Number of control the atom must be constrained by - * \param name Name of atom to look for - * \return True/false depending on whether the atom can be found or not - */ - template - MQ_NODISCARD bool has_atom(num_control_t num_controls, std::string_view name) const noexcept; - - //! Look for a suitable decomposition atom within the storage - /*! - * \param inst An instruction - * \return Pointer to atom if any, \c nullptr otherwise - */ - MQ_NODISCARD atom_t* get_atom_for(const instruction_t& inst) noexcept; - - // Read-write accessors - - //! Inserts a new element, constructed in-place with the given args or returns an existing compatible atom - /*! - * This is different from add_or_return_atom in the sense that it does not enforce an exact match for the atom. - * - * \tparam o_atom_t Type of atom to insert/return - * \tparam kind_idx If the atom has multiple element in its kinds_t tuple, this is the index of the type in that - * tuple to use to register the atom inside the storage. - * \return Pointer to inserted element, pointer to compatible element. - */ - template - MQ_NODISCARD atom_t* add_or_compatible_atom(args_t&&... args); - - //! Inserts a new element, constructed in-place with the given args or returns an existing one - /*! - * This is different from add_or_compatible_atom in that it looks for an exact match. - * - * \tparam o_atom_t Type of atom to insert/return - * \tparam kind_idx If the atom has multiple element in its kinds_t tuple, this is the index of the type in that - * tuple to use to register the atom inside the storage. - * \return Pointer to inserted element, pointer to compatible element. - */ - template - MQ_NODISCARD atom_t* add_or_return_atom(args_t&&... args); - - //! Inserts or replaces a new element, constructed in-place with the given args - /*! - * \tparam o_atom_t Type of atom to insert/replace - * \tparam kind_idx If the atom has multiple element in its kinds_t tuple, this is the index of the type in that - * tuple to use to register the atom inside the storage. - * \return Pointer to inserted element, pointer to compatible element or nullptr. - */ - template - MQ_NODISCARD atom_t* add_or_replace_atom(args_t&&... args); - - private: -#ifdef UNIT_TESTS - friend class ::UnitTestAccessor; -#endif // UNIT_TESTS - - template - MQ_NODISCARD atom_t* add_or_non_replace_atom_(args_t&&... args); - - template - struct has_atom_helper_; - - template - struct has_atom_helper_> { - static constexpr auto apply(const AtomStorage& storage, num_control_t num_controls, std::string_view name) { - return storage.has_atom(num_controls, name); - } - }; - - map_t atoms_; - - // TODO(dnguyen): add vector of atoms for non-gate decompositions -}; -} // namespace mindquantum::decompositions - -#include "atom_storage.tpp" - -#endif /* ATOM_STORAGE_HPP */ diff --git a/ccsrc/include/experimental/decompositions/atom_storage.tpp b/ccsrc/include/experimental/decompositions/atom_storage.tpp deleted file mode 100644 index 2de0cfe82..000000000 --- a/ccsrc/include/experimental/decompositions/atom_storage.tpp +++ /dev/null @@ -1,158 +0,0 @@ -// Copyright 2021 -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef ATOM_STORAGE_TPP -#define ATOM_STORAGE_TPP - -#include -#include -#include - -#ifdef _MSC_VER -# include -#endif // _MSC_VER - -#include "experimental/decompositions/config.hpp" -#include "experimental/decompositions/decomposition_atom.hpp" -#include "experimental/decompositions/details/concepts.hpp" -#ifndef ATOM_STORAGE_HPP -# error This file must only be included by atom_storage.hpp! -#endif // ATOM_STORAGE_HPP - -// NB: This is mainly for syntax checkers and completion helpers as this file -// is only intended to be included directly by atom_storage.hpp -#include "experimental/decompositions/atom_storage.hpp" - -namespace mindquantum::decompositions { -// ========================================================================= -// ::has_atom - -template -bool AtomStorage::has_atom() const noexcept { - return has_atom_helper_::apply(*this, o_atom_t::num_controls(), - o_atom_t::name()); -} - -template -bool AtomStorage::has_atom(num_control_t num_controls, std::string_view name) const noexcept { - return std::find_if(begin(atoms_), end(atoms_), - [&num_controls, &name](const auto& item) { - return (item.second.is_kind(operators_t::kind()) || ...) && item.second.name() == name - && item.first.second == num_controls; - }) - != end(atoms_); -} - -// ========================================================================= -// ::add_or_compatible_atom - -template -auto AtomStorage::add_or_compatible_atom(args_t&&... args) -> atom_t* { - return add_or_non_replace_atom_, idx, args...>(std::forward(args)...); -} - -// ========================================================================= -// ::add_or_return_atom - -template -auto AtomStorage::add_or_return_atom(args_t&&... args) -> atom_t* { - return add_or_non_replace_atom_, idx, args...>(std::forward(args)...); -} - -// ========================================================================= -// ::add_or_replace_atom - -template -auto AtomStorage::add_or_replace_atom(args_t&&... args) -> atom_t* { - static constexpr auto num_controls = o_atom_t::num_controls(); - - const auto kind = std::tuple_element_t::kind(); - const auto atoms_end = end(atoms_); - - const auto kind_match = [kind = kind](const map_t::value_type& item) { return item.first.first == kind; }; - - /* Multiple cases here: - * - if there is a rule that can handle any number of qubits, see if we need to insert - * - else - * + look if there is already a match based on the kind and number of constrained control qubits - * * if there is, replace the matching atom - * * else, do a simple insertion - */ - - auto it_begin = std::find_if(begin(atoms_), atoms_end, kind_match); - - map_t::iterator it_match(atoms_end); - - if (num_controls == any_control && it_begin != atoms_end && it_begin->first.second == any_control) { - // Do replacement - it_match = it_begin; - } else { -#ifdef _MSC_VER - const std::function -#else - const auto -#endif // _MSC_VER - atom_match = [kind_match = kind_match, num_controls = num_controls](const map_t::value_type& item) { - return kind_match(item) && item.first.second == num_controls; - }; - // First have a look if we know of this kind of atom - it_match = std::find_if(it_begin, atoms_end, atom_match); - - if (it_match == atoms_end) { - // Simple insertion - const auto& [it, _] = atoms_.emplace(map_t::key_type{kind, num_controls}, - o_atom_t::create(*this, std::forward(args)...)); - return &it->second; - } - } - - // TODO(damien): Avoid replacement if name and kind match? - it_match->second = o_atom_t::create(*this, std::forward(args)...); - return &it_match->second; -} - -// ========================================================================= -// ::add_or_non_replace_atom_ - -template -auto AtomStorage::add_or_non_replace_atom_(args_t&&... args) -> atom_t* { - static constexpr auto num_controls = o_atom_t::num_controls(); - - const auto kind = std::tuple_element_t::kind(); - const auto atoms_end = end(atoms_); - -#ifdef _MSC_VER - const std::function -#else - const auto -#endif // _MSC_VER - atom_match = [&kind, num_controls = num_controls](const map_t::value_type& item) { - return item.first.first == kind && ctrl_comp_t{}(item.first.second, num_controls); - }; - - const auto it_match = std::find_if(begin(atoms_), atoms_end, atom_match); - - if (it_match == atoms_end) { - // Simple insertion - const auto& [it, _] = atoms_.emplace(map_t::key_type{kind, num_controls}, - o_atom_t::create(*this, std::forward(args)...)); - return &it->second; - } - - return &it_match->second; -} - -} // namespace mindquantum::decompositions - -#endif /* ATOM_STORAGE_TPP */ diff --git a/ccsrc/include/experimental/decompositions/config.hpp b/ccsrc/include/experimental/decompositions/config.hpp deleted file mode 100644 index fb38c16a2..000000000 --- a/ccsrc/include/experimental/decompositions/config.hpp +++ /dev/null @@ -1,62 +0,0 @@ -// Copyright 2021 -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef DECOMPOSITIONS_CONFIG_HPP -#define DECOMPOSITIONS_CONFIG_HPP - -#include -#include - -#include -#include -#include -#include - -#include "experimental/core/config.hpp" - -namespace mindquantum::decompositions { -using num_target_t = uint32_t; -using num_control_t = int32_t; -using num_param_t = uint32_t; - -//! Constant representing no constraints on the number of target qubits -static constexpr auto any_target = num_target_t(0); - -//! Constant representing no constraints on the number of control qubits -static constexpr auto any_control = num_control_t(-1); -} // namespace mindquantum::decompositions - -namespace mindquantum::traits { -//! Type traits class to calculate control qubit related constants -template -struct controls { - /*! - * Number of controls qubits to be used when decomposing a gate. This constant is required to calculate which - * control qubits are "free" control qubits and which ones are actually required as part of the decomposition - * rule of a gate. - * - * e.g. (a) the X -> H Z H decomposition has no constraint -> 0 - * (b) the CX -> H CZ H decomposition is constrained to 1 control qubit -> 1 - * - * -> applying (a) to CCX would therefore have 2 "free" control qubits - * -> applying (b) to CCX would therefore have 1 "free" control qubit and 1 control qubit used in the - * decomposition rule - */ - static constexpr auto num_controls_for_decomp = (num_controls_ == decompositions::any_control) - ? decompositions::num_control_t(0) - : num_controls_; -}; -} // namespace mindquantum::traits - -#endif /* DECOMPOSITIONS_CONFIG_HPP */ diff --git a/ccsrc/include/experimental/decompositions/decomposition_atom.hpp b/ccsrc/include/experimental/decompositions/decomposition_atom.hpp deleted file mode 100644 index 7f9b2be16..000000000 --- a/ccsrc/include/experimental/decompositions/decomposition_atom.hpp +++ /dev/null @@ -1,318 +0,0 @@ -// Copyright 2021 -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef DECOMPOSITION_ATOM_HPP -#define DECOMPOSITION_ATOM_HPP - -#include -#include -#include -#include -#include -#include - -#include "experimental/core/config.hpp" -#include "experimental/core/control.hpp" -#include "experimental/core/operator_traits.hpp" -#include "experimental/decompositions/config.hpp" -#include "experimental/decompositions/details/concepts.hpp" -#include "experimental/ops/gates/invalid.hpp" -#include "experimental/ops/parametric/config.hpp" -#include "experimental/ops/parametric/register_gate_type.hpp" - -namespace mindquantum::decompositions { -class DecompositionAtom { - public: - using gate_param_t = mindquantum::ops::parametric::gate_param_t; - - template , DecompositionAtom>>> - DecompositionAtom(atom_t&& atom) noexcept { // NOLINT(runtime/explicit) - static_assert(std::is_trivially_copyable_v>); - constexpr bool is_small = sizeof(Model, true>) <= small_size; - new (&model_) Model, is_small>(std::forward(atom)); - concept_ = &Model, is_small>::vtable_; - } - - DecompositionAtom(const DecompositionAtom& other) noexcept : concept_(other.concept_) { - concept_->clone(&other.model_, &model_); - } - DecompositionAtom& operator=(const DecompositionAtom& other) noexcept { - if (this != &other) { - concept_->dtor(&model_); - - concept_ = other.concept_; - concept_->clone(&other.model_, &model_); - } - return *this; - } - - DecompositionAtom(DecompositionAtom&& other) noexcept : concept_(other.concept_) { - std::copy(begin(other.model_), end(other.model_), begin(model_)); - std::fill(begin(other.model_), end(other.model_), std::byte{0}); - other.concept_ = nullptr; - } - DecompositionAtom& operator=(DecompositionAtom&& other) noexcept { - if (this != &other) { - concept_ = other.concept_; - std::copy(begin(other.model_), end(other.model_), begin(model_)); - std::fill(begin(other.model_), end(other.model_), std::byte{0}); - other.concept_ = nullptr; - } - return *this; - } - - ~DecompositionAtom() noexcept { - if (concept_ != nullptr) { - concept_->dtor(&model_); - } - } - - //! Return the name of this decomposition atom - MQ_NODISCARD auto name() const noexcept { - return concept_->name(); - } - - //! Test whether an atom has (supports) a particular kind of operator - MQ_NODISCARD auto is_kind(std::string_view kind) const noexcept { - return concept_->is_kind(kind); - } - - //! Test whether this atom is applicable to a particular instruction - /*! - * Child classes may implement a method named \c is_applicable_impl in order to customize the default - * behaviour for this method. - * - * \param inst An instruction - * \return True if the atom can be applied, false otherwise - */ - MQ_NODISCARD bool is_applicable(const instruction_t& inst) const noexcept { - return concept_->is_applicable(&model_, inst); - } - - //! Apply a decomposition atom to decompose an instruction - /*! - * \pre is_applicable() returns true - * \param circuit A quantum circuit to apply the decomposition atom to - * \param inst A quantum instruction to decompose - */ - void apply(circuit_t& circuit, const instruction_t& inst) noexcept { - return concept_->apply(&model_, circuit, inst); - } - - //! Apply the atom (ie. the decomposition it represents) to a quantum circuit - /*! - * This overload assumes the decomposition atom is not parametric - * - * \param circuit A quantum circuit to apply the decomposition atom to - * \param op A quantum operation - * \param qubits A list of qubits to apply the decomposition atom - * \param cbits A list of classical bit the decomposition applies to - * - * \note Currently the \c cbits parameter is not used at all! It is here to make the API futureproof. - */ - void apply(circuit_t& circuit, const operator_t& op, const qubits_t& qubits, const cbits_t& cbits = {}) noexcept { - concept_->apply_operator(&model_, circuit, op, qubits, cbits); - } - - private: - struct Concept { - void (*dtor)(void*) noexcept; // NOLINT(readability/casting) - void (*clone)(void const*, void*) noexcept; - std::string_view (*name)() noexcept; - bool (*is_kind)(std::string_view) noexcept; - bool (*is_applicable)(void const*, const instruction_t&) noexcept; - void (*apply)(void*, circuit_t&, const instruction_t&) noexcept; - void (*apply_operator)(void*, circuit_t&, const operator_t&, const qubits_t&, const cbits_t&) noexcept; - } MQ_ALIGN(64); - - template - struct Model; - - static constexpr size_t small_size = sizeof(void*) * 4; - - // NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers,readability-magic-numbers) - alignas(64) std::array model_{}; - Concept const* concept_; -}; - -namespace details { -template -void apply_gate(atom_t& atom, circuit_t& circuit, const instruction_t& inst) { - /* NB: The approach below has one key limitation in that it is not able to handle decomposition rules that - * match the following conditions: - * - non-constant number of target qubits - * - no constraints on the number of control qubits - * - the decomposition needs access to some of the control qubits - * - * e.g. imagine you have a quantum operator `A` that has variable number of targets and you would like - * to write a decomposition rule that should apply regardless of the number of control qubits and that aim - * to reduce the number of control qubits by 1, such that: - * - CCCA -> CA + some other gates - * - CCA -> CA + some other gates - * - CA -> A + some other gates - * - * As it is now, this decomposition rule will have num_controls_for_decomp == 0 and therefore never - * receive any control qubits when its apply(...) methods are called. - * - * However, if the number of target qubits is fixed, no such limitation exists. - */ - - assert(inst.num_controls() >= atom_t::num_controls_for_decomp); - const auto qubit_offset = inst.num_controls() - atom_t::num_controls_for_decomp; - - auto free_controls = qubits_t{}; - for (auto i(0); i < qubit_offset; ++i) { - free_controls.emplace_back(inst.qubit(i)); - } - auto qubits = qubits_t{}; - for (auto i(qubit_offset); i < inst.num_qubits(); ++i) { - qubits.emplace_back(inst.qubit(i)); - } - - MQ_WITH_CONTROL(circuit, controlled, free_controls) { - // TODO(dnguyen): Fix cbits argument if required in the future! - atom.apply(controlled, static_cast(inst), qubits, {}); - } -} -} // namespace details - -// Stack -template -struct DecompositionAtom::Model { - using type = atom_t; - - explicit Model(atom_t&& op) noexcept : operator_(std::forward(op)) { - } - - explicit Model(atom_t const& op) noexcept : operator_(op) { - } - - static auto* self_cast(void* self) noexcept { - return std::launder(reinterpret_cast(self)); - } - static auto* self_cast(const void* self) noexcept { - return std::launder(reinterpret_cast(self)); - } - - static void dtor(void* self) noexcept { - self_cast(self)->~Model(); - } - - static void clone(void const* self, void* other) noexcept { - new (other) Model, true>(self_cast(self)->operator_); - } - - static constexpr std::string_view name() noexcept { - return atom_t::name(); - } - - static constexpr bool is_kind(std::string_view kind) noexcept { - if constexpr (concepts::GateDecomposition) { - return traits::kind_compare(kind); - } else { - return false; - } - } - - static bool is_applicable(void const* self, const instruction_t& inst) noexcept { - return self_cast(self)->operator_.is_applicable(inst); - } - - static void apply(void* self, circuit_t& circuit, const instruction_t& inst) noexcept { - if constexpr (concepts::GateDecomposition) { - details::apply_gate(self_cast(self)->operator_, circuit, inst); - } else { - self_cast(self)->operator_.apply(circuit, inst); - } - } - - static void apply_operator(void* self, circuit_t& circuit, const operator_t& op, const qubits_t& qubits, - const cbits_t& cbits) noexcept { - if constexpr (concepts::GateDecomposition) { - self_cast(self)->operator_.apply(circuit, op, qubits, cbits); - } else { - circuit.apply_operator(ops::Invalid{}, qubits); - } - } - - static constexpr Concept vtable_{dtor, clone, name, is_kind, is_applicable, apply, apply_operator}; - - atom_t operator_; -}; - -// Heap -template -struct DecompositionAtom::Model { - explicit Model(atom_t&& op) noexcept : operator_(std::make_unique(std::forward(op))) { - } - - explicit Model(atom_t const& op) noexcept : operator_(std::make_unique(op)) { - } - - static auto* self_cast(void* self) noexcept { - return std::launder(reinterpret_cast(self)); - } - static auto* self_cast(const void* self) noexcept { - return std::launder(reinterpret_cast(self)); - } - - static void dtor(void* self) noexcept { - self_cast(self)->~Model(); - } - - static void clone(void const* self, void* other) noexcept { - new (other) Model(*self_cast(self)->operator_); - } - - static constexpr std::string_view name() noexcept { - return atom_t::name(); - } - - static constexpr bool is_kind(std::string_view kind) noexcept { - if constexpr (concepts::GateDecomposition) { - return traits::kind_compare(kind); - } else { - return false; - } - } - - static bool is_applicable(void const* self, const instruction_t& inst) noexcept { - return self_cast(self)->operator_->is_applicable(inst); - } - - static void apply(void* self, circuit_t& circuit, const instruction_t& inst) noexcept { - if constexpr (concepts::GateDecomposition) { - details::apply_gate(*(self_cast(self)->operator_), circuit, inst); - } else { - self_cast(self)->operator_->apply(circuit, inst); - } - } - - static void apply_operator(void* self, circuit_t& circuit, const operator_t& op, const qubits_t& qubits, - const cbits_t& cbits) noexcept { - if constexpr (concepts::GateDecomposition) { - self_cast(self)->operator_->apply(circuit, op, qubits, cbits); - } else { - circuit.apply_operator(ops::Invalid{std::size(qubits)}, qubits); - } - } - - static constexpr Concept vtable_{dtor, clone, name, is_kind, is_applicable, apply, apply_operator}; - - std::unique_ptr operator_; -}; -} // namespace mindquantum::decompositions - -#endif /* DECOMPOSITION_ATOM_HPP */ diff --git a/ccsrc/include/experimental/decompositions/decomposition_rule.hpp b/ccsrc/include/experimental/decompositions/decomposition_rule.hpp deleted file mode 100644 index aac58ee9b..000000000 --- a/ccsrc/include/experimental/decompositions/decomposition_rule.hpp +++ /dev/null @@ -1,127 +0,0 @@ -// Copyright 2022 -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef DECOMPOSITION_RULE_HPP -#define DECOMPOSITION_RULE_HPP - -#include -#include - -#include "experimental/decompositions/atom_storage.hpp" -#include "experimental/decompositions/config.hpp" -#include "experimental/decompositions/decomposition_atom.hpp" -#include "experimental/decompositions/details/traits.hpp" -#include "experimental/ops/parametric/config.hpp" - -namespace mindquantum::decompositions { -template -class DecompositionRule { - public: - using base_t = DecompositionRule; - using self_t = DecompositionRule; - - using gate_param_t = ops::parametric::gate_param_t; - - static_assert(traits::is_unique::type...>, "Atom types must be unique"); - - //! Return the name of this DecompositionRule - static constexpr auto name() noexcept { - return derived_t::name(); - } - - //! Helper function to create a DecompositionRule instance - /*! - * \param storage Atom storage within which this decomposition will live in - */ - template - MQ_NODISCARD static auto create(AtomStorage& storage, args_t&&... args) noexcept { - return derived_t{storage, std::forward(args)...}; - } - - // --------------------------------------------------------------------- - - //! Constructor - /*! - * \note The atoms of this decomposition rule will be insertd into the storage if they are not already - * present. However, existing (exactly matching) atoms will not be replaced. - * - * \param storage Atom storage within which this decomposition will live in - */ - explicit DecompositionRule(AtomStorage& storage); - - // --------------------------------------------------------------------- - - //! Getter function for the individual atoms - /*! - * Overload using a non-type template parameter corresponding to the index of the atom in the atom list. - * - * \tparam idx Index of atom in atom list - */ - template - constexpr auto* atom() noexcept MQ_REQUIRES((idx < sizeof...(atoms_t))); - - //! Getter function for the individual atoms - /*! - * Overload using a type template type parameter. This works since the list of atoms contains only unique - * values. - * - * \tparam atom_t Type of atom to look for. - */ - template - constexpr auto* atom() noexcept - MQ_REQUIRES((concepts::tuple_contains::type, - typename traits::atom_traits::type...>) ); - - //! Apply a decomposition - /*! - * \param circuit A quantum circuit to apply the decomposition atom to - * \param op A quantum operation to decompose - * \param qubits A list of qubits to apply the decomposition atom - * \param cbits A list of classical bit the decomposition applies to - * - * \note Currently the \c cbits parameter is not used at all! It is here to make the API futureproof. - */ - void apply(circuit_t& circuit, const operator_t& op, const qubits_t& qubits, const cbits_t& cbits) noexcept; - - protected: - //! Apply an invalid operatoir to a circuit (to indicate an error in processing) - /*! - * \param circuit Quantum circuit - * \param qubits List of qubits - */ - static void invalid_op_(circuit_t& circuit, const qubits_t& qubits); - //! Apply an invalid operatoir to a circuit (to indicate an error in processing) - /*! - * Overload for parametric operators. - * - * \param circuit Quantum circuit - * \param qubits List of qubits - * \param param Parameter to use during the application - */ - static void invalid_op_(circuit_t& circuit, const qubits_t& qubits, const gate_param_t& param); - - private: - template - auto create_(AtomStorage& storage); - - template - auto create_el_(AtomStorage& storage); - - std::array atoms_ = {}; -}; -} // namespace mindquantum::decompositions - -#include "decomposition_rule.tpp" - -#endif /* DECOMPOSITION_RULE_HPP */ diff --git a/ccsrc/include/experimental/decompositions/decomposition_rule.tpp b/ccsrc/include/experimental/decompositions/decomposition_rule.tpp deleted file mode 100644 index 31d4f9c6c..000000000 --- a/ccsrc/include/experimental/decompositions/decomposition_rule.tpp +++ /dev/null @@ -1,110 +0,0 @@ -// Copyright 2022 -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef DECOMPOSITION_RULE_TPP -#define DECOMPOSITION_RULE_TPP - -#include - -#include "experimental/decompositions/config.hpp" -#include "experimental/decompositions/decomposition_atom.hpp" -#ifndef DECOMPOSITION_RULE_HPP -# error This file must only be included by decomposition_rule.hpp! -#endif // DECOMPOSITION_RULE_HPP - -// NB: This is mainly for syntax checkers and completion helpers as this file -// is only intended to be included directly by atom_storage.hpp -#include "experimental/decompositions/decomposition_rule.hpp" -#include "experimental/ops/gates/invalid.hpp" - -namespace mindquantum::decompositions { - -// ========================================================================= -// ::DecompositionRule() - -template -DecompositionRule::DecompositionRule(AtomStorage& storage) - : atoms_{create_(storage)} { -} - -// ========================================================================= -// ::atom() - -template -template -constexpr auto* DecompositionRule::atom() noexcept MQ_REQUIRES((idx < sizeof...(atoms_t))) { -#if !MQ_HAS_CONCEPTS - static_assert(idx < sizeof...(atoms_t)); -#endif // !MQ_HAS_CONCEPTS - return atoms_[idx]; -} - -template -template -constexpr auto* DecompositionRule::atom() noexcept - MQ_REQUIRES((concepts::tuple_contains::type, - typename traits::atom_traits::type...>) ) { - using real_atom_t = typename traits::atom_traits::type; - using atoms_tuple_t = std::tuple::type...>; -#if !MQ_HAS_CONCEPTS - static_assert(traits::tuple_contains); -#endif // !MQ_HAS_CONCEPTS - return atom>(); -} - -// ========================================================================= -// ::apply() - -template -void DecompositionRule::apply(circuit_t& circuit, const operator_t& op, const qubits_t& qubits, - const cbits_t& cbits) noexcept { - static_cast(this)->apply_impl(circuit, op, qubits, cbits); -} - -// ========================================================================= -// ::invalid_op_() - -template -void DecompositionRule::invalid_op_(circuit_t& circuit, const qubits_t& qubits) { - circuit.apply_operator(ops::Invalid{std::size(qubits)}, qubits); -} - -template -void DecompositionRule::invalid_op_(circuit_t& circuit, const qubits_t& qubits, - const gate_param_t& /* param */) { - invalid_op_(circuit, qubits); -} - -// ========================================================================= -// ::create_() - -template -template -auto DecompositionRule::create_(AtomStorage& storage) { - return std::array{create_el_(storage)...}; -} - -// ========================================================================= -// ::create_el() - -template -template -auto DecompositionRule::create_el_(AtomStorage& storage) { - using atom_t = typename traits::atom_traits::type; - return storage.add_or_compatible_atom(); -} - -} // namespace mindquantum::decompositions - -#endif /* DECOMPOSITION_RULE_TPP */ diff --git a/ccsrc/include/experimental/decompositions/details/CPPLINT.cfg b/ccsrc/include/experimental/decompositions/details/CPPLINT.cfg deleted file mode 100644 index ecede325e..000000000 --- a/ccsrc/include/experimental/decompositions/details/CPPLINT.cfg +++ /dev/null @@ -1 +0,0 @@ -filter=-readability/braces diff --git a/ccsrc/include/experimental/decompositions/details/concepts.hpp b/ccsrc/include/experimental/decompositions/details/concepts.hpp deleted file mode 100644 index 74854b0c5..000000000 --- a/ccsrc/include/experimental/decompositions/details/concepts.hpp +++ /dev/null @@ -1,181 +0,0 @@ -// Copyright 2021 -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef DECOMPOSITIONS_CONCEPTS_HPP -#define DECOMPOSITIONS_CONCEPTS_HPP - -#include -#include - -#include "experimental/ops/parametric/config.hpp" - -namespace tweedledum { -class Circuit; -class Qubit; -} // namespace tweedledum - -namespace mindquantum::concepts { -using circuit_t = tweedledum::Circuit; -using qubits_t = std::vector; - -using ops::parametric::double_list_t; -using ops::parametric::gate_param_t; -using ops::parametric::param_list_t; -} // namespace mindquantum::concepts - -#if MQ_HAS_CONCEPTS -# include - -# include "experimental/core/concepts.hpp" -# include "experimental/core/traits.hpp" -# include "experimental/decompositions/config.hpp" - -namespace mindquantum::decompositions { -class AtomStorage; -} // namespace mindquantum::decompositions - -namespace mindquantum::concepts { -template -concept BaseDecomposition = requires(atom_t atom, decompositions::AtomStorage& storage, const instruction_t& inst) { - { std::remove_cvref_t::name() } -> std::same_as; - { std::remove_cvref_t::num_targets() } -> std::same_as; - { std::remove_cvref_t::num_controls() } -> std::same_as; - {std::remove_cvref_t::create(storage)}; - requires std::constructible_from, decompositions::AtomStorage&>; - { atom.is_applicable(inst) } -> std::same_as; -}; - -template -concept GateDecomposition = requires(atom_t) { - requires BaseDecomposition; - typename std::remove_cvref_t::kinds_t; - requires traits::is_tuple_v::kinds_t>; - { std::remove_cvref_t::num_params() } -> std::same_as; -}; - -template -concept GeneralDecomposition = requires(atom_t) { - requires BaseDecomposition; - requires !GateDecomposition; - typename std::remove_cvref_t::non_gate_decomposition; -}; - -template -concept has_non_param_apply = requires(T t, circuit_t circuit, qubits_t qubits) { - {t.apply(circuit, qubits)}; -}; - -template -concept has_param_apply = requires(T t, circuit_t circuit, qubits_t qubits, const gate_param_t params) { - {t.apply(circuit, qubits, params)}; -}; - -template -concept has_double_apply = requires(T t, circuit_t circuit, qubits_t qubits, double d) { - {t.apply(circuit, qubits, d)}; -}; -template -concept has_double_list_apply = requires(T t, circuit_t circuit, qubits_t qubits, double_list_t v) { - {t.apply(circuit, qubits, v)}; -}; -template -concept has_param_list_apply = requires(T t, circuit_t circuit, qubits_t qubits, param_list_t v) { - {t.apply(circuit, qubits, v)}; -}; -} // namespace mindquantum::concepts -#else -namespace mindquantum::concepts { -template -struct GateDecomposition_ : std::false_type {}; - -template -struct GateDecomposition_> : std::true_type {}; - -template -static constexpr auto GateDecomposition = GateDecomposition_::value; - -template -struct GeneralDecomposition_ : std::false_type {}; - -template -struct GeneralDecomposition_> : std::true_type {}; - -template -static constexpr auto GeneralDecomposition = !GateDecomposition && GeneralDecomposition_::value; - -// --------------------------------- - -template -struct has_non_param_apply_ : std::false_type {}; - -template -struct has_non_param_apply_< - Op, std::void_t().apply(std::declval(), std::declval()))>> - : std::true_type {}; - -template -static constexpr auto has_non_param_apply = has_non_param_apply_::value; - -// --------------------------------- - -template -struct has_param_apply_ : std::false_type {}; - -template -struct has_param_apply_().apply( - std::declval(), std::declval(), std::declval()))>> - : std::true_type {}; - -template -static constexpr auto has_param_apply = has_param_apply_::value; - -// --------------------------------- - -template -struct has_double_apply_ : std::false_type {}; - -template -struct has_double_apply_().apply( - std::declval(), std::declval(), std::declval()))>> - : std::true_type {}; -template -static constexpr auto has_double_apply = has_double_apply_::value; - -// --------------------------------- - -template -struct has_double_list_apply_ : std::false_type {}; - -template -struct has_double_list_apply_< - Op, std::void_t().apply(std::declval(), std::declval(), - std::declval()))>> : std::true_type {}; -template -static constexpr auto has_double_list_apply = has_double_list_apply_::value; - -// --------------------------------- - -template -struct has_param_list_apply_ : std::false_type {}; - -template -struct has_param_list_apply_< - Op, std::void_t().apply(std::declval(), std::declval(), - std::declval()))>> : std::true_type {}; -template -static constexpr auto has_param_list_apply = has_param_list_apply_::value; -} // namespace mindquantum::concepts -#endif // MQ_HAS_CONCEPTS - -#endif /* DECOMPOSITIONS_CONCEPTS_HPP */ diff --git a/ccsrc/include/experimental/decompositions/details/decomposition_param.hpp b/ccsrc/include/experimental/decompositions/details/decomposition_param.hpp deleted file mode 100644 index 59b84ab38..000000000 --- a/ccsrc/include/experimental/decompositions/details/decomposition_param.hpp +++ /dev/null @@ -1,118 +0,0 @@ -// Copyright 2021 -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef DECOMPOSITION_PARAM_HPP -#define DECOMPOSITION_PARAM_HPP - -#include - -#include "experimental/decompositions/config.hpp" -#include "experimental/ops/parametric/config.hpp" - -namespace mindquantum::decompositions { -//! Aggregate type to store DecompositionRule template parameters -struct DecompositionRuleParam { - num_target_t num_targets; //!< Number of target qubits the decomposition is constrained on - num_control_t num_controls; //!< Number of control qubits the decomposition is constrained on - num_param_t num_params; //!< Number of parameters the decomposition rule possesses -} MQ_ALIGN(16); - -// --------------------------------- -// Definition of special values for decomposition rule template parameter - -//! Namespace containing some helper constants to use when defining DecompositionRule classes -namespace tparam { -//! Constants for decomposition rules without constraints on the number of target qubits -namespace any_tgt { -static constexpr auto any_ctrl = DecompositionRuleParam{0, any_control, 0}; -static constexpr auto no_ctrl = DecompositionRuleParam{0, 0, 0}; -static constexpr auto single_ctrl = DecompositionRuleParam{0, 1, 0}; -static constexpr auto double_ctrl = DecompositionRuleParam{0, 2, 0}; -} // namespace any_tgt - -//! Constants for decomposition rules for single target qubit gates -namespace single_tgt { -static constexpr auto any_ctrl = DecompositionRuleParam{1, any_control, 0}; -static constexpr auto no_ctrl = DecompositionRuleParam{1, 0, 0}; -static constexpr auto single_ctrl = DecompositionRuleParam{1, 1, 0}; -static constexpr auto double_ctrl = DecompositionRuleParam{1, 2, 0}; -} // namespace single_tgt - -//! Constants for decomposition rules for single target qubit gates -namespace dual_tgt { -static constexpr auto any_ctrl = DecompositionRuleParam{2, any_control, 0}; -static constexpr auto no_ctrl = DecompositionRuleParam{2, 0, 0}; -static constexpr auto single_ctrl = DecompositionRuleParam{2, 1, 0}; -static constexpr auto double_ctrl = DecompositionRuleParam{2, 2, 0}; -} // namespace dual_tgt - -//! Constants for decomposition rules for single target qubit with parameteric gates with 1 parameter -namespace single_tgt_param { -static constexpr auto any_ctrl = DecompositionRuleParam{1, any_control, 1}; -static constexpr auto no_ctrl = DecompositionRuleParam{1, 0, 1}; -static constexpr auto single_ctrl = DecompositionRuleParam{1, 1, 1}; -static constexpr auto double_ctrl = DecompositionRuleParam{1, 2, 1}; -} // namespace single_tgt_param - -static constexpr auto default_t = any_tgt::any_ctrl; -} // namespace tparam -} // namespace mindquantum::decompositions - -#if MQ_HAS_CLASS_NON_TYPE_TEMPLATE_ARGS -# define ANY_TGT_ANY_CTRL mindquantum::decompositions::tparam::any_tgt::any_ctrl -# define ANY_TGT_NO_CTRL mindquantum::decompositions::tparam::any_tgt::no_ctrl -# define ANY_TGT_SINGLE_CTRL mindquantum::decompositions::tparam::any_tgt::single_ctrl -# define ANY_TGT_DOUBLE_CTRL mindquantum::decompositions::tparam::any_tgt::double_ctrl - -# define SINGLE_TGT_ANY_CTRL mindquantum::decompositions::tparam::single_tgt::any_ctrl -# define SINGLE_TGT_NO_CTRL mindquantum::decompositions::tparam::single_tgt::no_ctrl -# define SINGLE_TGT_SINGLE_CTRL mindquantum::decompositions::tparam::single_tgt::single_ctrl -# define SINGLE_TGT_DOUBLE_CTRL mindquantum::decompositions::tparam::single_tgt::double_ctrl - -# define DUAL_TGT_ANY_CTRL mindquantum::decompositions::tparam::dual_tgt::any_ctrl -# define DUAL_TGT_NO_CTRL mindquantum::decompositions::tparam::dual_tgt::no_ctrl -# define DUAL_TGT_SINGLE_CTRL mindquantum::decompositions::tparam::dual_tgt::single_ctrl -# define DUAL_TGT_DOUBLE_CTRL mindquantum::decompositions::tparam::dual_tgt::double_ctrl - -# define SINGLE_TGT_PARAM_ANY_CTRL mindquantum::decompositions::tparam::single_tgt_param::any_ctrl -# define SINGLE_TGT_PARAM_NO_CTRL mindquantum::decompositions::tparam::single_tgt_param::no_ctrl -# define SINGLE_TGT_PARAM_SINGLE_CTRL mindquantum::decompositions::tparam::single_tgt_param::single_ctrl -# define SINGLE_TGT_PARAM_DOUBLE_CTRL mindquantum::decompositions::tparam::single_tgt_param::double_ctrl -#else -# define MQ_INTERNAL_DR_EXPAND_TPARAM_(value) value.num_targets, value.num_controls, value.num_params -// NOLINTNEXTLINE(whitespace/line_length) -# define MQ_INTERNAL_DR_EXPAND_TPARAM(value) MQ_INTERNAL_DR_EXPAND_TPARAM_(mindquantum::decompositions::value) - -# define ANY_TGT_ANY_CTRL MQ_INTERNAL_DR_EXPAND_TPARAM(tparam::any_tgt::any_ctrl) -# define ANY_TGT_NO_CTRL MQ_INTERNAL_DR_EXPAND_TPARAM(tparam::any_tgt::no_ctrl) -# define ANY_TGT_SINGLE_CTRL MQ_INTERNAL_DR_EXPAND_TPARAM(tparam::any_tgt::single_ctrl) -# define ANY_TGT_DOUBLE_CTRL MQ_INTERNAL_DR_EXPAND_TPARAM(tparam::any_tgt::double_ctrl) - -# define SINGLE_TGT_ANY_CTRL MQ_INTERNAL_DR_EXPAND_TPARAM(tparam::single_tgt::any_ctrl) -# define SINGLE_TGT_NO_CTRL MQ_INTERNAL_DR_EXPAND_TPARAM(tparam::single_tgt::no_ctrl) -# define SINGLE_TGT_SINGLE_CTRL MQ_INTERNAL_DR_EXPAND_TPARAM(tparam::single_tgt::single_ctrl) -# define SINGLE_TGT_DOUBLE_CTRL MQ_INTERNAL_DR_EXPAND_TPARAM(tparam::single_tgt::double_ctrl) - -# define DUAL_TGT_ANY_CTRL MQ_INTERNAL_DR_EXPAND_TPARAM(tparam::dual_tgt::any_ctrl) -# define DUAL_TGT_NO_CTRL MQ_INTERNAL_DR_EXPAND_TPARAM(tparam::dual_tgt::no_ctrl) -# define DUAL_TGT_DUAL_CTRL MQ_INTERNAL_DR_EXPAND_TPARAM(tparam::dual_tgt::dual_ctrl) -# define DUAL_TGT_DOUBLE_CTRL MQ_INTERNAL_DR_EXPAND_TPARAM(tparam::dual_tgt::double_ctrl) - -# define SINGLE_TGT_PARAM_ANY_CTRL MQ_INTERNAL_DR_EXPAND_TPARAM(tparam::single_tgt_param::any_ctrl) -# define SINGLE_TGT_PARAM_NO_CTRL MQ_INTERNAL_DR_EXPAND_TPARAM(tparam::single_tgt_param::no_ctrl) -# define SINGLE_TGT_PARAM_SINGLE_CTRL MQ_INTERNAL_DR_EXPAND_TPARAM(tparam::single_tgt_param::single_ctrl) -# define SINGLE_TGT_PARAM_DOUBLE_CTRL MQ_INTERNAL_DR_EXPAND_TPARAM(tparam::single_tgt_param::double_ctrl) -#endif // MQ_HAS_CLASS_NON_TYPE_TEMPLATE_ARGS - -#endif /* DECOMPOSITION_PARAM_HPP */ diff --git a/ccsrc/include/experimental/decompositions/details/gate_decomposition_rule_cxx17.hpp b/ccsrc/include/experimental/decompositions/details/gate_decomposition_rule_cxx17.hpp deleted file mode 100644 index 02bd02e0a..000000000 --- a/ccsrc/include/experimental/decompositions/details/gate_decomposition_rule_cxx17.hpp +++ /dev/null @@ -1,104 +0,0 @@ -// Copyright 2021 -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef GATE_DECOMPOSITION_RULE_CXX17_HPP -#define GATE_DECOMPOSITION_RULE_CXX17_HPP - -#include -#include - -#include "experimental/decompositions/config.hpp" -#include "experimental/decompositions/decomposition_rule.hpp" -#include "experimental/ops/parametric/config.hpp" - -namespace mindquantum::decompositions { -template -class GateDecompositionRuleCXX17; - -template -using GateDecompositionRule - = GateDecompositionRuleCXX17; -} // namespace mindquantum::decompositions - -// ============================================================================= - -namespace mindquantum::decompositions { -template -class GateDecompositionRuleCXX17 - : public DecompositionRule - , public traits::controls { - public: - using base_t = GateDecompositionRuleCXX17; - using kinds_t = kinds_t_; - using parent_t = DecompositionRule; - using self_t = GateDecompositionRuleCXX17; - - using gate_param_t = ops::parametric::gate_param_t; - using double_list_t = ops::parametric::double_list_t; - using param_list_t = ops::parametric::param_list_t; - - // --------------------------------------------------------------------- - - using DecompositionRule::DecompositionRule; - - // --------------------------------------------------------------------- - - //! Return the number of target qubits this DecompositionRule is constrained on - static constexpr auto num_targets() noexcept { - return num_targets_; - } - - //! Return the number of control qubits this DecompositionRule is constrained on - static constexpr auto num_controls() noexcept { - return num_controls_; - } - - //! Constant boolean indicating whether the GateDecompositionRuleCXX17 is parametric or not - static constexpr auto is_parametric = num_params_ != 0U; - - //! Return the number of parameters of this GateDecompositionRuleCXX17 - static constexpr auto num_params() noexcept { - return num_params_; - } - - // --------------------------------------------------------------------- - - //! Check whether a decomposition is compatible with another one. - /*! - * Another GateDecompositionRuleCXX17 instance is deemed compatible iff: - * - the number of target qubit are identical - * - the number of controls are compatible: - * - the number of control qubits in the decomposition rule is left undefined - * - or they have the same number of controls - * - * \param num_targets Number of target qubits of the operation to decompose - * \param num_controls Number of control qubits of the operation to decompose - */ - // TODO(dnguyen): constrain `rule_t` to decomposition atoms - template - MQ_NODISCARD constexpr bool is_compatible() const noexcept; - - //! Check whether a decomposition is applicable with a given instruction - /*! - * \param inst A quantum instruction - */ - MQ_NODISCARD bool is_applicable(const instruction_t& inst) const noexcept; -}; -} // namespace mindquantum::decompositions - -#include "gate_decomposition_rule_cxx17.tpp" - -#endif /* GATE_DECOMPOSITION_RULE_CXX17_HPP */ diff --git a/ccsrc/include/experimental/decompositions/details/gate_decomposition_rule_cxx17.tpp b/ccsrc/include/experimental/decompositions/details/gate_decomposition_rule_cxx17.tpp deleted file mode 100644 index b2d4c197e..000000000 --- a/ccsrc/include/experimental/decompositions/details/gate_decomposition_rule_cxx17.tpp +++ /dev/null @@ -1,64 +0,0 @@ -// Copyright 2021 -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef GATE_DECOMPOSITION_RULE_CXX17_TPP -#define GATE_DECOMPOSITION_RULE_CXX17_TPP - -#include "experimental/decompositions/config.hpp" -#include "experimental/decompositions/decomposition_atom.hpp" -#ifndef GATE_DECOMPOSITION_RULE_CXX17_HPP -# error This file must only be included by gate_decomposition_rule_cxx17.hpp! -#endif // GATE_DECOMPOSITION_RULE_CXX17_HPP - -// NB: This is mainly for syntax checkers and completion helpers as this file -// is only intended to be included directly by atom_storage.hpp -#include "experimental/decompositions/details/gate_decomposition_rule_cxx17.hpp" - -namespace mindquantum::decompositions { - -// ========================================================================= -// ::is_compatible() - -template -template -constexpr bool GateDecompositionRuleCXX17::is_compatible() const noexcept { - return num_targets_ == rule_t::num_targets_ - && (num_controls_ < 0 || rule_t::num_controls_ < 0 || num_controls_ == rule_t::num_controls_); -} - -// ========================================================================= -// ::is_applicable() - -template -bool GateDecompositionRuleCXX17::is_applicable(const instruction_t& inst) const noexcept { - if constexpr (traits::has_is_applicable_v) { - return static_cast(this)->is_applicable_impl(inst); - } else { - return traits::kind_compare(inst.kind()) && (derived_t::num_params() == inst.num_parameters()) - && ((derived_t::num_targets() == decompositions::any_target) - || derived_t::num_targets() == inst.num_targets()) - && (derived_t::num_controls() == decompositions::any_control - /* It is ok for a decomposition rule constrained on N control qubits to decompose an instruction - * with M >= N qubits; the "extra" control qubits are simply counted as "free" control qubits. - */ - || derived_t::num_controls() <= inst.num_controls()); // TODO(dnguyen): Use == instead? - } -} -} // namespace mindquantum::decompositions - -#endif /* GATE_DECOMPOSITION_RULE_CXX17_TPP */ diff --git a/ccsrc/include/experimental/decompositions/details/gate_decomposition_rule_cxx20.hpp b/ccsrc/include/experimental/decompositions/details/gate_decomposition_rule_cxx20.hpp deleted file mode 100644 index d90bedfea..000000000 --- a/ccsrc/include/experimental/decompositions/details/gate_decomposition_rule_cxx20.hpp +++ /dev/null @@ -1,100 +0,0 @@ -// Copyright 2021 -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef GATE_DECOMPOSITION_RULE_CXX20_HPP -#define GATE_DECOMPOSITION_RULE_CXX20_HPP - -#include -#include - -#include "experimental/decompositions/config.hpp" -#include "experimental/ops/parametric/config.hpp" - -#if MQ_HAS_CONCEPTS -# include "experimental/core/gate_concepts.hpp" -#endif // MQ_HAS_CONCEPTS - -#include "experimental/decompositions/decomposition_rule.hpp" -#include "experimental/decompositions/details/decomposition_param.hpp" - -// ============================================================================= - -namespace mindquantum::decompositions { -template -class GateDecompositionRule - : public DecompositionRule - , public traits::controls { - public: - using base_t = GateDecompositionRule; - using kinds_t = kinds_t_; - using self_t = GateDecompositionRule; - - using gate_param_t = ops::parametric::gate_param_t; - using double_list_t = ops::parametric::double_list_t; - using param_list_t = ops::parametric::param_list_t; - - // --------------------------------------------------------------------- - - using DecompositionRule::DecompositionRule; - - // --------------------------------------------------------------------- - - //! Return the number of target qubits this DecompositionRule is constrained on - static constexpr auto num_targets() noexcept { - return param_.num_targets; - } - - //! Return the number of control qubits this DecompositionRule is constrained on - static constexpr auto num_controls() noexcept { - return param_.num_controls; - } - - //! Constant boolean indicating whether the GateDecompositionRule is parametric or not - static constexpr auto is_parametric = param_.num_params != 0U; - - //! Return the number of parameters of this GateDecompositionRule - static constexpr auto num_params() noexcept { - return param_.num_params; - } - - // --------------------------------------------------------------------- - - //! Check whether a decomposition is compatible with another one. - /*! - * Another GateDecompositionRule instance is deemed compatible iff: - * - the number of target qubit are identical - * - the number of controls are compatible: - * - the number of control qubits in the decomposition rule is left undefined - * - or they have the same number of controls - * - * \param num_targets Number of target qubits of the operation to decompose - * \param num_controls Number of control qubits of the operation to decompose - */ - // TODO(dnguyen): constrain `rule_t` to decomposition atoms - template - MQ_NODISCARD constexpr bool is_compatible() const noexcept; - - //! Check whether a decomposition is applicable with a given instruction - /*! - * \param inst A quantum instruction - */ - MQ_NODISCARD bool is_applicable(const instruction_t& inst) const noexcept; - - // ----------------------------- -}; -} // namespace mindquantum::decompositions - -#include "gate_decomposition_rule_cxx20.tpp" - -#endif /* GATE_DECOMPOSITION_RULE_CXX20_HPP */ diff --git a/ccsrc/include/experimental/decompositions/details/gate_decomposition_rule_cxx20.tpp b/ccsrc/include/experimental/decompositions/details/gate_decomposition_rule_cxx20.tpp deleted file mode 100644 index 8ab47e951..000000000 --- a/ccsrc/include/experimental/decompositions/details/gate_decomposition_rule_cxx20.tpp +++ /dev/null @@ -1,63 +0,0 @@ -// Copyright 2021 -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef GATE_DECOMPOSITION_RULE_CXX20_TPP -#define GATE_DECOMPOSITION_RULE_CXX20_TPP - -#include "experimental/decompositions/config.hpp" -#include "experimental/decompositions/decomposition_atom.hpp" -#include "experimental/decompositions/details/traits.hpp" -#ifndef GATE_DECOMPOSITION_RULE_CXX20_HPP -# error This file must only be included by gate_decomposition_rule_cxx20.hpp! -#endif // GATE_DECOMPOSITION_RULE_CXX20_HPP - -// NB: This is mainly for syntax checkers and completion helpers as this file -// is only intended to be included directly by atom_storage.hpp -#include "experimental/decompositions/details/gate_decomposition_rule_cxx20.hpp" - -namespace mindquantum::decompositions { - -// ========================================================================= -// ::is_compatible() - -template -template -MQ_NODISCARD constexpr bool GateDecompositionRule::is_compatible() - const noexcept { - return param_.num_targets == rule_t::num_targets_ - && (param_.num_controls < 0 || rule_t::num_controls_ < 0 || param_.num_controls == rule_t::num_controls_); -} - -// ========================================================================= -// ::is_applicable() - -template -MQ_NODISCARD bool GateDecompositionRule::is_applicable( - const instruction_t& inst) const noexcept { - if constexpr (traits::has_is_applicable_v) { - return static_cast(this)->is_applicable_impl(inst); - } else { - return traits::kind_compare(inst.kind()) && (derived_t::num_params() == inst.num_parameters()) - && ((derived_t::num_targets() == decompositions::any_target) - || derived_t::num_targets() == inst.num_targets()) - && (derived_t::num_controls() == decompositions::any_control - /* It is ok for a decomposition rule constrained on N control qubits to decompose an instruction - * with M >= N qubits; the "extra" control qubits are simply counted as "free" control qubits. - */ - || derived_t::num_controls() <= inst.num_controls()); // TODO(dnguyen): Use == instead? - } -} -} // namespace mindquantum::decompositions - -#endif /* GATE_DECOMPOSITION_RULE_CXX20_TPP */ diff --git a/ccsrc/include/experimental/decompositions/details/traits.hpp b/ccsrc/include/experimental/decompositions/details/traits.hpp deleted file mode 100644 index bbd483142..000000000 --- a/ccsrc/include/experimental/decompositions/details/traits.hpp +++ /dev/null @@ -1,135 +0,0 @@ -// Copyright 2021 -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef DECOMPOSITION_RULES_TRAITS_HPP -#define DECOMPOSITION_RULES_TRAITS_HPP - -#include -#include - -#include "experimental/core/config.hpp" -#include "experimental/decompositions/config.hpp" -#include "experimental/ops/parametric/traits.hpp" - -#if MQ_HAS_CONCEPTS -# include "experimental/core/gate_concepts.hpp" -#endif // MQ_HAS_CONCEPTS - -#include "experimental/decompositions/details/decomposition_param.hpp" -#include "experimental/decompositions/parametric_atom.hpp" -#include "experimental/decompositions/trivial_atom.hpp" - -namespace mindquantum::decompositions { -#if MQ_HAS_CLASS_NON_TYPE_TEMPLATE_ARGS -template -class GateDecompositionRule; -#else -template -class GateDecompositionRuleCXX17; -#endif // MQ_HAS_CLASS_NON_TYPE_TEMPLATE_ARGS -} // namespace mindquantum::decompositions - -namespace mindquantum::traits { -// Automatic type conversion utilities -#if MQ_HAS_CONCEPTS -template -struct atom_traits; - -template -struct atom_traits { - using type = decompositions::ParametricSimpleAtom; -}; -template -struct atom_traits { - using type = decompositions::TrivialSimpleAtom; -}; -#else -namespace details { -template -struct helper : std::false_type {}; - -template -struct helper().params())>> : std::true_type {}; -} // namespace details - -template -struct atom_traits { - using type = std::conditional_t::value, decompositions::ParametricSimpleAtom, - decompositions::TrivialSimpleAtom>; -}; -#endif - -#if MQ_HAS_CLASS_NON_TYPE_TEMPLATE_ARGS -template -struct atom_traits> { - using type = decompositions::GateDecompositionRule; -}; -#else -template -struct atom_traits> { - using type = decompositions::GateDecompositionRuleCXX17; -}; -#endif // MQ_HAS_CLASS_NON_TYPE_TEMPLATE_ARGS - -template -struct atom_traits> { - using type = decompositions::TrivialAtom; -}; - -template -struct atom_traits> { - using type = decompositions::ParametricAtom; -}; - -// ------------------------------------------------------------------------- -// Helper traits to handle atoms that do not provide atom_t::is_applicable - -template -struct has_is_applicable : std::false_type {}; - -template -struct has_is_applicable< - atom_t, std::void_t().is_applicable_impl(std::declval()))>> - : std::true_type {}; - -template -inline constexpr auto has_is_applicable_v = has_is_applicable::value; -} // namespace mindquantum::traits - -namespace mindquantum::decompositions::details { -template -constexpr auto index_in_tuple_fn() -#if MQ_HAS_CONCEPTS - requires(idx < std::tuple_size_v /* if this fails, elem_t is not in tuple_t */) -#endif // MQ_HAS_CONCEPTS -{ -#if !MQ_HAS_CONCEPTS - static_assert(idx < std::tuple_size_v, "The element is not in the tuple!"); -#endif // !MQ_HAS_CONCEPTS - using tuple_elem_t = typename std::tuple_element_t; - if constexpr (std::is_same_v) { - return idx; - } else { - return index_in_tuple_fn(); - } -} - -template -inline constexpr auto index_in_tuple = index_in_tuple_fn<0, elem_t, tuple_t>(); -} // namespace mindquantum::decompositions::details - -#endif /* DECOMPOSITION_RULES_TRAITS_HPP */ diff --git a/ccsrc/include/experimental/decompositions/gate_decomposer.hpp b/ccsrc/include/experimental/decompositions/gate_decomposer.hpp deleted file mode 100644 index 2d65ed018..000000000 --- a/ccsrc/include/experimental/decompositions/gate_decomposer.hpp +++ /dev/null @@ -1,111 +0,0 @@ -// Copyright 2021 -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef GATE_DECOMPOSER_HPP -#define GATE_DECOMPOSER_HPP - -#include -#include -#include - -#include "experimental/decompositions/atom_storage.hpp" - -#ifdef UNIT_TESTS -class UnitTestAccessor; -#endif // UNIT_TESTS - -namespace mindquantum::decompositions { -namespace details { -struct rules_less { // NOLINT(altera-struct-pack-align) - using is_transparent = void; - - template - constexpr auto operator()(T&& lhs, U&& rhs) const { - return std::forward(lhs).name() < std::forward(rhs).name(); - } -}; -} // namespace details - -class GateDecomposer { - public: - using atom_storage_t = AtomStorage; - using atom_t = atom_storage_t::atom_t; - using general_rule_storage_t = std::set; - - //! Return the number of atoms in the internal storage - MQ_NODISCARD auto num_atoms() const noexcept { - return std::size(atom_storage_); - } - - //! Return the number of general decomposition rules in the internal storage - MQ_NODISCARD auto num_rules() const noexcept { - return std::size(general_rule_storage_); - } - - //! Simple getter to the internal storage - MQ_NODISCARD const auto& storage() const noexcept { - return atom_storage_; - } - - //! Check whether a matching (gate) atom can be found in the storage - /*! - * The comparison is performed based on the value of \c o_atom_t::num_controls(), \c o_atom_t::name(), as well - * as taking \c o_atom_t::kinds_t into account. The matching for the kind is performed by calling \c - * atom->is_kind(type::kind()) for each operator contained in \c o_atom_t::kinds_t. - * - * \note This method does not take general decompositions into account. - * - * \tparam o_atom_t Type of atom to look for - * \return True/false depending on whether the atom can be found or not - */ - template - MQ_NODISCARD bool has_atom() const noexcept; - - //! Look for a suitable decomposition within the storages - /*! - * This method will favour gate decompositions over general decompositions when looking for a match. - * - * \param inst An instruction - * \return Pointer to atom if any, \c nullptr otherwise - */ - MQ_NODISCARD atom_t* get_atom_for(const instruction_t& inst) noexcept; - - // Read-write accessors - - //! Inserts a new element, constructed in-place with the given args - /*! - * The type \c o_atom_t will be used to determine where the atom will be stored; ie. whether it is a gate - * decomposition or a general decomposition. - * - * \tparam o_atom_t Type of atom to insert/replace - * \tparam kind_idx If the atom has multiple element in its kinds_t tuple, this is the index of the type in that - * tuple to use to register the atom inside the storage. - * \return Pointer to inserted element, pointer to compatible element or nullptr. - */ - template - MQ_NODISCARD atom_t* add_or_replace_atom(args_t&&... args); - - private: -#ifdef UNIT_TESTS - friend class ::UnitTestAccessor; -#endif // UNIT_TESTS - - atom_storage_t atom_storage_; - general_rule_storage_t general_rule_storage_; -}; -} // namespace mindquantum::decompositions - -#include "experimental/decompositions/gate_decomposer.tpp" // NOLINT(build/include) - -#endif /* GATE_DECOMPOSER_HPP */ diff --git a/ccsrc/include/experimental/decompositions/gate_decomposer.tpp b/ccsrc/include/experimental/decompositions/gate_decomposer.tpp deleted file mode 100644 index cd245cd35..000000000 --- a/ccsrc/include/experimental/decompositions/gate_decomposer.tpp +++ /dev/null @@ -1,66 +0,0 @@ -// Copyright 2021 -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef GATE_DECOMPOSER_TPP -#define GATE_DECOMPOSER_TPP - -#ifndef GATE_DECOMPOSER_HPP -# error This file must only be included by gate_decomposer.hpp! -#endif // !GATE_DECOMPOSER_HPP - -// clang-format off -// NB: This is mainly for syntax checkers and completion helpers as this file -// is only intended to be included directly by gate_decomposer.hpp -#include "experimental/decompositions/gate_decomposer.hpp" -// clang-format on - -#include - -namespace mindquantum::decompositions { - -// ========================================================================= -// ::has_atom - -template -bool GateDecomposer::has_atom() const noexcept { - if constexpr (concepts::GateDecomposition) { - return atom_storage_.has_atom(); - } else { - constexpr auto name = o_atom_t::name(); - return std::find_if(begin(general_rule_storage_), end(general_rule_storage_), - [&name](const auto& item) { return item.name() == name; }) - != end(general_rule_storage_); - } -} - -// ========================================================================= - -template -auto GateDecomposer::add_or_replace_atom(args_t&&... args) -> atom_t* { - if constexpr (concepts::GateDecomposition) { - return atom_storage_.add_or_replace_atom(std::forward(args)...); - } else { - auto [it, _] = general_rule_storage_.emplace(o_atom_t::create(atom_storage_, std::forward(args)...)); - /* NB: const_cast() is needed for compilers/STL implementations where std::set elements are always - * immutable when accessed through iterators. - */ - return &const_cast(*it); - } -} - -} // namespace mindquantum::decompositions - -// ============================================================================= - -#endif /* GATE_DECOMPOSER_TPP */ diff --git a/ccsrc/include/experimental/decompositions/gate_decomposition_rule.hpp b/ccsrc/include/experimental/decompositions/gate_decomposition_rule.hpp deleted file mode 100644 index 039d37af5..000000000 --- a/ccsrc/include/experimental/decompositions/gate_decomposition_rule.hpp +++ /dev/null @@ -1,26 +0,0 @@ -// Copyright 2022 -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef GATE_DECOMPOSITION_RULE_HPP -#define GATE_DECOMPOSITION_RULE_HPP - -#include "experimental/decompositions/decomposition_rule.hpp" - -#if MQ_HAS_CLASS_NON_TYPE_TEMPLATE_ARGS -# include "experimental/decompositions/details/gate_decomposition_rule_cxx20.hpp" -#else -# include "experimental/decompositions/details/gate_decomposition_rule_cxx17.hpp" -#endif // MQ_HAS_CLASS_NON_TYPE_TEMPLATE_ARGS - -#endif /* GATE_DECOMPOSITION_RULE_HPP */ diff --git a/ccsrc/include/experimental/decompositions/non_gate_decomposition_rule.hpp b/ccsrc/include/experimental/decompositions/non_gate_decomposition_rule.hpp deleted file mode 100644 index c62da1b71..000000000 --- a/ccsrc/include/experimental/decompositions/non_gate_decomposition_rule.hpp +++ /dev/null @@ -1,67 +0,0 @@ -// Copyright 2022 -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef NON_GATE_DECOMPOSITION_RULE_HPP -#define NON_GATE_DECOMPOSITION_RULE_HPP - -#include "experimental/decompositions/atom_storage.hpp" -#include "experimental/decompositions/config.hpp" -#include "experimental/decompositions/decomposition_atom.hpp" -#include "experimental/decompositions/decomposition_rule.hpp" - -namespace mindquantum::decompositions { -template -class NonGateDecompositionRule : public DecompositionRule { - public: - using base_t = NonGateDecompositionRule; - using self_t = NonGateDecompositionRule; - using parent_t = DecompositionRule; - using non_gate_decomposition = void; - - // --------------------------------------------------------------------- - - explicit NonGateDecompositionRule(AtomStorage& storage) : parent_t{storage}, storage_{storage} { - } - - // --------------------------------------------------------------------- - - //! Getter function for the individual atoms - /*! - * Overload using a type template type parameter. This works since the list of atoms contains only unique - * values. - * - * \tparam atom_t Type of atom to look for. - */ - template - constexpr auto* atom(args_t&&... args) noexcept; - - auto& storage() noexcept { - return storage_; - } - - //! Apply a decomposition rule - /*! - * \param circuit Quantum circuit - * \param inst Quantum instructio to decompose - */ - void apply(circuit_t& circuit, const instruction_t& inst) noexcept; - - private: - AtomStorage& storage_; -}; -} // namespace mindquantum::decompositions - -#include "non_gate_decomposition_rule.tpp" - -#endif /* NON_GATE_DECOMPOSITION_RULE_HPP */ diff --git a/ccsrc/include/experimental/decompositions/non_gate_decomposition_rule.tpp b/ccsrc/include/experimental/decompositions/non_gate_decomposition_rule.tpp deleted file mode 100644 index 49e7dda26..000000000 --- a/ccsrc/include/experimental/decompositions/non_gate_decomposition_rule.tpp +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright 2022 -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef NON_GATE_DECOMPOSITION_RULE_TPP -#define NON_GATE_DECOMPOSITION_RULE_TPP - -#ifndef NON_GATE_DECOMPOSITION_RULE_HPP -# error This file must only be included by non_gate_decomposition_rule.hpp! -#endif // NON_GATE_DECOMPOSITION_RULE_HPP - -// NB: This is mainly for syntax checkers and completion helpers as this file -// is only intended to be included directly by non_gate_decomposition_rule.hpp -#include -#include - -#include "experimental/decompositions/non_gate_decomposition_rule.hpp" - -namespace mindquantum::decompositions { - -// ========================================================================= -// ::NonGateDecompositionRule - -template -template -constexpr auto* NonGateDecompositionRule::atom(args_t&&... args) noexcept { - using real_atom_t = typename traits::atom_traits::type; - using atoms_tuple_t = std::tuple::type...>; - - if constexpr (traits::tuple_contains) { - return parent_t::template atom(); - } else { - return storage_.add_or_return_atom(std::forward(args)...); - } -} - -// ========================================================================= -// ::apply() - -template -void NonGateDecompositionRule::apply(circuit_t& circuit, const instruction_t& inst) noexcept { - static_cast(this)->apply_impl(circuit, inst); -} - -} // namespace mindquantum::decompositions - -#endif /* NON_GATE_DECOMPOSITION_RULE_TPP */ diff --git a/ccsrc/include/experimental/decompositions/parametric_atom.hpp b/ccsrc/include/experimental/decompositions/parametric_atom.hpp deleted file mode 100644 index a567bab47..000000000 --- a/ccsrc/include/experimental/decompositions/parametric_atom.hpp +++ /dev/null @@ -1,110 +0,0 @@ -// Copyright 2021 -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef PARAMETRIC_ATOM_HPP -#define PARAMETRIC_ATOM_HPP - -#include - -#include "experimental/core/config.hpp" -#include "experimental/core/operator_traits.hpp" -#include "experimental/decompositions/atom_storage.hpp" -#include "experimental/decompositions/config.hpp" -#include "experimental/ops/parametric/config.hpp" -#include "experimental/ops/parametric/gate_base.hpp" - -namespace mindquantum::decompositions { -namespace details { -using namespace ops::parametric::details; // NOLINT(build/namespaces) -} // namespace details - -//! A decomposition atom representing a gate with some free-parameter(s) -/*! - * \note This must be a parametric gate with at least one free parameter - * - * \tparam operator_t Type of the gate the atom is representing - * \tparam num_targets_ Number of target qubits the gate this atom is representing has - * \tparam num_controls_ Number of control qubits the gate this atom is representing has. Possible values: - * -1 for any number of control qubits, >= 0 for a specified number of control qubits. - */ -template -class ParametricAtom : public traits::controls { - public: - using subs_map_t = mindquantum::ops::parametric::subs_map_t; - using double_list_t = mindquantum::ops::parametric::double_list_t; - using param_list_t = mindquantum::ops::parametric::param_list_t; - using self_t = ParametricAtom; - using kinds_t = std::tuple; - - explicit ParametricAtom(AtomStorage& /* storage */) { - // NB: TrivialAtom has no dependent atoms to insert into the storage - } - - //! Return the name of this decomposition atom - MQ_NODISCARD static constexpr std::string_view name() noexcept { - return op_t::kind(); - } - - //! Return the number of target qubits this decomposition atom is constrained on - MQ_NODISCARD static constexpr auto num_targets() noexcept { - return num_targets_; - } - - //! Return the number of control qubits this decomposition atom is constrained on - MQ_NODISCARD static constexpr auto num_controls() noexcept { - return num_controls_; - } - - //! Return the number of parameters of this decomposition atom - MQ_NODISCARD static constexpr auto num_params() noexcept { - return num_param_t{op_t::num_params}; - } - - //! Helper function to create an instance of this atom - /*! - * \param storage Atom storage within which this decomposition will live in - */ - MQ_NODISCARD static auto create(AtomStorage& storage) noexcept { - return self_t{storage}; - } - - // --------------------------------------------------------------------- - - //! Test whether this atom is applicable to a particular instruction - /*! - * \param inst An instruction - * \return True if the atom can be applied, false otherwise - */ - MQ_NODISCARD bool is_applicable(const instruction_t& inst) const noexcept; - - //! Apply the atom (ie. the decomposition it represents) to a quantum circuit - /*! - * \param circuit A quantum circuit to apply the decomposition atom to - * \param op A quantum operation to decompose - * \param qubits A list of qubits to apply the decomposition atom - * \param param Some parameters to apply the decomposition atom with - * \param cbits A list of classical bit the decomposition applies to - * - * \note Currently the \c cbits parameter is not used at all! It is here to make the API futureproof. - */ - void apply(circuit_t& circuit, const operator_t& op, const qubits_t& qubits, const cbits_t& cbits) noexcept; -}; - -template -using ParametricSimpleAtom = ParametricAtom, num_controls_>; -} // namespace mindquantum::decompositions - -#include "parametric_atom.tpp" - -#endif /* PARAMETRIC_ATOM_HPP */ diff --git a/ccsrc/include/experimental/decompositions/parametric_atom.tpp b/ccsrc/include/experimental/decompositions/parametric_atom.tpp deleted file mode 100644 index 441b9e555..000000000 --- a/ccsrc/include/experimental/decompositions/parametric_atom.tpp +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright 2021 -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef PARAMETRIC_ATOM_TPP -#define PARAMETRIC_ATOM_TPP - -#include "experimental/decompositions/config.hpp" -#include "experimental/ops/parametric/substitutions.hpp" - -#ifndef PARAMETRIC_ATOM_HPP -# error This file must only be included by parametric_atom.hpp! -#endif // PARAMETRIC_ATOM_HPP - -// NB: This is mainly for syntax checkers and completion helpers as this file -// is only intended to be included directly by parametric_atom.hpp -#include "experimental/decompositions/parametric_atom.hpp" - -namespace mindquantum::decompositions { -template -bool ParametricAtom::is_applicable(const instruction_t& inst) const noexcept { - return ((op_t::kind() == inst.kind() || op_t::non_param_type::kind() == inst.kind()) // Technically not required? - && op_t::num_params == inst.num_parameters() - && ((num_targets_ == any_target) || num_targets_ == inst.num_targets()) - && (num_controls_ == any_control || num_controls_ == inst.num_controls())); -} - -// ========================================================================= - -template -void ParametricAtom::apply(circuit_t& circuit, const operator_t& op, - const qubits_t& qubits, const cbits_t& cbits) noexcept { - circuit.apply_operator(op, qubits, cbits); -} -} // namespace mindquantum::decompositions - -#endif /* PARAMETRIC_ATOM_TPP */ diff --git a/ccsrc/include/experimental/decompositions/rules/cnot2cz.hpp b/ccsrc/include/experimental/decompositions/rules/cnot2cz.hpp deleted file mode 100644 index ac8ba891b..000000000 --- a/ccsrc/include/experimental/decompositions/rules/cnot2cz.hpp +++ /dev/null @@ -1,45 +0,0 @@ -// Copyright 2022 -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef DECOMPOSITION_RULE_CNOT2CZ_HPP -#define DECOMPOSITION_RULE_CNOT2CZ_HPP - -#include - -#include "experimental/decompositions/gate_decomposition_rule.hpp" -#include "experimental/decompositions/rules/config.hpp" -#include "experimental/ops/gates.hpp" - -namespace mindquantum::decompositions::rules { -class CNOT2CZ - : public GateDecompositionRule, SINGLE_TGT_SINGLE_CTRL, ops::H, atoms::C> { - public: - static_assert(self_t::num_controls_for_decomp == 1); - - using base_t::base_t; - - static constexpr auto name() noexcept { - return "CNOT2CZ"sv; - } - - void apply_impl(circuit_t& circuit, const operator_t& /* op */, const qubits_t& qubits, - const cbits_t& /* unused */) { - atom()->apply(circuit, ops::H{}, {qubits[1]}); - atom>()->apply(circuit, ops::Z{}, {qubits[0], qubits[1]}); - atom()->apply(circuit, ops::H{}, {qubits[1]}); - } -}; -} // namespace mindquantum::decompositions::rules - -#endif /* DECOMPOSITION_RULE_CNOT2CZ_HPP */ diff --git a/ccsrc/include/experimental/decompositions/rules/cnot2rxx.hpp b/ccsrc/include/experimental/decompositions/rules/cnot2rxx.hpp deleted file mode 100644 index e8eae4465..000000000 --- a/ccsrc/include/experimental/decompositions/rules/cnot2rxx.hpp +++ /dev/null @@ -1,85 +0,0 @@ -// Copyright 2022 -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef DECOMPOSITION_RULE_CNOT2RXX_HPP -#define DECOMPOSITION_RULE_CNOT2RXX_HPP - -#include - -#include "experimental/decompositions/gate_decomposition_rule.hpp" -#include "experimental/decompositions/rules/config.hpp" -#include "experimental/ops/gates.hpp" -#include "experimental/ops/parametric/angle_gates.hpp" - -namespace mindquantum::decompositions::rules { -class CNOT2Rxx - : public GateDecompositionRule, SINGLE_TGT_SINGLE_CTRL, ops::parametric::Rx, - ops::parametric::Ry, ops::parametric::Ph, atoms::C> { - public: - static_assert(self_t::num_controls_for_decomp == 1); - - using base_t::base_t; - - explicit CNOT2Rxx(AtomStorage& storage) : base_t{storage}, use_positive_decomp_{false} { - } - - static constexpr auto name() noexcept { - return "CNOT2Rxx"sv; - } - - void apply_positive_decomp(circuit_t& circuit, const qubits_t& qubits) { - using ops::parametric::Ph; - using ops::parametric::Rx; - using ops::parametric::Rxx; - using ops::parametric::Ry; - - atom()->apply(circuit, ops::Ry{-PI_VAL_2}, {qubits[0]}); - atom()->apply(circuit, ops::Ph{PI_VAL_4}, {qubits[0]}); - atom()->apply(circuit, ops::Rx{-PI_VAL_2}, {qubits[0]}); - atom()->apply(circuit, ops::Rx{PI_VAL_2}, {qubits[1]}); - // NB: pi_half -> pi_quarter compared to ProjectQ because of Tweedledum gate definition - atom>()->apply(circuit, ops::Rxx{PI_VAL_4}, qubits); - atom()->apply(circuit, ops::Ry{PI_VAL_2}, {qubits[0]}); - } - - void apply_negative_decomp(circuit_t& circuit, const qubits_t& qubits) { - using ops::parametric::Ph; - using ops::parametric::Rx; - using ops::parametric::Rxx; - using ops::parametric::Ry; - - atom()->apply(circuit, ops::Ry{PI_VAL_2}, {qubits[0]}); - atom()->apply(circuit, ops::Ph{PI_VAL_4 * 7.}, {qubits[0]}); - atom()->apply(circuit, ops::Rx{-PI_VAL_2}, {qubits[0]}); - atom()->apply(circuit, ops::Rx{-PI_VAL_2}, {qubits[1]}); - // NB: pi_half -> pi_quarter compared to ProjectQ because of Tweedledum gate definition - atom>()->apply(circuit, ops::Rxx{PI_VAL_4}, qubits); - atom()->apply(circuit, ops::Ry{-PI_VAL_2}, {qubits[0]}); - } - - void apply_impl(circuit_t& circuit, const operator_t& /* op */, const qubits_t& qubits, - const cbits_t& /* unused */) { - if (use_positive_decomp_) { - apply_positive_decomp(circuit, qubits); - } else { - apply_negative_decomp(circuit, qubits); - } - use_positive_decomp_ ^= true; - } - - private: - bool use_positive_decomp_; -}; -} // namespace mindquantum::decompositions::rules -#endif /* DECOMPOSITION_RULE_CNOT2RXX_HPP */ diff --git a/ccsrc/include/experimental/decompositions/rules/cnu2toffoliandcu.hpp b/ccsrc/include/experimental/decompositions/rules/cnu2toffoliandcu.hpp deleted file mode 100644 index e8d097227..000000000 --- a/ccsrc/include/experimental/decompositions/rules/cnu2toffoliandcu.hpp +++ /dev/null @@ -1,90 +0,0 @@ -// Copyright 2022 -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef DECOMPOSITION_RULE_CNU2TOFFOLIANDCU_HPP -#define DECOMPOSITION_RULE_CNU2TOFFOLIANDCU_HPP - -#include -#include - -#include "experimental/core/compute.hpp" -#include "experimental/core/control.hpp" -#include "experimental/decompositions/non_gate_decomposition_rule.hpp" -#include "experimental/decompositions/rules/config.hpp" -#include "experimental/ops/gates.hpp" -#include "experimental/ops/parametric/angle_gates.hpp" - -namespace mindquantum::decompositions::rules { -class CNu2ToffoliAndCu : public decompositions::NonGateDecompositionRule> { - public: - using base_t::base_t; - - static constexpr auto name() noexcept { - return "CNu2ToffoliAndCu"sv; - } - - MQ_NODISCARD static bool is_applicable(const decompositions::instruction_t& inst) { - return inst.num_controls() > 2 || (inst.num_controls() == 2 && inst.kind() != ops::X::kind()); - } - - void apply_impl(circuit_t& circuit, const instruction_t& inst, const qubits_t& qubits) { - const auto& kind = inst.kind(); - auto n_controls = inst.num_controls(); - - qubits_t controls; - std::copy(begin(qubits), begin(qubits) + n_controls, std::back_inserter(controls)); - - qubits_t targets; - std::copy(begin(qubits) + n_controls, end(qubits), std::back_inserter(targets)); - - const auto is_x_larger_than_toffoli = kind == ops::X::kind() && n_controls > 2; - if (is_x_larger_than_toffoli) { - --n_controls; - } - - qubits_t ancillae; - for (auto i(0UL); i < n_controls - 1; ++i) { - ancillae.emplace_back(circuit.create_qubit()); - } - - MQ_WITH_COMPUTE(circuit, compute) { - atom>()->apply(compute, ops::X{}, {controls[0], controls[1], ancillae[0]}); - for (auto ctrl_idx(2UL); ctrl_idx < n_controls; ++ctrl_idx) { - atom>()->apply( - compute, ops::X{}, {controls[ctrl_idx], ancillae[ctrl_idx - 2], ancillae[ctrl_idx - 1]}); - } - } - MQ_WITH_COMPUTE_END - - qubits_t ctrls{ancillae.back()}; - - if (is_x_larger_than_toffoli) { - ctrls.emplace_back(controls.back()); - } - - MQ_WITH_CONTROL(circuit, controlled, ctrls) { - const auto new_inst = instruction_t{inst, targets, {}}; - if (auto* atom{storage().get_atom_for(new_inst)}; atom) { - atom->apply(circuit, new_inst); - } else { - controlled.apply_operator(new_inst); - } - } - - // Automatic uncompute - } -}; -} // namespace mindquantum::decompositions::rules - -#endif /* DECOMPOSITION_RULE_CNU2TOFFOLIANDCU_HPP */ diff --git a/ccsrc/include/experimental/decompositions/rules/config.hpp b/ccsrc/include/experimental/decompositions/rules/config.hpp deleted file mode 100644 index 478225495..000000000 --- a/ccsrc/include/experimental/decompositions/rules/config.hpp +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright 2022 -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef DECOPOSITION_RULES_CONFIG_HPP -#define DECOPOSITION_RULES_CONFIG_HPP - -#if __has_include() && __cplusplus > 201703L -# include -#endif // __has_include() && C++20+ -#include -#include - -#include "experimental/decompositions/atom_meta.hpp" -#include "experimental/decompositions/config.hpp" - -namespace mindquantum::decompositions::rules { -using namespace std::literals::string_view_literals; // NOLINT(build/namespaces_literals) - -#if __has_include() && __cplusplus > 201703L -static constexpr auto PI_VAL = std::numbers::pi; -#else -static constexpr auto PI_VAL = 3.141592653589793; -#endif // __has_include() && C++20 -static constexpr auto PI_VAL_2 = PI_VAL / 2.; -static constexpr auto PI_VAL_4 = PI_VAL / 4.; -} // namespace mindquantum::decompositions::rules - -#endif /* DECOPOSITION_RULES_CONFIG_HPP */ diff --git a/ccsrc/include/experimental/decompositions/rules/crz2cxandrz.hpp b/ccsrc/include/experimental/decompositions/rules/crz2cxandrz.hpp deleted file mode 100644 index ddd548e17..000000000 --- a/ccsrc/include/experimental/decompositions/rules/crz2cxandrz.hpp +++ /dev/null @@ -1,92 +0,0 @@ -// Copyright 2022 -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef DECOMPOSITION_RULE_CRZ2CXANDRZ_HPP -#define DECOMPOSITION_RULE_CRZ2CXANDRZ_HPP - -#include - -#include -#include - -#include "experimental/decompositions/non_gate_decomposition_rule.hpp" -#include "experimental/decompositions/rules/config.hpp" -#include "experimental/ops/gates.hpp" -#include "experimental/ops/parametric/angle_gates.hpp" -#include "experimental/ops/parametric/config.hpp" -#include "experimental/ops/parametric/register_gate_type.hpp" - -namespace mindquantum::decompositions::rules { -class CRZ2CXAndRz : public decompositions::NonGateDecompositionRule { - public: - using base_t::base_t; - - static constexpr auto name() noexcept { - return "CRZ2CXAndRz"sv; - } - - MQ_NODISCARD static bool is_applicable(const instruction_t& inst) { - return inst.is_one() && inst.num_controls() > 0; - } - - void apply_impl(circuit_t& circuit, const instruction_t& inst) { - const auto& kind = inst.kind(); - const auto& qubits = inst.qubits(); - auto n_controls = inst.num_controls(); - - qubits_t cnot_qubits; - std::copy(begin(qubits), begin(qubits) + n_controls, std::back_inserter(cnot_qubits)); - cnot_qubits.emplace_back(inst.target()); - - qubits_t targets{inst.target()}; - - std::visit( - [this, &circuit, &targets, &cnot_qubits](const auto& param) { - using ops::parametric::param_list_t; - using param_t = std::remove_cvref_t; - if constexpr (std::is_same_v) { - atom()->apply(circuit, ops::Rz{0.5 * param}, targets); - } else if constexpr (std::is_same_v) { - if (std::size(param) == 1) { - atom()->apply( - circuit, ops::parametric::Rz{SymEngine::mul(param[0], SymEngine::number(0.5))}.eval_smart(), - targets); - } - } else { - invalid_op_(circuit, targets, param); - } - - atom()->apply(circuit, ops::X{}, cnot_qubits); - - if constexpr (std::is_same_v) { - atom()->apply(circuit, ops::Rz{-0.5 * param}, targets); - } else if constexpr (std::is_same_v) { - if (std::size(param) == 1) { - atom()->apply( - circuit, - ops::parametric::Rz{SymEngine::mul(param[0], SymEngine::number(-0.5))}.eval_smart(), - targets); - } - } else { - invalid_op_(circuit, targets, param); - } - - atom()->apply(circuit, ops::X{}, cnot_qubits); - }, - ops::parametric::get_param(inst)); - } -}; -} // namespace mindquantum::decompositions::rules - -#endif /* DECOMPOSITION_RULE_CRZ2CXANDRZ_HPP */ diff --git a/ccsrc/include/experimental/decompositions/rules/entangle.hpp b/ccsrc/include/experimental/decompositions/rules/entangle.hpp deleted file mode 100644 index caec5a8d7..000000000 --- a/ccsrc/include/experimental/decompositions/rules/entangle.hpp +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright 2022 -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef DECOMPOSITION_RULE_ENTANGLE_HPP -#define DECOMPOSITION_RULE_ENTANGLE_HPP - -#include -#include - -#include "experimental/decompositions/gate_decomposition_rule.hpp" -#include "experimental/decompositions/rules/config.hpp" -#include "experimental/ops/gates.hpp" - -namespace mindquantum::decompositions::rules { -class Entangle2HAndCNOT - : public GateDecompositionRule, ANY_TGT_NO_CTRL, ops::H, - atoms::C> { - public: - static_assert(self_t::num_controls_for_decomp == 0); - - using base_t::base_t; - - static constexpr auto name() noexcept { - return "Entangle2HAndCNOT"sv; - } - - void apply_impl(circuit_t& circuit, const decompositions::operator_t& /* op */, - const decompositions::qubits_t& qubits, const decompositions::cbits_t& /* unused */) { - atom()->apply(circuit, ops::H{}, {qubits[0]}); - - auto tgt{qubits.front()}; - - std::for_each(begin(qubits) + 1, end(qubits), [&circuit, &tgt, this](const qubit_t& qubit) { - atom>()->apply(circuit, ops::X{}, {tgt, qubit}); - }); - } -}; -} // namespace mindquantum::decompositions::rules -#endif /* DECOMPOSITION_RULE_ENTANGLE_HPP */ diff --git a/ccsrc/include/experimental/decompositions/rules/h2rx.hpp b/ccsrc/include/experimental/decompositions/rules/h2rx.hpp deleted file mode 100644 index 603f0cef1..000000000 --- a/ccsrc/include/experimental/decompositions/rules/h2rx.hpp +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright 2022 -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef DECOMPOSITION_RULE_H2RX_HPP -#define DECOMPOSITION_RULE_H2RX_HPP - -#include - -#include "experimental/decompositions/gate_decomposition_rule.hpp" -#include "experimental/decompositions/rules/config.hpp" -#include "experimental/ops/gates.hpp" -#include "experimental/ops/parametric/angle_gates.hpp" - -namespace mindquantum::decompositions::rules { -class H2Rx - : public GateDecompositionRule, SINGLE_TGT_NO_CTRL, ops::parametric::Rx, - ops::parametric::Ph, ops::parametric::Ry> { - public: - static_assert(self_t::num_controls_for_decomp == 0UL); - - using base_t::base_t; - - static constexpr auto name() noexcept { - return "H2Rx"sv; - } - - void apply_impl(circuit_t& circuit, const operator_t& /* op */, const qubits_t& qubits, - const cbits_t& /* unused */) { - assert(std::size(qubits) == 1); - atom()->apply(circuit, ops::Rx{PI_VAL}, qubits); - atom()->apply(circuit, ops::Ph{PI_VAL_2}, qubits); - atom()->apply(circuit, ops::Ry{-PI_VAL_2}, qubits); - } -}; -} // namespace mindquantum::decompositions::rules - -#endif /* DECOMPOSITION_RULE_H2RX_HPP */ diff --git a/ccsrc/include/experimental/decompositions/rules/no_control_ph.hpp b/ccsrc/include/experimental/decompositions/rules/no_control_ph.hpp deleted file mode 100644 index ede6bfccc..000000000 --- a/ccsrc/include/experimental/decompositions/rules/no_control_ph.hpp +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright 2022 -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef DECOMPOSITION_RULE_NO_CONTROL_PH -#define DECOMPOSITION_RULE_NO_CONTROL_PH - -#include - -#include "experimental/core/config.hpp" -#include "experimental/decompositions/non_gate_decomposition_rule.hpp" -#include "experimental/decompositions/rules/config.hpp" -#include "experimental/ops/gates.hpp" -#include "experimental/ops/parametric/angle_gates.hpp" - -namespace mindquantum::decompositions::rules { -class RemovePhNoCtrl : public decompositions::NonGateDecompositionRule { - public: - using base_t::base_t; - - static constexpr auto name() noexcept { - return "CNOT2CZ"sv; - } - - MQ_NODISCARD static bool is_applicable(const instruction_t& inst) { - return inst.is_one() && inst.num_controls() == 0; - } - - void apply_impl(circuit_t& /* circuit */, const instruction_t& /* inst */) { - } -}; -} // namespace mindquantum::decompositions::rules -#endif /* DECOMPOSITION_RULE_NO_CONTROL_PH */ diff --git a/ccsrc/include/experimental/decompositions/rules/ph2r.hpp b/ccsrc/include/experimental/decompositions/rules/ph2r.hpp deleted file mode 100644 index c658d34e0..000000000 --- a/ccsrc/include/experimental/decompositions/rules/ph2r.hpp +++ /dev/null @@ -1,60 +0,0 @@ -// Copyright 2022 -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef DECOMPOSITION_RULE_PH2R_HPP -#define DECOMPOSITION_RULE_PH2R_HPP - -#include - -#include "experimental/decompositions/gate_decomposition_rule.hpp" -#include "experimental/decompositions/rules/config.hpp" -#include "experimental/ops/gates.hpp" -#include "experimental/ops/parametric/angle_gates.hpp" - -namespace mindquantum::decompositions::rules { -class Ph2R - : public GateDecompositionRule, SINGLE_TGT_PARAM_SINGLE_CTRL, - ops::parametric::P> { - public: - static_assert(self_t::num_controls_for_decomp == 1); - - using base_t::base_t; - - static constexpr auto name() noexcept { - return "Ph2R"sv; - } - - void apply_impl(circuit_t& circuit, const operator_t& op, const qubits_t& qubits, const cbits_t& /* unused */) { - std::visit( - [this, &circuit, &qubits](const auto& param) { - using param_t = std::remove_cvref_t; - if constexpr (std::is_same_v) { - atom()->apply(circuit, ops::P{param}, {qubits[0]}); - return; - } else if constexpr (std::is_same_v) { - if (std::size(param) == 1) { - // TODO(dnguyen): This (.eval_smart()) should be taken care of by the apply() method... - atom()->apply(circuit, ops::parametric::P{param[0]}.eval_smart(), - {qubits[0]}); - return; - } - } - invalid_op_(circuit, qubits, param); - }, - ops::parametric::get_param(op)); - } -}; -} // namespace mindquantum::decompositions::rules - -#endif /* DECOMPOSITION_RULE_PH2R_HPP */ diff --git a/ccsrc/include/experimental/decompositions/rules/qft2crandhadamard.hpp b/ccsrc/include/experimental/decompositions/rules/qft2crandhadamard.hpp deleted file mode 100644 index a2d5dabad..000000000 --- a/ccsrc/include/experimental/decompositions/rules/qft2crandhadamard.hpp +++ /dev/null @@ -1,53 +0,0 @@ -// Copyright 2022 -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef DECOMPOSITION_RULE_QFT2CRANDHADAMARD_HPP -#define DECOMPOSITION_RULE_QFT2CRANDHADAMARD_HPP - -#include - -#include "experimental/decompositions/gate_decomposition_rule.hpp" -#include "experimental/decompositions/rules/config.hpp" -#include "experimental/ops/gates.hpp" -#include "experimental/ops/parametric/angle_gates.hpp" - -namespace mindquantum::decompositions::rules { -class QFT2CrAndHadamard - : public GateDecompositionRule, ANY_TGT_NO_CTRL, ops::H, atoms::C> { - public: - static_assert(self_t::num_controls_for_decomp == 0); - - using base_t::base_t; - - static constexpr auto name() noexcept { - return "QFT2CrAndHadamard"sv; - } - - void apply_impl(circuit_t& circuit, const operator_t& /* op */, const qubits_t& qubits, - const cbits_t& /* unused */) { - auto last = std::size(qubits) - 1; - - for (std::size_t i(0); i < std::size(qubits); i++) { - atom()->apply(circuit, ops::H{}, {qubits[last - i]}); - - for (std::size_t j = 0; j < std::size(qubits) - 1 - i; ++j) { - atom>()->apply(circuit, ops::P{1. / static_cast((1UL << (1 + j)))}, - {qubits[last - (j + i + 1)], qubits[last - i]}); - } - } - } -}; -} // namespace mindquantum::decompositions::rules - -#endif /* DECOMPOSITION_RULE_QFT2CRANDHADAMARD_HPP */ diff --git a/ccsrc/include/experimental/decompositions/rules/r2rzandph.hpp b/ccsrc/include/experimental/decompositions/rules/r2rzandph.hpp deleted file mode 100644 index 3a02d19fa..000000000 --- a/ccsrc/include/experimental/decompositions/rules/r2rzandph.hpp +++ /dev/null @@ -1,64 +0,0 @@ -// Copyright 2022 -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef DECOMPOSITION_RULE_R2RZANDPH_HPP -#define DECOMPOSITION_RULE_R2RZANDPH_HPP -#include - -#include "experimental/decompositions/gate_decomposition_rule.hpp" -#include "experimental/decompositions/rules/config.hpp" -#include "experimental/ops/gates.hpp" -#include "experimental/ops/parametric/angle_gates.hpp" -#include "experimental/ops/parametric/register_gate_type.hpp" - -namespace mindquantum::decompositions::rules { -class R2RzAndPh - : public GateDecompositionRule, SINGLE_TGT_PARAM_ANY_CTRL, - ops::parametric::Rz, ops::parametric::Ph> { - public: - static_assert(self_t::num_controls_for_decomp == 0); - - using base_t::base_t; - - static constexpr auto name() noexcept { - return "R2RzAndPh"sv; - } - - void apply_impl(circuit_t& circuit, const operator_t& op, const qubits_t& qubits, const cbits_t& /* unused */) { - std::visit( - [this, &circuit, &qubits](const auto& param) { - using ops::parametric::param_list_t; - using param_t = std::remove_cvref_t; - - if constexpr (std::is_same_v) { - atom()->apply(circuit, ops::Ph{0.5 * param}, qubits); - atom()->apply(circuit, ops::Rz{param}, qubits); - return; - } else if constexpr (std::is_same_v) { - if (std::size(param) == 1) { - atom()->apply( - circuit, ops::parametric::Ph{SymEngine::mul(param[0], SymEngine::number(0.5))}.eval_smart(), - qubits); - atom()->apply(circuit, ops::parametric::Rz{param[0]}.eval_smart(), qubits); - return; - } - } - invalid_op_(circuit, qubits, param); - }, - ops::parametric::get_param(op)); - } -}; -} // namespace mindquantum::decompositions::rules - -#endif /* DECOMPOSITION_RULE_R2RZANDPH_HPP */ diff --git a/ccsrc/include/experimental/decompositions/rules/rx2rz.hpp b/ccsrc/include/experimental/decompositions/rules/rx2rz.hpp deleted file mode 100644 index 0d3924a5e..000000000 --- a/ccsrc/include/experimental/decompositions/rules/rx2rz.hpp +++ /dev/null @@ -1,63 +0,0 @@ -// Copyright 2022 -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef DECOMPOSITION_RULE_RX2RZ_HPP -#define DECOMPOSITION_RULE_RX2RZ_HPP - -#include - -#include "experimental/decompositions/gate_decomposition_rule.hpp" -#include "experimental/decompositions/rules/config.hpp" -#include "experimental/ops/gates.hpp" -#include "experimental/ops/parametric/angle_gates.hpp" - -namespace mindquantum::decompositions::rules { -class Rx2Rz - : public GateDecompositionRule, SINGLE_TGT_PARAM_ANY_CTRL, ops::H, - ops::parametric::Rz> { - public: - static_assert(self_t::num_controls_for_decomp == 0); - - using base_t::base_t; - - static constexpr auto name() noexcept { - return "Rx2Rz"sv; - } - - void apply_impl(circuit_t& circuit, const operator_t& op, const qubits_t& qubits, const cbits_t& /* unused */) { - atom()->apply(circuit, ops::H{}, qubits); - std::visit( - [this, &circuit, &qubits](const auto& param) { - using ops::parametric::param_list_t; - using param_t = std::remove_cvref_t; - - if constexpr (std::is_same_v) { - atom()->apply(circuit, ops::Rz{param}, qubits); - return; - } else if constexpr (std::is_same_v) { - if (std::size(param) == 1) { - atom()->apply(circuit, ops::parametric::Rz{param[0]}.eval_smart(), qubits); - return; - } - } - invalid_op_(circuit, qubits, param); - }, - ops::parametric::get_param(op)); - - atom()->apply(circuit, ops::H{}, qubits); - } -}; -} // namespace mindquantum::decompositions::rules - -#endif /* DECOMPOSITION_RULE_RX2RZ_HPP */ diff --git a/ccsrc/include/experimental/decompositions/rules/ry2rz.hpp b/ccsrc/include/experimental/decompositions/rules/ry2rz.hpp deleted file mode 100644 index d69ac48e9..000000000 --- a/ccsrc/include/experimental/decompositions/rules/ry2rz.hpp +++ /dev/null @@ -1,66 +0,0 @@ -// Copyright 2022 -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef DECOMPOSITION_RULE_RY2RZ_HPP -#define DECOMPOSITION_RULE_RY2RZ_HPP -#include - -#include -#include -#include - -#include "experimental/decompositions/gate_decomposition_rule.hpp" -#include "experimental/decompositions/rules/config.hpp" -#include "experimental/ops/gates.hpp" -#include "experimental/ops/parametric/angle_gates.hpp" -#include "experimental/ops/parametric/register_gate_type.hpp" - -namespace mindquantum::decompositions::rules { -class Ry2Rz - : public GateDecompositionRule, SINGLE_TGT_PARAM_ANY_CTRL, - ops::parametric::Rx, ops::parametric::Rz> { - public: - static_assert(self_t::num_controls_for_decomp == 0); - - using base_t::base_t; - - static constexpr auto name() noexcept { - return "Ry2Rz"sv; - } - - void apply_impl(circuit_t& circuit, const operator_t& op, const qubits_t& qubits, const cbits_t& /* unused */) { - atom()->apply(circuit, ops::Rx{PI_VAL_2}, qubits); - std::visit( - [this, &circuit, &qubits](const auto& param) { - using ops::parametric::param_list_t; - using param_t = std::remove_cvref_t; - - if constexpr (std::is_same_v) { - atom()->apply(circuit, ops::Rz{param}, qubits); - return; - } else if constexpr (std::is_same_v) { - if (std::size(param) == 1) { - atom()->apply(circuit, ops::parametric::Rz{param[0]}.eval_smart(), qubits); - return; - } - } - invalid_op_(circuit, qubits, param); - }, - ops::parametric::get_param(op)); - atom()->apply(circuit, ops::Rx{-PI_VAL_2}, qubits); - } -}; -} // namespace mindquantum::decompositions::rules - -#endif /* DECOMPOSITION_RULE_RY2RZ_HPP */ diff --git a/ccsrc/include/experimental/decompositions/rules/rz2rxandry.hpp b/ccsrc/include/experimental/decompositions/rules/rz2rxandry.hpp deleted file mode 100644 index 31f4dda04..000000000 --- a/ccsrc/include/experimental/decompositions/rules/rz2rxandry.hpp +++ /dev/null @@ -1,109 +0,0 @@ -// Copyright 2022 -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef DECOMPOSITION_RULE_RZ2RXANDRY_HPP -#define DECOMPOSITION_RULE_RZ2RXANDRY_HPP - -#include - -#include -#include -#include -#include - -#include "experimental/decompositions/gate_decomposition_rule.hpp" -#include "experimental/decompositions/rules/config.hpp" -#include "experimental/ops/gates.hpp" -#include "experimental/ops/parametric/angle_gates.hpp" -#include "experimental/ops/parametric/register_gate_type.hpp" - -namespace mindquantum::decompositions::rules { -class Rz2RxAndRy - : public GateDecompositionRule, SINGLE_TGT_PARAM_ANY_CTRL, - ops::parametric::Rx, ops::parametric::Ry> { - public: - static_assert(self_t::num_controls_for_decomp == 0); - - using base_t::base_t; - - explicit Rz2RxAndRy(AtomStorage& storage) : base_t{storage}, use_positive_decomp_{false} { - } - - static constexpr auto name() noexcept { - return "Rz2RxAndRy"sv; - } - - void apply_positive_decomp(circuit_t& circuit, const qubits_t& qubits, const gate_param_t& param) { - atom()->apply(circuit, ops::Ry{-PI_VAL_2}, qubits); - - std::visit( - [this, &circuit, &qubits](const auto& param) { - using ops::parametric::param_list_t; - using param_t = std::remove_cvref_t; - - if constexpr (std::is_same_v) { - atom()->apply(circuit, ops::Rx{-param}, qubits); - return; - } else if constexpr (std::is_same_v) { - if (std::size(param) == 1) { - atom()->apply( - circuit, ops::parametric::Rx{SymEngine::neg(param[0])}.eval_smart(), qubits); - return; - } - } - invalid_op_(circuit, qubits, param); - }, - param); - - atom()->apply(circuit, ops::Ry{PI_VAL_2}, qubits); - } - - void apply_negative_decomp(circuit_t& circuit, const qubits_t& qubits, const gate_param_t& param) { - atom()->apply(circuit, ops::Ry{PI_VAL_2}, qubits); - std::visit( - [this, &circuit, &qubits](const auto& param) { - using ops::parametric::param_list_t; - using param_t = std::remove_cvref_t; - - if constexpr (std::is_same_v) { - atom()->apply(circuit, ops::Rx{param}, qubits); - return; - } else if constexpr (std::is_same_v) { - if (std::size(param) == 1) { - atom()->apply(circuit, ops::parametric::Rx{param[0]}.eval_smart(), qubits); - return; - } - } - invalid_op_(circuit, qubits, param); - }, - param); - - atom()->apply(circuit, ops::Ry{-PI_VAL_2}, qubits); - } - - void apply_impl(circuit_t& circuit, const operator_t& op, const qubits_t& qubits, const cbits_t& /* unused */) { - if (use_positive_decomp_) { - apply_positive_decomp(circuit, qubits, ops::parametric::get_param(op)); - } else { - apply_negative_decomp(circuit, qubits, ops::parametric::get_param(op)); - } - use_positive_decomp_ ^= 1U; - } - - private: - bool use_positive_decomp_; -}; -} // namespace mindquantum::decompositions::rules - -#endif /* DECOMPOSITION_RULE_RZ2RXANDRY_HPP */ diff --git a/ccsrc/include/experimental/decompositions/rules/sqrtswap2cnotandsqrtx.hpp b/ccsrc/include/experimental/decompositions/rules/sqrtswap2cnotandsqrtx.hpp deleted file mode 100644 index 07f8b2b78..000000000 --- a/ccsrc/include/experimental/decompositions/rules/sqrtswap2cnotandsqrtx.hpp +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright 2022 -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef DECOMPOSITION_RULE_SQRTSWAP2CNOTANDSQRTX_HPP -#define DECOMPOSITION_RULE_SQRTSWAP2CNOTANDSQRTX_HPP - -#include - -#include "experimental/decompositions/gate_decomposition_rule.hpp" -#include "experimental/decompositions/rules/config.hpp" -#include "experimental/ops/gates.hpp" -#include "experimental/ops/gates/sqrtswap.hpp" - -namespace mindquantum::decompositions::rules { -class SqrtSwap2CNOTAndSqrtX - : public GateDecompositionRule, DUAL_TGT_ANY_CTRL, ops::Sx, - atoms::C> { - public: - static_assert(self_t::num_controls_for_decomp == 0); - - using base_t::base_t; - - static constexpr auto name() noexcept { - return "SqrtSwap2CNOTAndSqrtX"sv; - } - - void apply_impl(circuit_t& circuit, const operator_t& /* op */, const qubits_t& qubits, - const cbits_t& /* unused */) { - atom>()->apply(circuit, ops::X{}, {qubits[0], qubits[1]}); - atom()->apply(circuit, ops::Sx{}, {qubits[1], qubits[0]}); - atom>()->apply(circuit, ops::X{}, {qubits[0], qubits[1]}); - } -}; -} // namespace mindquantum::decompositions::rules - -#endif /* DECOMPOSITION_RULE_SQRTSWAP2CNOTANDSQRTX_HPP */ diff --git a/ccsrc/include/experimental/decompositions/rules/swap2cnot.hpp b/ccsrc/include/experimental/decompositions/rules/swap2cnot.hpp deleted file mode 100644 index dfd2575d8..000000000 --- a/ccsrc/include/experimental/decompositions/rules/swap2cnot.hpp +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright 2022 -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef DECOMPOSITION_RULE_SWAP2CNOT_HPP -#define DECOMPOSITION_RULE_SWAP2CNOT_HPP - -#include - -#include "experimental/decompositions/gate_decomposition_rule.hpp" -#include "experimental/decompositions/rules/config.hpp" -#include "experimental/ops/gates.hpp" - -namespace mindquantum::decompositions::rules { -class Swap2CNOT : public GateDecompositionRule, DUAL_TGT_ANY_CTRL, atoms::C> { - public: - static_assert(self_t::num_controls_for_decomp == 0); - - using base_t::base_t; - - static constexpr auto name() noexcept { - return "Swap2CNOT"sv; - } - - void apply_impl(circuit_t& circuit, const operator_t& /* op */, const qubits_t& qubits, - const cbits_t& /* unused */) { - atom>()->apply(circuit, ops::X{}, {qubits[0], qubits[1]}); - atom>()->apply(circuit, ops::X{}, {qubits[1], qubits[0]}); - atom>()->apply(circuit, ops::X{}, {qubits[0], qubits[1]}); - } -}; -} // namespace mindquantum::decompositions::rules - -#endif /* DECOMPOSITION_RULE_SWAP2CNOT_HPP */ diff --git a/ccsrc/include/experimental/decompositions/rules/toffoli2cnotandtgate.hpp b/ccsrc/include/experimental/decompositions/rules/toffoli2cnotandtgate.hpp deleted file mode 100644 index c5a23a7c8..000000000 --- a/ccsrc/include/experimental/decompositions/rules/toffoli2cnotandtgate.hpp +++ /dev/null @@ -1,65 +0,0 @@ -// Copyright 2022 -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef DECOMPOSITION_RULE_TOFFOLI2CNOTANDTGATE_HPP -#define DECOMPOSITION_RULE_TOFFOLI2CNOTANDTGATE_HPP - -#include - -#include - -#include "experimental/decompositions/gate_decomposition_rule.hpp" -#include "experimental/decompositions/rules/config.hpp" -#include "experimental/ops/gates.hpp" - -namespace mindquantum::decompositions::rules { -class Toffoli2CNOTAndT - : public GateDecompositionRule, SINGLE_TGT_DOUBLE_CTRL, atoms::C, - ops::H, ops::T, ops::Tdg> { - public: - static_assert(self_t::num_controls_for_decomp == 2); - - using base_t::base_t; - - static constexpr auto name() noexcept { - return "Toffoli2CNOTAndT"sv; - } - - void apply_impl(circuit_t& circuit, const operator_t& /* op */, const qubits_t& qubits, - const cbits_t& /* unused */) { - assert(std::size(qubits) == 3); - const auto& control0 = qubits[0]; - const auto& control1 = qubits[1]; - const auto& target = qubits[2]; - - atom()->apply(circuit, ops::H{}, {target}); - atom>()->apply(circuit, ops::X{}, {control0, target}); - atom()->apply(circuit, ops::T{}, {control0}); - atom()->apply(circuit, ops::Tdg{}, {target}); - atom>()->apply(circuit, ops::X{}, {control1, target}); - atom>()->apply(circuit, ops::X{}, {control1, control0}); - atom()->apply(circuit, ops::Tdg{}, {control0}); - atom()->apply(circuit, ops::T{}, {target}); - atom>()->apply(circuit, ops::X{}, {control1, control0}); - atom>()->apply(circuit, ops::X{}, {control0, target}); - atom()->apply(circuit, ops::Tdg{}, {target}); - atom>()->apply(circuit, ops::X{}, {control1, target}); - atom()->apply(circuit, ops::T{}, {target}); - atom()->apply(circuit, ops::T{}, {control1}); - atom()->apply(circuit, ops::X{}, {target}); - } -}; -} // namespace mindquantum::decompositions::rules - -#endif /* DECOMPOSITION_RULE_TOFFOLI2CNOTANDTGATE_HPP */ diff --git a/ccsrc/include/experimental/decompositions/trivial_atom.hpp b/ccsrc/include/experimental/decompositions/trivial_atom.hpp deleted file mode 100644 index 20dbc19a8..000000000 --- a/ccsrc/include/experimental/decompositions/trivial_atom.hpp +++ /dev/null @@ -1,100 +0,0 @@ -// Copyright 2021 -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef TRIVIAL_ATOM_HPP -#define TRIVIAL_ATOM_HPP - -#include -#include - -#include "experimental/core/config.hpp" -#include "experimental/core/operator_traits.hpp" -#include "experimental/decompositions/atom_storage.hpp" -#include "experimental/decompositions/config.hpp" - -namespace mindquantum::decompositions { -//! A decomposition atom representing a gate with no free-parameter -/*! - * \note This can be a parametric gate with all of its parameters fully specified - * - * \tparam operator_t Type of the gate the atom is representing - * \tparam num_controls_ Number of control qubits the gate this atom is representing has. Possible values: - * -1 for any number of control qubits, >= 0 for a specified number of control qubits. - */ -template -class TrivialAtom : public traits::controls { - public: - using self_t = TrivialAtom; - using kinds_t = std::tuple; - - explicit TrivialAtom(AtomStorage& /* storage */) { - // NB: TrivialAtom has no dependent atoms to insert into the storage - } - - //! Return the name of this decomposition atom - MQ_NODISCARD static constexpr std::string_view name() noexcept { - return op_t::kind(); - } - - //! Return the number of target qubits this decomposition atom is constrained on - MQ_NODISCARD static constexpr auto num_targets() noexcept { - return num_targets_; - } - - //! Return the number of control qubits this decomposition atom is constrained on - MQ_NODISCARD static constexpr auto num_controls() noexcept { - return num_controls_; - } - - //! Return the number of parameters of this decomposition atom - MQ_NODISCARD static constexpr auto num_params() noexcept { - return num_param_t{0UL}; - } - - //! Helper function to create an instance of this atom - /*! - * \param storage Atom storage within which this decomposition will live in - */ - MQ_NODISCARD static auto create(AtomStorage& storage) noexcept { - return self_t{storage}; - } - - // --------------------------------------------------------------------- - - //! Test whether this atom is applicable to a particular instruction - /*! - * \param inst An instruction - * \return True if the atom can be applied, false otherwise - */ - MQ_NODISCARD bool is_applicable(const instruction_t& inst) const noexcept; - - //! Apply the atom (ie. the decomposition it represents) to a quantum circuit - /*! - * \param circuit A quantum circuit to apply the decomposition atom to - * \param op A quantum operation to decompose - * \param qubits A list of qubits to apply the decomposition atom - * \param cbits A list of classical bit the decomposition applies to - * - * \note Currently the \c cbits parameter is not used at all! It is here to make the API futureproof. - */ - void apply(circuit_t& circuit, const operator_t& op, const qubits_t& qubits, const cbits_t& cbits) noexcept; -}; - -template -using TrivialSimpleAtom = TrivialAtom, num_controls_>; -} // namespace mindquantum::decompositions - -#include "trivial_atom.tpp" - -#endif /* TRIVIAL_ATOM_HPP */ diff --git a/ccsrc/include/experimental/decompositions/trivial_atom.tpp b/ccsrc/include/experimental/decompositions/trivial_atom.tpp deleted file mode 100644 index 1d63799fa..000000000 --- a/ccsrc/include/experimental/decompositions/trivial_atom.tpp +++ /dev/null @@ -1,45 +0,0 @@ -// Copyright 2021 -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef TRIVIAL_ATOM_TPP -#define TRIVIAL_ATOM_TPP - -#include "experimental/decompositions/config.hpp" - -#ifndef TRIVIAL_ATOM_HPP -# error This file must only be included by trivial_atom.hpp! -#endif // TRIVIAL_ATOM_HPP - -// NB: This is mainly for syntax checkers and completion helpers as this file -// is only intended to be included directly by trivial_atom.hpp -#include "experimental/decompositions/trivial_atom.hpp" - -namespace mindquantum::decompositions { -template -bool TrivialAtom::is_applicable(const instruction_t& inst) const noexcept { - return (op_t::kind() == inst.kind() && inst.num_parameters() == 0U - && ((num_targets_ == any_target) || num_targets_ == inst.num_targets()) - && (num_controls_ == any_control || num_controls_ == inst.num_controls())); -} - -// ========================================================================= - -template -void TrivialAtom::apply(circuit_t& circuit, const operator_t& op, - const qubits_t& qubits, const cbits_t& cbits) noexcept { - circuit.apply_operator(op, qubits, cbits); -} -} // namespace mindquantum::decompositions - -#endif /* TRIVIAL_ATOM_TPP */ diff --git a/ccsrc/include/experimental/format/CPPLINT.cfg b/ccsrc/include/experimental/format/CPPLINT.cfg deleted file mode 100644 index 79ab8fcd4..000000000 --- a/ccsrc/include/experimental/format/CPPLINT.cfg +++ /dev/null @@ -1 +0,0 @@ -filter=-runtime/references diff --git a/ccsrc/include/experimental/format/tweedledum.hpp b/ccsrc/include/experimental/format/tweedledum.hpp deleted file mode 100644 index 03bf619fe..000000000 --- a/ccsrc/include/experimental/format/tweedledum.hpp +++ /dev/null @@ -1,161 +0,0 @@ -// Copyright 2022 -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef MQ_FORMAT_TWEEDLEDUM_HPP -#define MQ_FORMAT_TWEEDLEDUM_HPP - -#include - -#include -#include -#include -#include - -#include -#include - -#include "experimental/ops/gates.hpp" -#include "experimental/ops/meta/dagger.hpp" - -// ============================================================================= - -namespace mindquantum::fmt_details { -struct formatter_base { - FMT_CONSTEXPR auto parse(::fmt::format_parse_context& ctx) -> decltype(ctx.begin()) { - return ctx.begin(); - } -}; -} // namespace mindquantum::fmt_details - -//! Custom formatter for a tweedledum::Qubit:::Polarity -template -struct fmt::formatter : mindquantum::fmt_details::formatter_base { - using type_t = tweedledum::Qubit::Polarity; - - template - auto format(const type_t& polarity, format_context_t& ctx) const -> decltype(ctx.out()) { - if (polarity == tweedledum::Qubit::positive) { - return fmt::format_to(ctx.out(), "pos"); - } - return fmt::format_to(ctx.out(), "neg"); - } -}; - -//! Custom formatter for a tweedledum::Qubit -template -struct fmt::formatter : mindquantum::fmt_details::formatter_base { - using type_t = tweedledum::Qubit; - - template - auto format(const type_t& qubit, format_context_t& ctx) const -> decltype(ctx.out()) { - return fmt::format_to(ctx.out(), "Q[{}]({})", qubit.uid(), qubit.polarity()); - } -}; - -// ----------------------------------------------------------------------------- - -//! Custom formatter for a tweedledum::Cbit:::Polarity -template -struct fmt::formatter : mindquantum::fmt_details::formatter_base { - using type_t = tweedledum::Cbit::Polarity; - - template - auto format(const type_t& polarity, format_context_t& ctx) const -> decltype(ctx.out()) { - if (polarity == tweedledum::Cbit::positive) { - return fmt::format_to(ctx.out(), "pos"); - } - return fmt::format_to(ctx.out(), "neg"); - } -}; - -//! Custom formatter for a tweedledum::Cbit -template -struct fmt::formatter : mindquantum::fmt_details::formatter_base { - using type_t = tweedledum::Cbit; - - template - auto format(const type_t& cbit, format_context_t& ctx) const -> decltype(ctx.out()) { - return fmt::format_to(ctx.out(), "C[{}]({})", cbit, cbit.polarity()); - } -}; - -// ----------------------------------------------------------------------------- - -//! Custom formatter for a tweedledum::Operator -template -struct fmt::formatter : mindquantum::fmt_details::formatter_base { - using type_t = tweedledum::Operator; - - template - auto format(const type_t& op, format_context_t& ctx) const -> decltype(ctx.out()) { - namespace ops = mindquantum::ops; - if (op.is_a()) { - fmt::format_to(ctx.out(), "Dagger({})", op.adjoint()); - } else { - fmt::format_to(ctx.out(), "{}", op); - } - if (op.is_a()) { - fmt::format_to(ctx.out(), "({})", op.cast().angle()); - } else if (op.is_a()) { - fmt::format_to(ctx.out(), "({})", op.cast().angle()); - } else if (op.is_a()) { - fmt::format_to(ctx.out(), "({})", op.cast().angle()); - } else if (op.is_a()) { - fmt::format_to(ctx.out(), "({})", op.cast().angle()); - } else if (op.is_a()) { - fmt::format_to(ctx.out(), "({})", op.cast().angle()); - } else if (op.is_a()) { - fmt::format_to(ctx.out(), "({})", op.cast().angle()); - } else if (op.is_a()) { - fmt::format_to(ctx.out(), "({})", op.cast().angle()); - } else if (op.is_a()) { - fmt::format_to(ctx.out(), "({})", op.cast().angle()); - } - return ctx.out(); - } -}; - -// ----------------------------------------------------------------------------- - -//! Custom formatter for a tweedledum::Instruction -template -struct fmt::formatter : mindquantum::fmt_details::formatter_base { - using type_t = tweedledum::Instruction; - - template - auto format(const type_t& inst, format_context_t& ctx) const -> decltype(ctx.out()) { - return fmt::format_to(ctx.out(), "{} [{}]", static_cast(inst), inst.qubits()); - } -}; - -// ----------------------------------------------------------------------------- - -//! Custom formatter for a tweedledum::Circuit -template -struct fmt::formatter : mindquantum::fmt_details::formatter_base { - using type_t = tweedledum::Circuit; - - template - auto format(const type_t& circuit, format_context_t& ctx) const -> decltype(ctx.out()) { - fmt::format_to(ctx.out(), "Circuit ({} | {})", circuit.qubits(), circuit.cbits()); - - circuit.foreach_instruction( - [&ctx](const tweedledum::Instruction& inst) { fmt::format_to(ctx.out(), "{}\n", inst); }); - return ctx.out(); - } -}; - -// ============================================================================= - -#endif /* MQ_FORMAT_TWEEDLEDUM_HPP */ diff --git a/ccsrc/include/experimental/mapping/partial_placer.hpp b/ccsrc/include/experimental/mapping/partial_placer.hpp deleted file mode 100644 index 95cdd7aaf..000000000 --- a/ccsrc/include/experimental/mapping/partial_placer.hpp +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright 2021 -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef PARTIAL_PLACER_HPP -#define PARTIAL_PLACER_HPP - -#include - -#include -#include -#include -#include - -namespace mindquantum::mapping { -class PartialPlacer { - public: - using qubit_t = tweedledum::Qubit; - using device_t = tweedledum::Device; - using placement_t = tweedledum::Placement; - - //! Constructor - PartialPlacer(const device_t& device, placement_t& placement); - - //! Execute placing algorithm - /*! - * \note This placer should only be run **before** any operations have been added to the mapped circuit. - */ - void run(const std::vector& new_qubits); - - private: - const device_t& device_; - placement_t& placement_; -}; -} // namespace mindquantum::mapping - -#endif /* PARTIAL_PLACER_HPP */ diff --git a/ccsrc/include/experimental/ops/gates.hpp b/ccsrc/include/experimental/ops/gates.hpp deleted file mode 100644 index 31171307c..000000000 --- a/ccsrc/include/experimental/ops/gates.hpp +++ /dev/null @@ -1,54 +0,0 @@ -// Copyright 2020 -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef GATES_HPP -#define GATES_HPP - -#include -#include - -#include "ops/gates/qubit_operator.hpp" - -#include "experimental/ops/gates/allocate.hpp" -#include "experimental/ops/gates/deallocate.hpp" -#include "experimental/ops/gates/entangle.hpp" -#include "experimental/ops/gates/invalid.hpp" -#include "experimental/ops/gates/measure.hpp" -#include "experimental/ops/gates/ph.hpp" -#include "experimental/ops/gates/qft.hpp" -#include "experimental/ops/gates/sqrtswap.hpp" -#include "experimental/ops/gates/time_evolution.hpp" - -namespace mindquantum::ops { -using namespace tweedledum::Op; // NOLINT(build/namespaces) -} // namespace mindquantum::ops - -namespace tweedledum { -template <> -inline constexpr uint8_t num_param_v = 1; -template <> -inline constexpr uint8_t num_param_v = 1; -template <> -inline constexpr uint8_t num_param_v = 1; -template <> -inline constexpr uint8_t num_param_v = 1; -template <> -inline constexpr uint8_t num_param_v = 1; -template <> -inline constexpr uint8_t num_param_v = 1; -template <> -inline constexpr uint8_t num_param_v = 1; -} // namespace tweedledum - -#endif /* GATES_HPP */ diff --git a/ccsrc/include/experimental/ops/gates/CPPLINT.cfg b/ccsrc/include/experimental/ops/gates/CPPLINT.cfg deleted file mode 100644 index 283ef7cc0..000000000 --- a/ccsrc/include/experimental/ops/gates/CPPLINT.cfg +++ /dev/null @@ -1 +0,0 @@ -filter=-build/include_order,-whitespace/newline,-readability/braces,-readability/nolint,-whitespace/braces,-build/namespaces_literals,-build/include,-runtime/references diff --git a/ccsrc/include/experimental/ops/gates/allocate.hpp b/ccsrc/include/experimental/ops/gates/allocate.hpp deleted file mode 100644 index a9ac855f7..000000000 --- a/ccsrc/include/experimental/ops/gates/allocate.hpp +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright 2020 -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef ALLOCATE_OP_HPP -#define ALLOCATE_OP_HPP - -#include - -namespace mindquantum::ops { -class Allocate { - public: - static constexpr std::string_view kind() { - return "projectq.allocate"; - } -}; -} // namespace mindquantum::ops - -#endif /* ALLOCATE_OP_HPP */ diff --git a/ccsrc/include/experimental/ops/gates/deallocate.hpp b/ccsrc/include/experimental/ops/gates/deallocate.hpp deleted file mode 100644 index 0f9034848..000000000 --- a/ccsrc/include/experimental/ops/gates/deallocate.hpp +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright 2020 -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef DEALLOCATE_OP_HPP -#define DEALLOCATE_OP_HPP - -#include - -namespace mindquantum::ops { -class Deallocate { - public: - static constexpr std::string_view kind() { - return "projectq.deallocate"; - } -}; -} // namespace mindquantum::ops - -#endif /* DEALLOCATE_OP_HPP */ diff --git a/ccsrc/include/experimental/ops/gates/entangle.hpp b/ccsrc/include/experimental/ops/gates/entangle.hpp deleted file mode 100644 index 4f9de9db6..000000000 --- a/ccsrc/include/experimental/ops/gates/entangle.hpp +++ /dev/null @@ -1,53 +0,0 @@ -// Copyright 2020 -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef ENTANGLE_HPP -#define ENTANGLE_HPP - -#include - -#include - -#include "experimental/ops/meta/dagger.hpp" - -namespace mindquantum::ops { -class Entangle { - public: - using non_const_num_targets = void; - - static constexpr std::string_view kind() { - return "projectq.entangle"; - } - - explicit Entangle(uint32_t num_targets) : num_targets_(num_targets) { - } - - td::Operator adjoint() const { - return DaggerOperation(*this); - } - - uint32_t num_targets() const { - return num_targets_; - } - - bool operator==(const Entangle& other) const { - return num_targets_ == other.num_targets_; - } - - private: - uint32_t num_targets_; -}; -} // namespace mindquantum::ops - -#endif /* ENTANGLE_HPP */ diff --git a/ccsrc/include/experimental/ops/gates/invalid.hpp b/ccsrc/include/experimental/ops/gates/invalid.hpp deleted file mode 100644 index 634356306..000000000 --- a/ccsrc/include/experimental/ops/gates/invalid.hpp +++ /dev/null @@ -1,41 +0,0 @@ -// Copyright 2020 -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef INVALID_OP_HPP -#define INVALID_OP_HPP - -#include -#include - -namespace mindquantum::ops { -class Invalid { - public: - static constexpr std::string_view kind() { - return "projectq.invalid"; - } - - Invalid() = default; - explicit Invalid(uint64_t num_targets) : num_targets_(num_targets) { - } - - auto num_targets() const noexcept { - return num_targets_; - } - - private: - uint32_t num_targets_ = 1; -}; -} // namespace mindquantum::ops - -#endif /* INVALID_OP_HPP */ diff --git a/ccsrc/include/experimental/ops/gates/measure.hpp b/ccsrc/include/experimental/ops/gates/measure.hpp deleted file mode 100644 index 4059d13a1..000000000 --- a/ccsrc/include/experimental/ops/gates/measure.hpp +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright 2020 -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef MEASURE_OP_HPP -#define MEASURE_OP_HPP - -#include - -namespace mindquantum::ops { -class Measure { - public: - static constexpr std::string_view kind() { - return "projectq.measure"; - } -}; -} // namespace mindquantum::ops - -#endif /* MEASURE_OP_HPP */ diff --git a/ccsrc/include/experimental/ops/gates/ph.hpp b/ccsrc/include/experimental/ops/gates/ph.hpp deleted file mode 100644 index bf24cf2e3..000000000 --- a/ccsrc/include/experimental/ops/gates/ph.hpp +++ /dev/null @@ -1,64 +0,0 @@ -// Copyright 2020 -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef PH_HPP -#define PH_HPP - -#include - -#include -#include - -namespace mindquantum::ops { -class Ph { - using UMatrix2 = tweedledum::UMatrix2; - - public: - static constexpr std::string_view kind() { - return "projectq.ph"; - } - - static constexpr auto num_params = 1UL; - - explicit Ph(double angle) : angle_(angle) { - } - - Ph adjoint() const { - return Ph(-angle_); - } - - constexpr bool is_symmetric() const { - return true; - } - - UMatrix2 const matrix() const { - using Complex = tweedledum::Complex; - Complex const a = std::exp(Complex(0., angle_)); - return (UMatrix2() << a, 0., 0., a).finished(); - } - - bool operator==(Ph const& other) const { - return angle_ == other.angle_; - } - - const auto& angle() const { - return angle_; - } - - private: - double const angle_; -}; -} // namespace mindquantum::ops - -#endif /* PH_HPP */ diff --git a/ccsrc/include/experimental/ops/gates/qft.hpp b/ccsrc/include/experimental/ops/gates/qft.hpp deleted file mode 100644 index 9e3ae88d4..000000000 --- a/ccsrc/include/experimental/ops/gates/qft.hpp +++ /dev/null @@ -1,51 +0,0 @@ -// Copyright 2020 -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef QFT_HPP -#define QFT_HPP - -#include - -#include "experimental/ops/meta/dagger.hpp" - -namespace mindquantum::ops { -class QFT { - public: - using non_const_num_targets = void; - - static constexpr std::string_view kind() { - return "projectq.qft"; - } - - explicit QFT(uint32_t num_targets) : num_targets_(num_targets) { - } - - td::Operator adjoint() const { - return DaggerOperation(*this); - } - - uint32_t num_targets() const { - return num_targets_; - } - - bool operator==(const QFT& other) const { - return num_targets_ == other.num_targets_; - } - - private: - uint32_t num_targets_; -}; -} // namespace mindquantum::ops - -#endif /* QFT_HPP */ diff --git a/ccsrc/include/experimental/ops/gates/sqrtswap.hpp b/ccsrc/include/experimental/ops/gates/sqrtswap.hpp deleted file mode 100644 index 9920e32e1..000000000 --- a/ccsrc/include/experimental/ops/gates/sqrtswap.hpp +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright 2021 -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef SQRTSWAP_HPP -#define SQRTSWAP_HPP - -#include -#include - -#include - -#include "experimental/ops/meta/dagger.hpp" - -namespace mindquantum::ops { -namespace td = tweedledum; - -// SqrtSwap operator -class SqrtSwap { - // clang-format off - constexpr static std::array mat_ = { - 1, 0, 0, 0, - 0, td::Complex(0.5, 0.5), td::Complex(0.5, -0.5), 0, - 0, td::Complex(0.5, -0.5), td::Complex(0.5, 0.5), 0, - 0, 0, 0, 1 - }; - // clang-format on - - public: - static constexpr std::string_view kind() { - return "projectq.sqrtswap"; - } - - uint32_t num_targets() const { - return 2u; - } - - td::Operator adjoint() const { - return DaggerOperation(*this); - } - - static td::UMatrix4 const matrix() { - return Eigen::Map(mat_.data()); - } -}; -} // namespace mindquantum::ops - -#endif /* SQRTSWAP_HPP */ diff --git a/ccsrc/include/experimental/ops/gates/time_evolution.hpp b/ccsrc/include/experimental/ops/gates/time_evolution.hpp deleted file mode 100644 index 0c9e5726e..000000000 --- a/ccsrc/include/experimental/ops/gates/time_evolution.hpp +++ /dev/null @@ -1,86 +0,0 @@ -// Copyright 2020 -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef TIMEEVOLUTION_OP_HPP -#define TIMEEVOLUTION_OP_HPP - -#include - -#include "ops/gates/details/std_complex_coeff_policy.hpp" -#include "ops/gates/qubit_operator.hpp" - -#include "experimental/core/config.hpp" - -namespace mindquantum::ops { -class TimeEvolution { - public: - using non_const_num_targets = void; - - static constexpr std::string_view kind() { - return "projectq.timeevolution"; - } - - using QubitOperatorCD = QubitOperator>; - - //! Constructor - /*! - * Overload required in some cases for metaprogramming with operators. - */ - TimeEvolution(uint32_t num_targets, QubitOperatorCD hamiltonian, double time) - : TimeEvolution(std::move(hamiltonian), time) { - assert(num_targets == hamiltonian.num_targets()); - } - - //! Constructor - TimeEvolution(QubitOperatorCD hamiltonian, double time) : hamiltonian_(std::move(hamiltonian)), time_(time) { - } - - MQ_NODISCARD TimeEvolution adjoint() const { - return {hamiltonian_.num_targets(), hamiltonian_, -time_}; - } - - MQ_NODISCARD uint32_t num_targets() const { - return hamiltonian_.num_targets(); - } - - bool operator==(const TimeEvolution& other) const { - return hamiltonian_ == other.hamiltonian_ && time_ == other.time_; - } - - // ------------------------------------------------------------------- - - MQ_NODISCARD const QubitOperatorCD& get_hamiltonian() const { - return hamiltonian_; - } - - MQ_NODISCARD auto get_time() const { - return time_; - } - - MQ_NODISCARD auto param() const { - return get_time(); - } - - private: - QubitOperatorCD hamiltonian_; - double time_; -}; -} // namespace mindquantum::ops - -namespace tweedledum { -template <> -inline constexpr uint8_t num_param_v = 1; -} // namespace tweedledum - -#endif /* TIMEEVOLUTION_OP_HPP */ diff --git a/ccsrc/include/experimental/ops/meta/CPPLINT.cfg b/ccsrc/include/experimental/ops/meta/CPPLINT.cfg deleted file mode 100644 index ce8679f71..000000000 --- a/ccsrc/include/experimental/ops/meta/CPPLINT.cfg +++ /dev/null @@ -1 +0,0 @@ -filter=-build/include_order diff --git a/ccsrc/include/experimental/ops/meta/dagger.hpp b/ccsrc/include/experimental/ops/meta/dagger.hpp deleted file mode 100644 index c6cc91934..000000000 --- a/ccsrc/include/experimental/ops/meta/dagger.hpp +++ /dev/null @@ -1,66 +0,0 @@ -// Copyright 2020 -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef DAGGER_OP_HPP -#define DAGGER_OP_HPP - -#include -#include -#include -#include -#include - -#include -#include - -namespace mindquantum::ops { -namespace td = tweedledum; - -class DaggerOperation { - public: - template - explicit DaggerOperation(OpT&& op) : op_(std::forward(op)) { - } - - static constexpr std::string_view kind() { - return "projectq.daggeroperation"; - } - - uint32_t num_targets() const { - return op_.num_targets(); - } - - td::Operator adjoint() const { - return op_; - } - - std::optional matrix() const { - const auto m = op_.matrix(); - if (m) { - return m.value().inverse(); - } else { - return std::nullopt; - } - } - - bool operator==(const DaggerOperation& other) const { - return op_ == other.op_; - } - - private: - td::Operator op_; -}; -} // namespace mindquantum::ops - -#endif /* DAGGER_OP_HPP */ diff --git a/ccsrc/include/experimental/ops/parametric/CPPLINT.cfg b/ccsrc/include/experimental/ops/parametric/CPPLINT.cfg deleted file mode 100644 index caef6a42b..000000000 --- a/ccsrc/include/experimental/ops/parametric/CPPLINT.cfg +++ /dev/null @@ -1 +0,0 @@ -filter=-readability/braces,-build/include diff --git a/ccsrc/include/experimental/ops/parametric/angle_base.hpp b/ccsrc/include/experimental/ops/parametric/angle_base.hpp deleted file mode 100644 index fd06a606c..000000000 --- a/ccsrc/include/experimental/ops/parametric/angle_base.hpp +++ /dev/null @@ -1,139 +0,0 @@ -// Copyright 2021 -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef PARAM_ANGLE_BASE_HPP -#define PARAM_ANGLE_BASE_HPP - -#include - -#include -#if __has_include() && __cplusplus > 201703L -# include -#endif // __has_include() && C++20 -#include - -#include - -#include -#include -#include - -#include "experimental/core/config.hpp" -#include "experimental/ops/parametric/gate_base.hpp" -#include "experimental/ops/parametric/param_names.hpp" - -namespace mindquantum::ops::parametric { -#if MQ_HAS_CONCEPTS -template -#else -template -#endif // MQ_HAS_CONCEPTS -class AngleParametricBase : public ParametricBase { - public: - using operator_t = tweedledum::Operator; - using parent_t = ParametricBase; - using base_t = AngleParametricBase; - using self_t = AngleParametricBase; - - using typename parent_t::non_param_type; - using typename parent_t::subs_map_t; - - // NB: using typename parent_t::ParametricBase should work fine but not on older compilers... - using ParametricBase::ParametricBase; - - //! Evaluation helper function - template - MQ_NODISCARD static auto to_param_type(const self_t& /* self */, evaluated_param_t&& evaluated_param) { - return derived_t{std::forward(evaluated_param)}; - } - - //! Evaluation helper function - template - MQ_NODISCARD static auto to_non_param_type(const self_t& /* self */, evaluated_param_t&& evaluated_param) { - // NB: non-parametric classes simply accept the evaluated parameter - return non_param_type{std::forward(evaluated_param)}; - } - - //! Test whether another operation is the same as this instance - MQ_NODISCARD bool operator==(const AngleParametricBase& other) const noexcept { - return eq(*this->param(0), *other.param(0)); - // return eq(*expand(sub(this->param(0), other.param(0))), SymEngine::Integer(0)); - } - - //! Get the adjoint of an \c AngleParametricBase gate instance - MQ_NODISCARD auto adjoint() const noexcept { - auto params = base_t::params_; - for (auto& param : params) { - param = expand(neg(param)); - } - - if constexpr (base_t::has_const_num_targets) { - return derived_t{std::move(params)}; - } else { - return derived_t{this->num_targets_, std::move(params)}; - } - } - - //! Fully evaluate this parametric gate - /*! - * Attempt to fully evaluate this parametric gate (ie. evaluate all parameter numerically). The constructor - * of the non-parametric gate type is called by passing each of the numerically evaluated parameter in the - * order that is defined when passing the type as the template parameters to this base class. - * - * \return An instance of a non-parametric gate (\c non_param_type) - * \throw SymEngine::SymEngineException if the expression cannot be fully evaluated numerically - */ - MQ_NODISCARD non_param_type eval_full() const { - using param_t = typename std::tuple_element_t<0, typename parent_t::params_type>::param_type; - - return non_param_type { - std::fmod(param_t::eval(this->params_[0]), -#if __has_include() && __cplusplus > 201703L - std::numbers::pi * mod_pi -#else - 3.1415926535897932 * mod_pi -#endif // __has_include() && C++20 - ) - }; - } - - //! Fully evaluate this parametric gate - /*! - * Attempt to fully evaluate this parametric gate (ie. evaluate all parameter numerically). The constructor - * of the non-parametric gate type is called by passing each of the numerically evaluated parameter in the - * order that is defined when passing the type as the template parameters to this base class. - * - * This overload accepts a dictionary of substitutions to perform on the parameters. - * - * \param subs_map Dictionary containing all the substitution to perform - * \return An instance of a non-parametric gate (\c non_param_type) - * \throw SymEngine::SymEngineException if the expression cannot be fully evaluated numerically - */ - MQ_NODISCARD non_param_type eval_full(const subs_map_t& subs_map) const { - using param_t = typename std::tuple_element_t<0, typename parent_t::params_type>::param_type; - - return non_param_type { - std::fmod(param_t::eval(this->params_[0]->subs(subs_map)), -#if __has_include() && __cplusplus > 201703L - std::numbers::pi * mod_pi -#else - 3.1415926535897932 * mod_pi -#endif // __has_include() && C++20 - ) - }; - } -}; -} // namespace mindquantum::ops::parametric - -#endif /* PARAM_ANGLE_BASE_HPP */ diff --git a/ccsrc/include/experimental/ops/parametric/angle_gates.hpp b/ccsrc/include/experimental/ops/parametric/angle_gates.hpp deleted file mode 100644 index 110b1931a..000000000 --- a/ccsrc/include/experimental/ops/parametric/angle_gates.hpp +++ /dev/null @@ -1,74 +0,0 @@ -// Copyright 2021 -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef PARAM_ANGLE_GATES_HPP -#define PARAM_ANGLE_GATES_HPP - -#include -#include -#include -#include -#include -#include -#include - -#include "experimental/core/operator_traits.hpp" -#include "experimental/ops/gates/ph.hpp" -#include "experimental/ops/parametric/angle_base.hpp" - -namespace mindquantum::ops::parametric { -// NOLINTNEXTLINE(cppcoreguidelines-macro-usage) -#define DEFINE_PARAMETRIC_ANGLE_GATE_CLASS(klass, non_param_type, gate_kind, mod_pi) \ - /* NOLINTNEXTLINE(bugprone-macro-parentheses) */ \ - class klass : public AngleParametricBase { \ - public: \ - using base_t::base_t; \ - static constexpr auto num_targets = traits::num_targets; \ - \ - static constexpr std::string_view kind() { \ - return gate_kind; \ - } \ - } - -DEFINE_PARAMETRIC_ANGLE_GATE_CLASS(Ph, ops::Ph, "projectq.param.ph", 2); -DEFINE_PARAMETRIC_ANGLE_GATE_CLASS(P, tweedledum::Op::P, "projectq.param.p", 2); -DEFINE_PARAMETRIC_ANGLE_GATE_CLASS(Rx, tweedledum::Op::Rx, "projectq.param.rx", 4); -DEFINE_PARAMETRIC_ANGLE_GATE_CLASS(Rxx, tweedledum::Op::Rxx, "projectq.param.rxx", 4); -DEFINE_PARAMETRIC_ANGLE_GATE_CLASS(Ry, tweedledum::Op::Ry, "projectq.param.ry", 4); -DEFINE_PARAMETRIC_ANGLE_GATE_CLASS(Ryy, tweedledum::Op::Ryy, "projectq.param.ryy", 4); -DEFINE_PARAMETRIC_ANGLE_GATE_CLASS(Rz, tweedledum::Op::Rz, "projectq.param.rz", 4); -DEFINE_PARAMETRIC_ANGLE_GATE_CLASS(Rzz, tweedledum::Op::Rzz, "projectq.param.rzz", 4); - -static_assert(Ph::num_targets == 1); -static_assert(P::num_targets == 1); -static_assert(Rx::num_targets == 1); -static_assert(Ry::num_targets == 1); -static_assert(Rz::num_targets == 1); -static_assert(Rxx::num_targets == 2); -static_assert(Ryy::num_targets == 2); -static_assert(Rzz::num_targets == 2); - -static_assert(Ph::has_const_num_targets); -static_assert(P::has_const_num_targets); -static_assert(Rx::has_const_num_targets); -static_assert(Ry::has_const_num_targets); -static_assert(Rz::has_const_num_targets); -static_assert(Rxx::has_const_num_targets); -static_assert(Ryy::has_const_num_targets); -static_assert(Rzz::has_const_num_targets); - -#undef DEFINE_PARAMETRIC_ANGLE_GATE_CLASS -} // namespace mindquantum::ops::parametric - -#endif /* PARAM_ANGLE_GATES_HPP */ diff --git a/ccsrc/include/experimental/ops/parametric/concepts.hpp b/ccsrc/include/experimental/ops/parametric/concepts.hpp deleted file mode 100644 index 9360f2eae..000000000 --- a/ccsrc/include/experimental/ops/parametric/concepts.hpp +++ /dev/null @@ -1,69 +0,0 @@ -// Copyright 2021 -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef PARAMETRIC_CONCEPTS_HPP -#define PARAMETRIC_CONCEPTS_HPP - -#include - -#include -#include -#include - -#include "experimental/ops/parametric/config.hpp" - -#if MQ_HAS_CONCEPTS -# include "experimental/core/concepts.hpp" -#endif // MQ_HAS_CONCEPTS -#include "experimental/ops/parametric/param_names.hpp" - -namespace mindquantum::concepts { -#if MQ_HAS_CONCEPTS -// template -// using umap_t = frozen::unordered_map, std::equal_to<>>; - -template -concept symengine_expr = std::is_convertible_v>; - -template -concept parameter = requires(param_t p) { - requires std::same_as; - // clang-format off - // NOLINTNEXTLINE(whitespace/parens) - requires (std::same_as - || std::same_as); - // clang-format on -}; - -template -concept expr_or_number = symengine_expr || number; -#else -template -struct symengine_expr : std::false_type {}; - -template -struct symengine_expr< - expr_t, std::enable_if_t>, - std::is_convertible>>> - : std::true_type {}; - -template -struct number : std::false_type {}; - -template -struct number || std::is_floating_point_v) - || (std::is_same_v, T>)>> : std::true_type {}; -#endif // MQ_HAS_CONCEPTS -} // namespace mindquantum::concepts -#endif // PARAMETRIC_CONCEPTS_HPP diff --git a/ccsrc/include/experimental/ops/parametric/config.hpp b/ccsrc/include/experimental/ops/parametric/config.hpp deleted file mode 100644 index 7b6f95570..000000000 --- a/ccsrc/include/experimental/ops/parametric/config.hpp +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright 2021 -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef OPS_CONFIG_HPP -#define OPS_CONFIG_HPP - -#include -#include - -#include -#include -#include - -#include "experimental/core/config.hpp" - -namespace mindquantum::ops::parametric { -using subs_map_t = SymEngine::map_basic_basic; -using basic_t = SymEngine::RCP; -using double_list_t = std::vector; -using param_list_t = SymEngine::vec_basic; -using gate_param_t = std::variant; -} // namespace mindquantum::ops::parametric - -#endif /* OPS_CONFIG_HPP */ diff --git a/ccsrc/include/experimental/ops/parametric/gate_base.hpp b/ccsrc/include/experimental/ops/parametric/gate_base.hpp deleted file mode 100644 index 01566aa88..000000000 --- a/ccsrc/include/experimental/ops/parametric/gate_base.hpp +++ /dev/null @@ -1,482 +0,0 @@ -// Copyright 2021 -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef GATE_BASE_HPP -#define GATE_BASE_HPP - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include - -#include -#include -#include -#include - -// #include - -#include "config/detected.hpp" - -#include "experimental/core/config.hpp" -#include "experimental/core/operator_traits.hpp" -#include "experimental/ops/parametric/config.hpp" -#include "experimental/ops/parametric/param_names.hpp" -#include "experimental/ops/parametric/to_symengine.hpp" - -#if MQ_HAS_CONCEPTS -# include "experimental/core/gate_concepts.hpp" -#endif // MQ_HAS_CONCEPTS - -// namespace frozen -// { -// template <> -// struct elsa -// { -// constexpr std::size_t operator()(std::string_view value) const noexcept -// { -// std::size_t d = 5381; -// for (std::size_t i = 0; i < value.size(); ++i) -// d = d * 33 + static_cast(value[i]); -// return d; -// } -// // https://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function -// // With the lowest bits removed, based on experimental setup. -// constexpr std::size_t operator()(std::string_view value, std::size_t seed) const noexcept -// { -// std::size_t d = (0x811c9dc5 ^ seed) * static_cast(0x01000193); -// for (std::size_t i = 0; i < value.size(); ++i) -// d = (d ^ static_cast(value[i])) * static_cast(0x01000193); -// return d >> 8; -// } -// }; -// } // namespace frozen - -namespace mindquantum::ops::parametric { -#if MQ_HAS_CONCEPTS -template -#else -template -#endif // MQ_HAS_CONCEPTS -class ParametricBase; -} // namespace mindquantum::ops::parametric - -namespace mindquantum::traits { -//! Detect if a template argument pack is a ParametricBase -/*! - * Only needed as a workaround for GCC 7+ when MQ_HAS_CONCEPTS == false - */ -template -struct is_param_base : std::false_type {}; - -#if MQ_HAS_CONCEPTS -template -#else -template -#endif // MQ_HAS_CONCEPTS -struct is_param_base> : std::true_type { -}; -} // namespace mindquantum::traits - -namespace mindquantum::ops::parametric { -#if MQ_HAS_CONCEPTS -template -#else -template -#endif // MQ_HAS_CONCEPTS -class ParametricBase { - public: - static_assert(sizeof...(params_t) > 0, "Need to define at least 1 parameter"); - - using base_t = ParametricBase; - using self_t = ParametricBase; - - using operator_t = tweedledum::Operator; - using is_parametric = void; - using non_param_type = non_param_t; - static constexpr auto num_params = sizeof...(params_t); - using params_type = std::tuple; - using param_array_t = std::array; - - // using map_t = details::umap_t; - using subs_map_t = SymEngine::map_basic_basic; - - static constexpr auto has_const_num_targets = traits::has_const_num_targets_v; - - // ===================================================================== - // :: create_op([num_targets]) - - //! Create a default instance of \c derived_t type - /*! - * Overload only available if \c non_param_type has compile-time constant number of qubits - */ - MQ_NODISCARD static constexpr derived_t create_op() -#if MQ_HAS_CONCEPTS - requires(has_const_num_targets) -#endif // MQ_HAS_CONCEPTS - { - return derived_t{param_array_t{SymEngine::symbol(std::string(params_t::name))...}}; - } - - //! Create a default instance of \c derived_t type - /*! - * Overload only available if \c non_param_type does not have compile-time constant number of qubits - */ - MQ_NODISCARD static constexpr derived_t create_op(uint32_t num_targets) -#if MQ_HAS_CONCEPTS - requires(!has_const_num_targets) -#else -#endif // MQ_HAS_CONCEPTS - { - return derived_t{num_targets, param_array_t{SymEngine::symbol(std::string(params_t::name))...}}; - } - - // --------------------------------------------------------------------- - // :: create_op([num_targets], transforms...) - - //! Create an instance of \c derived_t type with some transformation on the parameters - /*! - * Overload only available if \c non_param_type has compile-time constant number of qubits - */ - template - MQ_NODISCARD static constexpr derived_t create_op(funcs_t&&... transforms) -#if MQ_HAS_CONCEPTS - requires(traits::has_const_num_targets_v) -#endif // MQ_HAS_CONCEPTS - { - static_assert(sizeof...(funcs_t) == sizeof...(params_t), - "You need to specify as many transformation functions as there are parameters"); - return derived_t{param_array_t{expand(transforms(SymEngine::symbol(std::string(params_t::name))))...}}; - } - - //! Create an instance of \c derived_t type with some transformation on the parameters - /*! - * Overload only available if \c non_param_type does not have compile-time constant number of qubits - */ - template - MQ_NODISCARD static constexpr derived_t create_op(uint32_t num_targets, funcs_t&&... transforms) -#if MQ_HAS_CONCEPTS - requires(!has_const_num_targets) -#endif // MQ_HAS_CONCEPTS - { - static_assert(sizeof...(funcs_t) == sizeof...(params_t), - "You need to specify as many transformation functions as there are parameters"); - return derived_t{num_targets, - param_array_t{expand(transforms(SymEngine::symbol(std::string(params_t::name))))...}}; - } - - // --------------------------------------------------------------------- - // :: ParametricBase([num_targets], params...) - - //! Constructor from a list of either C++ numeric types or symbolic expressions - /*! - * \param expr List of SymEngine expressions - * \note This constructor expects exactly \c num_params arguments - */ -#if MQ_HAS_CONCEPTS - template - requires(has_const_num_targets && (concepts::expr_or_number || ...)) - constexpr ParametricBase(Ts&&... args) // NOLINT(runtime/explicit) -#else - template ::value>> - constexpr ParametricBase(Ts&&... args) // NOLINT(runtime/explicit) -#endif // MQ_HAS_CONCEPTS - : num_targets_(traits::num_targets), params_{to_symengine(std::forward(args))...} { - static_assert(sizeof...(Ts) == num_params, "You need to specify a value for all the parameters"); - } - - //! Constructor from a list of either C++ numeric types or symbolic expressions - /*! - * \param num_targets Number of target qubits - * \param expr List of SymEngine expressions - * \note This constructor expects exactly \c num_params arguments - */ -#if MQ_HAS_CONCEPTS - template - requires(!has_const_num_targets && (concepts::expr_or_number || ...)) - constexpr ParametricBase(uint32_t num_targets, Ts&&... args) // NOLINT(runtime/explicit) -#else - template > - constexpr ParametricBase(uint32_t num_targets, Ts&&... args) // NOLINT(runtime/explicit) -#endif // MQ_HAS_CONCEPTS - : num_targets_(num_targets), params_{to_symengine(std::forward(args))...} { - static_assert(sizeof...(Ts) == num_params, "You need to specify a value for all the parameters"); - } - - // --------------------------------------------------------------------- - // :: ParametricBase([num_targets], params) - - //! Constructor from an array of parameters -#if MQ_HAS_CONCEPTS - constexpr ParametricBase(param_array_t&& params) requires(has_const_num_targets) // NOLINT(runtime/explicit) -#else - template > - constexpr ParametricBase(param_array_t&& params) // NOLINT(runtime/explicit) -#endif // MQ_HAS_CONCEPTS - : num_targets_(traits::num_targets), params_{expand_all(std::move(params))} { - } - - //! Constructor from an array of parameters -#if MQ_HAS_CONCEPTS - constexpr ParametricBase(uint32_t num_targets, param_array_t&& params) requires(!has_const_num_targets) -#else - template > - constexpr ParametricBase(uint32_t num_targets, param_array_t&& params) -#endif // MQ_HAS_CONCEPTS - : num_targets_(num_targets), params_{expand_all(std::move(params))} { - } - - // --------------------------------------------------------------------- - // Other defaulted/deleted constructors - - ParametricBase() = delete; - ParametricBase(const ParametricBase&) = default; - -#if defined(MQ_CLANG_MAJOR) && MQ_CLANG_MAJOR < 9 - ParametricBase(ParametricBase&&) = default; -#else - ParametricBase(ParametricBase&&) noexcept = default; -#endif // MQ_CLANG_MAJOR - - ParametricBase& operator=(const ParametricBase&) = default; - ParametricBase& operator=(ParametricBase&&) noexcept = default; - - // --------------------------- - -#if MQ_HAS_CONCEPTS - MQ_NODISCARD static constexpr auto num_targets() noexcept requires(has_const_num_targets) -#else - /* This is totally hacky... - * - * We are essentially relying on the fact that people will be using the type traits - * traits::num_targets in order to get the number of targets at compile time (if available) - */ - template , uint32_t>> - MQ_NODISCARD static constexpr auto num_targets_static() noexcept -#endif // MQ_HAS_CONCEPTS - { - return traits::num_targets; - } - -#if MQ_HAS_CONCEPTS - MQ_NODISCARD constexpr auto num_targets() const noexcept requires(!has_const_num_targets) -#else - template , uint32_t>> - MQ_NODISCARD constexpr auto num_targets() const noexcept -#endif // MQ_HAS_CONCEPTS - { - return num_targets_; - } - - //! Test whether another operation is the same as this instance - MQ_NODISCARD bool operator==(const ParametricBase& other) const noexcept { - return std::equal(begin(params_), end(params_), begin(other.params_), - [](const auto& a, const auto& b) { return eq(*a, *b); }); - } - -#if !MQ_HAS_OPERATOR_NOT_EQUAL_SYNTHESIS - //! Test whether another operation is the same as this instance - MQ_NODISCARD bool operator!=(const ParametricBase& other) const noexcept { - return !(*this == other); - } -#endif // !MQ_HAS_OPERATOR_NOT_EQUAL_SYNTHESIS - - //! True if this operation has no particular ordering of qubits - MQ_NODISCARD bool is_symmetric() const noexcept { - return true; - } - - //! Get the name of the parameter at some index - /*! - * \param idx Index of parameter - */ - MQ_NODISCARD static constexpr const auto& param_name(std::size_t idx) { - assert(idx < num_params); - return pos_[idx]; - } - - //! Parameter getter method - /*! - * \param idx Index of parameter - * \return Parameter at index \c idx - */ - MQ_NODISCARD constexpr const auto& param(std::size_t idx) const { - assert(idx < num_params); - return params_[idx]; - } - - //! Get all the parameters in an array - /*! - * \return SymEngine::vec_basic (\c std::vector<...>) containing all parameters - */ - MQ_NODISCARD auto params() const noexcept { - SymEngine::vec_basic params; - std::copy(begin(params_), end(params_), std::inserter(params, end(params))); - return params; - } - - //! Evaluate the parameters of this parametric gate using some substitutions - /*! - * This function does not attempt to fully evaluate this parametric gate (ie. evaluate all parameter - * numerically) - * - * \param subs_map Dictionary containing all the substitution to perform - * \return An new instance of the parametric gate with evaluated parameters - * \sa non_param_type eval_full(const SymEngine::map_basic_basic& subs_map) const - */ - MQ_NODISCARD derived_t eval(const subs_map_t& subs_map) const { - auto new_params = base_t::params_; - for (auto& new_param : new_params) { - // NB: expand required to normalize the expressions (e.g. required for testing for equality) - new_param = expand(new_param->subs(subs_map)); - } - if constexpr (has_const_num_targets) { - return {std::move(new_params)}; - } else { - return {num_targets_, std::move(new_params)}; - } - } - - //! Fully evaluate this parametric gate - /*! - * Attempt to fully evaluate this parametric gate (ie. evaluate all parameter numerically). The constructor - * of the non-parametric gate type is called by passing each of the numerically evaluated parameter in the - * order that is defined when passing the type as the template parameters to this base class. - * - * \return An instance of a non-parametric gate (\c non_param_type) - * \throw SymEngine::SymEngineException if the expression cannot be fully evaluated numerically - */ - MQ_NODISCARD auto eval_full() const { - return eval_full_impl_(std::index_sequence_for{}); - } - - //! Fully evaluate this parametric gate - /*! - * Attempt to fully evaluate this parametric gate (ie. evaluate all parameter numerically). The constructor - * of the non-parametric gate type is called by passing each of the numerically evaluated parameter in the - * order that is defined when passing the type as the template parameters to this base class. - * - * This overload accepts a dictionary of substitutions to perform on the parameters. - * - * \param subs_map Dictionary containing all the substitution to perform - * \return An instance of a non-parametric gate (\c non_param_type) - * \throw SymEngine::SymEngineException if the expression cannot be fully evaluated numerically - */ - MQ_NODISCARD auto eval_full(const subs_map_t& subs_map) const { - return eval_full_impl_(std::index_sequence_for{}, subs_map); - } - - //! Evaluate the parameters of this parametric gate using some substitutions - /*! - * This function will attempt to fully evaluate this parametric gate if possible. This will happen only if, - * after substitutions, all the parameters have a numeric representation. - * - * \param subs_map Dictionary containing all the substitution to perform - * \return An new instance of the parametric gate with evaluated parameters - * \sa non_param_type eval_full(const SymEngine::map_basic_basic& subs_map) const - */ - MQ_NODISCARD operator_t eval_smart() const { - auto new_params = base_t::params_; - for (auto& new_param : new_params) { - // NB: expand required to normalize the expressions (e.g. required for testing for equality) - new_param = expand(new_param); - } - - if (std::all_of(begin(new_params), end(new_params), [](const auto& p) { return is_a_Number(*p); })) { - return eval_smart_impl_(std::index_sequence_for{}, std::move(new_params)); - } - - // TODO(dnguyen): Add support for default implementation of `to_param_type` - return derived_t::to_param_type(*static_cast(this), std::move(new_params)); - } - - //! Evaluate the parameters of this parametric gate using some substitutions - /*! - * This function will attempt to fully evaluate this parametric gate if possible. This will happen only if, - * after substitutions, all the parameters have a numeric representation. - * - * \param subs_map Dictionary containing all the substitution to perform - * \return An new instance of the parametric gate with evaluated parameters - * \sa non_param_type eval_full(const SymEngine::map_basic_basic& subs_map) const - */ - MQ_NODISCARD operator_t eval_smart(const subs_map_t& subs_map) const { - auto new_params = base_t::params_; - for (auto& new_param : new_params) { - // NB: expand required to normalize the expressions (e.g. required for testing for equality) - new_param = expand(new_param->subs(subs_map)); - } - - if (std::all_of(begin(new_params), end(new_params), [](const auto& p) { return is_a_Number(*p); })) { - return eval_smart_impl_(std::index_sequence_for{}, std::move(new_params)); - } - - // TODO(dnguyen): Add support for default implementation of `to_param_type` - return derived_t::to_param_type(*static_cast(this), std::move(new_params)); - } - - protected: - static constexpr std::array pos_ = {params_t::name...}; - // TODO(dnguyen): remove this attribute for operator that have compile-time constant number of targets - uint32_t num_targets_; - const param_array_t params_; - - private: - static constexpr auto expand_all(param_array_t&& params) { - return expand_all_impl(std::make_index_sequence>{}, std::move(params)); - } - - template - static constexpr auto expand_all_impl(std::index_sequence /*unused*/, param_array_t&& params) { - return param_array_t{expand(params[indices])...}; - } - - //! Helper function for \c eval_full - template - constexpr auto eval_full_impl_(std::index_sequence /*unused*/) const { - // NB: expand required to normalize the expressions (e.g. required for testing for equality) - // TODO(dnguyen): Add support for default implementation of `to_non_param_type` - return derived_t::to_non_param_type(*static_cast(this), - params_t::param_type::eval(expand(params_[indices]))...); - } - - //! Helper function for \c eval_full - template - constexpr auto eval_full_impl_(std::index_sequence /*unused*/, const subs_map_t& subs_map) const { - // NB: expand required to normalize the expressions (e.g. required for testing for equality) - // TODO(dnguyen): Add support for default implementation of `to_non_param_type` - return derived_t::to_non_param_type(*static_cast(this), - params_t::param_type::eval(expand(params_[indices]->subs(subs_map)))...); - } - - //! Helper function for \c eval_smart - template - constexpr auto eval_smart_impl_(std::index_sequence /*unused*/, - std::array&& params) const { - // TODO(dnguyen): Add support for default implementation of `to_non_param_type` - return derived_t::to_non_param_type(*static_cast(this), - params_t::param_type::eval(params[indices])...); - } -}; -} // namespace mindquantum::ops::parametric - -#endif /* GATE_BASE_HPP */ diff --git a/ccsrc/include/experimental/ops/parametric/param_names.hpp b/ccsrc/include/experimental/ops/parametric/param_names.hpp deleted file mode 100644 index 87da405a2..000000000 --- a/ccsrc/include/experimental/ops/parametric/param_names.hpp +++ /dev/null @@ -1,105 +0,0 @@ -// Copyright 2021 -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef PARAM_NAMES_HPP -#define PARAM_NAMES_HPP - -#include -#include - -#include - -#include "experimental/ops/parametric/config.hpp" - -namespace mindquantum::ops::parametric { -namespace details { -//! Defines a real parameter -struct real_tag_t { // NOLINT(altera-struct-pack-align) - using type = double; - static auto eval(const basic_t& expr) { - return eval_double(*expr); - } -}; -//! Defines a complex parameter -struct complex_tag_t { // NOLINT(altera-struct-pack-align) - using type = std::complex; - static auto eval(const basic_t& expr) { - return eval_complex_double(*expr); - } -}; -} // namespace details - -// NOLINTNEXTLINE(cppcoreguidelines-macro-usage) -#define DEFINE_PARAM_STRUCT(type, param_name) \ - struct param_name { /* NOLINT(altera-struct-pack-align) */ \ - static constexpr std::string_view name = #param_name; \ - using param_type = type; \ - } - -namespace real { -DEFINE_PARAM_STRUCT(details::real_tag_t, alpha); -DEFINE_PARAM_STRUCT(details::real_tag_t, beta); -DEFINE_PARAM_STRUCT(details::real_tag_t, gamma); -DEFINE_PARAM_STRUCT(details::real_tag_t, delta); -DEFINE_PARAM_STRUCT(details::real_tag_t, epsilon); -DEFINE_PARAM_STRUCT(details::real_tag_t, zeta); -DEFINE_PARAM_STRUCT(details::real_tag_t, eta); -DEFINE_PARAM_STRUCT(details::real_tag_t, theta); -DEFINE_PARAM_STRUCT(details::real_tag_t, iota); -DEFINE_PARAM_STRUCT(details::real_tag_t, kappa); -DEFINE_PARAM_STRUCT(details::real_tag_t, lambda); -DEFINE_PARAM_STRUCT(details::real_tag_t, mu); -DEFINE_PARAM_STRUCT(details::real_tag_t, nu); -DEFINE_PARAM_STRUCT(details::real_tag_t, xi); -DEFINE_PARAM_STRUCT(details::real_tag_t, omicron); -DEFINE_PARAM_STRUCT(details::real_tag_t, pi); -DEFINE_PARAM_STRUCT(details::real_tag_t, rho); -DEFINE_PARAM_STRUCT(details::real_tag_t, sigma); -DEFINE_PARAM_STRUCT(details::real_tag_t, tau); -DEFINE_PARAM_STRUCT(details::real_tag_t, upsilon); -DEFINE_PARAM_STRUCT(details::real_tag_t, phi); -DEFINE_PARAM_STRUCT(details::real_tag_t, chi); -DEFINE_PARAM_STRUCT(details::real_tag_t, omega); -} // namespace real - -namespace complex { -DEFINE_PARAM_STRUCT(details::complex_tag_t, alpha); -DEFINE_PARAM_STRUCT(details::complex_tag_t, beta); -DEFINE_PARAM_STRUCT(details::complex_tag_t, gamma); -DEFINE_PARAM_STRUCT(details::complex_tag_t, delta); -DEFINE_PARAM_STRUCT(details::complex_tag_t, epsilon); -DEFINE_PARAM_STRUCT(details::complex_tag_t, zeta); -DEFINE_PARAM_STRUCT(details::complex_tag_t, eta); -DEFINE_PARAM_STRUCT(details::complex_tag_t, theta); -DEFINE_PARAM_STRUCT(details::complex_tag_t, iota); -DEFINE_PARAM_STRUCT(details::complex_tag_t, kappa); -DEFINE_PARAM_STRUCT(details::complex_tag_t, lambda); -DEFINE_PARAM_STRUCT(details::complex_tag_t, mu); -DEFINE_PARAM_STRUCT(details::complex_tag_t, nu); -DEFINE_PARAM_STRUCT(details::complex_tag_t, xi); -DEFINE_PARAM_STRUCT(details::complex_tag_t, omicron); -DEFINE_PARAM_STRUCT(details::complex_tag_t, pi); -DEFINE_PARAM_STRUCT(details::complex_tag_t, rho); -DEFINE_PARAM_STRUCT(details::complex_tag_t, sigma); -DEFINE_PARAM_STRUCT(details::complex_tag_t, tau); -DEFINE_PARAM_STRUCT(details::complex_tag_t, upsilon); -DEFINE_PARAM_STRUCT(details::complex_tag_t, phi); -DEFINE_PARAM_STRUCT(details::complex_tag_t, chi); -DEFINE_PARAM_STRUCT(details::complex_tag_t, omega); -} // namespace complex - -#undef DEFINE_PARAM_STRUCT -} // namespace mindquantum::ops::parametric - -#endif /* PARAM_NAMES_HPP */ diff --git a/ccsrc/include/experimental/ops/parametric/register_gate_type.hpp b/ccsrc/include/experimental/ops/parametric/register_gate_type.hpp deleted file mode 100644 index d463049d8..000000000 --- a/ccsrc/include/experimental/ops/parametric/register_gate_type.hpp +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright 2021 -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef REGISTER_GATE_TYPE_HPP -#define REGISTER_GATE_TYPE_HPP - -#include - -#include - -#include "experimental/ops/parametric/config.hpp" - -#if MQ_HAS_CONCEPTS -# include "experimental/core/gate_concepts.hpp" -#endif // MQ_HAS_CONCEPTS - -namespace mindquantum::ops::parametric { -//! Register a new gate class -/*! - * \tparam operator_t Type of the gate to register - * - * \note If the gate is neither a parametric gate or a gate with an angle() method, this method is no-op. - */ -template -void register_gate_type() MQ_REQUIRES((concepts::ParametricGate) || (concepts::AngleGate) - || (concepts::SingleDoubleGate) || (concepts::MultiDoubleGate) ); - -//! Get the parameters of an operation -/*! - * \param optor A quantum operation - */ -[[nodiscard]] gate_param_t get_param(const operator_t& optor) noexcept; -} // namespace mindquantum::ops::parametric - -#include "register_gate_type.tpp" - -#endif /* REGISTER_GATE_TYPE_HPP */ diff --git a/ccsrc/include/experimental/ops/parametric/register_gate_type.tpp b/ccsrc/include/experimental/ops/parametric/register_gate_type.tpp deleted file mode 100644 index 447ea6182..000000000 --- a/ccsrc/include/experimental/ops/parametric/register_gate_type.tpp +++ /dev/null @@ -1,59 +0,0 @@ -// Copyright 2021 -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef REGISTER_GATE_TYPE_TPP -#define REGISTER_GATE_TYPE_TPP - -// clang-format off -#ifndef REGISTER_GATE_TYPE_HPP -# error This file must only be included by register_gate_type.hpp! -#endif // REGISTER_GATE_TYPE_HPP - -// NB: This is mainly for syntax checkers and completion helpers as this file -// is only intended to be included directly by register_gate_type.hpp -#include "experimental/ops/parametric/register_gate_type.hpp" -// clang-format on - -#include -#include - -#include "experimental/core/gate_traits.hpp" - -// ============================================================================= - -namespace mindquantum::ops::parametric { -using double_func_t = double (*)(const operator_t&); -using vec_double_func_t = std::vector (*)(const operator_t&); -using params_func_t = param_list_t (*)(const operator_t&); - -namespace details { -void register_gate(std::string_view kind, double_func_t angle_func); -void register_gate(std::string_view kind, vec_double_func_t angle_func); -void register_gate(std::string_view kind, params_func_t params_func); -} // namespace details - -template -void register_gate_type() -#if MQ_HAS_CONCEPTS - requires((concepts::ParametricGate) || (concepts::AngleGate) || (concepts::SingleDoubleGate) - || (concepts::MultiDoubleGate) ) -#endif // MQ_HAS_CONCEPTS -{ - details::register_gate(op_t::kind(), traits::gate_traits::param); -} -} // namespace mindquantum::ops::parametric - -// ============================================================================= - -#endif /* REGISTER_GATE_TYPE_TPP */ diff --git a/ccsrc/include/experimental/ops/parametric/substitutions.hpp b/ccsrc/include/experimental/ops/parametric/substitutions.hpp deleted file mode 100644 index ca8791e01..000000000 --- a/ccsrc/include/experimental/ops/parametric/substitutions.hpp +++ /dev/null @@ -1,64 +0,0 @@ -// Copyright 2021 -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef PARAMETRIC_SUBSTITUTIONS_HPP -#define PARAMETRIC_SUBSTITUTIONS_HPP -#include - -#include "experimental/ops/parametric/config.hpp" -#include "experimental/ops/parametric/traits.hpp" - -namespace mindquantum::ops::parametric { -//! Generate a substitution dictionary from a single double -/*! - * \pre \c sizeof(args_t) == operator_t::num_params() - */ -template -MQ_NODISCARD auto generate_subs(args_t&&... args); - -//! Generate a substitution dictionary from an array of double -/*! - * \sa generate_subs_(const std::vector& param) const; - */ -template -MQ_NODISCARD auto generate_subs(const double_list_t& params); - -//! Generate a substitution dictionary from an array of expressions -/*! - * \sa generate_subs_(const std::vector& param) const; - */ -template -MQ_NODISCARD auto generate_subs(const param_list_t& params); - -namespace details { -//! Generate a substitution dictionary from an array of elements -/*! - * \pre \c size(param) == op_t::num_params() - */ -template -MQ_NODISCARD auto generate_subs(const std::vector& params); - -#if MQ_HAS_CONCEPTS -template -MQ_NODISCARD auto create_subs_from_params(std::index_sequence /*unused*/, expr_t&&... exprs); -#else -template -MQ_NODISCARD auto create_subs_from_params(std::index_sequence /*unused*/, args_t&&... args); -#endif // MQ_HAS_CONCEPTS -} // namespace details -} // namespace mindquantum::ops::parametric - -#include "substitutions.tpp" - -#endif /* PARAMETRIC_SUBSTITUTIONS_HPP */ diff --git a/ccsrc/include/experimental/ops/parametric/substitutions.tpp b/ccsrc/include/experimental/ops/parametric/substitutions.tpp deleted file mode 100644 index 45df6e35b..000000000 --- a/ccsrc/include/experimental/ops/parametric/substitutions.tpp +++ /dev/null @@ -1,81 +0,0 @@ -// Copyright 2021 -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef PARAMETRIC_SUBSTITUTIONS_TPP -#define PARAMETRIC_SUBSTITUTIONS_TPP - -#ifndef PARAMETRIC_SUBSTITUTIONS_HPP -# error This file must only be included by ops/parametric/substitutions.hpp! -#endif // PARAMETRIC_SUBSTITUTIONS_HPP - -// NB: This is mainly for syntax checkers and completion helpers as this file -// is only intended to be included directly by atom_storage.hpp - -#include -#include - -#include "experimental/ops/parametric/config.hpp" -#include "experimental/ops/parametric/substitutions.hpp" -#include "experimental/ops/parametric/to_symengine.hpp" - -namespace mindquantum::ops::parametric { - -template -auto generate_subs(args_t&&... args) { - return details::create_subs_from_params(std::index_sequence_for{}, - std::forward(args)...); -} - -template -auto generate_subs(const double_list_t& params) { - return details::generate_subs(params); -} - -template -auto generate_subs(const param_list_t& params) { - return details::generate_subs(params); -} - -// ------------------------------------------------------------------------- - -namespace details { -template -auto generate_subs(const std::vector& params) { - subs_map_t subs; - auto idx = 0UL; - for (const auto& param : params) { - subs.emplace(op_t::create_op().param(idx), to_symengine(param)); - ++idx; - } - return subs; -} - -// ========================================================================= - -#if MQ_HAS_CONCEPTS -template -#else -template -#endif // MQ_HAS_CONCEPTS -auto create_subs_from_params(std::index_sequence /* indices */, exprs_t&&... exprs) { - static_assert(sizeof...(indices) == op_t::num_params); - static_assert(sizeof...(indices) == sizeof...(exprs)); - return subs_map_t{std::make_pair(op_t::create_op().param(indices), to_symengine(std::forward(exprs)))...}; -} - -} // namespace details - -} // namespace mindquantum::ops::parametric - -#endif // PARAMETRIC_SUBSTITUTIONS_TPP diff --git a/ccsrc/include/experimental/ops/parametric/time_evolution.hpp b/ccsrc/include/experimental/ops/parametric/time_evolution.hpp deleted file mode 100644 index 18ae4ea54..000000000 --- a/ccsrc/include/experimental/ops/parametric/time_evolution.hpp +++ /dev/null @@ -1,100 +0,0 @@ -// Copyright 2022 -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef PARAM_TIME_EVOLUTION_HPP -#define PARAM_TIME_EVOLUTION_HPP - -#include - -#include "experimental/core/config.hpp" -#include "experimental/ops/gates/time_evolution.hpp" -#include "experimental/ops/parametric/gate_base.hpp" -#include "experimental/ops/parametric/param_names.hpp" - -namespace mindquantum::ops::parametric { -class TimeEvolution : public ParametricBase { - public: - using operator_t = tweedledum::Operator; - using parent_t = ParametricBase; - using self_t = TimeEvolution; - - using typename parent_t::non_param_type; - using typename parent_t::subs_map_t; - - using QubitOperatorCD = QubitOperator>; - - using non_const_num_targets = void; - - static constexpr std::string_view kind() { - return "projectq.param.timeevolution"; - } - - //! Constructor - /*! - * Overload required in some cases for metaprogramming with operators. - */ - template - TimeEvolution(uint32_t num_targets, QubitOperatorCD hamiltonian, param_t&& param) - : TimeEvolution(hamiltonian, std::forward(param)) { - assert(num_targets == hamiltonian.num_targets()); - } - - //! Constructor - template - TimeEvolution(QubitOperatorCD hamiltonian, param_t&& param) - : ParametricBase(hamiltonian.num_targets(), - std::forward(param)) - , hamiltonian_(std::move(hamiltonian)) { - } - - //! Get the adjoint of an \c TimeEvolution gate instance - MQ_NODISCARD auto adjoint() const noexcept { - auto params = base_t::params_; - for (auto& param : params) { - param = expand(SymEngine::neg(param)); - } - - return self_t{hamiltonian_.num_targets(), hamiltonian_, std::move(params)}; - } - - bool operator==(const self_t& other) const { - return hamiltonian_ == other.hamiltonian_ && this->parent_t::operator==(other); - } - - template - MQ_NODISCARD static auto to_param_type(const self_t& self, evaluated_param_t&& evaluated_param) { - return self_t{self.hamiltonian_, std::forward(evaluated_param)}; - } - - template - MQ_NODISCARD static auto to_non_param_type(const self_t& self, evaluated_param_t&& evaluated_param) { - return non_param_type{self.hamiltonian_, std::forward(evaluated_param)}; - } - - // ------------------------------------------------------------------- - - MQ_NODISCARD const QubitOperatorCD& get_hamiltonian() const { - return hamiltonian_; - } - - MQ_NODISCARD const auto& get_time() const { - return param(0); - } - - private: - QubitOperatorCD hamiltonian_; -}; -} // namespace mindquantum::ops::parametric - -#endif /* PARAM_TIME_EVOLUTION_HPP */ diff --git a/ccsrc/include/experimental/ops/parametric/to_symengine.hpp b/ccsrc/include/experimental/ops/parametric/to_symengine.hpp deleted file mode 100644 index 8c6e69b8c..000000000 --- a/ccsrc/include/experimental/ops/parametric/to_symengine.hpp +++ /dev/null @@ -1,61 +0,0 @@ -// Copyright 2022 -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef TO_SYMENGINE_HPP -#define TO_SYMENGINE_HPP - -#include -#include - -#include "experimental/core/traits.hpp" -#include "experimental/ops/parametric/concepts.hpp" -#include "experimental/ops/parametric/config.hpp" - -#if MQ_HAS_CONCEPTS -# include "experimental/core/concepts.hpp" -#endif // MQ_HAS_CONCEPTS - -namespace mindquantum::ops::parametric { -#if MQ_HAS_CONCEPTS -template -auto to_symengine(T&& t) { - using type = std::remove_cvref_t; - if constexpr (std::integral) { - return SymEngine::integer(t); - } else if constexpr (std::floating_point) { - return SymEngine::number(t); - } else if constexpr (traits::is_std_complex_v) { - return SymEngine::complex_double(std::forward(t)); - } else { - return SymEngine::expand(std::forward(t)); - } -} -#else -template -auto to_symengine(T&& t) { - using type = std::remove_cvref_t; - if constexpr (std::is_integral_v) { - return SymEngine::integer(t); - } else if constexpr (std::is_floating_point_v) { - return SymEngine::number(t); - } else if constexpr (traits::is_std_complex_v) { - return SymEngine::complex_double(std::forward(t)); - } else { - return SymEngine::expand(std::forward(t)); - } -} -#endif // MQ_HAS_CONCEPTS -} // namespace mindquantum::ops::parametric - -#endif /* TO_SYMENGINE_HPP */ diff --git a/ccsrc/include/experimental/ops/parametric/traits.hpp b/ccsrc/include/experimental/ops/parametric/traits.hpp deleted file mode 100644 index a11927dc9..000000000 --- a/ccsrc/include/experimental/ops/parametric/traits.hpp +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright 2021 -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef PARAMETRIC_TRAITS_HPP -#define PARAMETRIC_TRAITS_HPP - -#include - -#include "experimental/ops/parametric/config.hpp" - -namespace mindquantum::traits { -template -constexpr bool kind_match(ref_kind_t&& ref_kind, kinds_t&&... kinds) -#if MQ_HAS_CONCEPTS - requires(sizeof...(kinds_t) > 0) -#endif // MQ_HAS_CONCEPTS -{ -#if !MQ_HAS_CONCEPTS - static_assert(sizeof...(kinds_t) > 0); -#endif // MQ_HAS_CONCEPTS - return ((ref_kind == kinds) || ...); -} -} // namespace mindquantum::traits - -#endif /* PARAMETRIC_TRAITS_HPP */ diff --git a/ccsrc/include/experimental/simulator/CPPLINT.cfg b/ccsrc/include/experimental/simulator/CPPLINT.cfg deleted file mode 100644 index caef6a42b..000000000 --- a/ccsrc/include/experimental/simulator/CPPLINT.cfg +++ /dev/null @@ -1 +0,0 @@ -filter=-readability/braces,-build/include diff --git a/ccsrc/include/experimental/simulator/concepts.hpp b/ccsrc/include/experimental/simulator/concepts.hpp deleted file mode 100644 index 782bf61eb..000000000 --- a/ccsrc/include/experimental/simulator/concepts.hpp +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright 2022 -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef SIMULATOR_CONCEPTS_HPP -#define SIMULATOR_CONCEPTS_HPP - -#include "experimental/core/types.hpp" -#include "experimental/simulator/config.hpp" - -#if MQ_HAS_CONCEPTS -# include "experimental/core/concepts.hpp" -#endif // MQ_HAS_CONCEPTS - -namespace mindquantum::concepts { -#if MQ_HAS_CONCEPTS -//! C++20 concept representing a basic simulator API. -template -concept CircuitSimulator = requires(simulator_t simulator, qubit_t qubit, qubits_t qubits, instruction_t inst) { - { simulator.run_instruction(inst) } -> same_decay_as; - { simulator.allocate_qubits(qubits) } -> same_decay_as; - { simulator.has_qubit(qubit) } -> same_decay_as; -}; -#endif // MQ_HAS_CONCEPTS -} // namespace mindquantum::concepts - -#endif /* SIMULATOR_CONCEPTS_HPP */ diff --git a/ccsrc/include/experimental/simulator/config.hpp b/ccsrc/include/experimental/simulator/config.hpp deleted file mode 100644 index 4d6944329..000000000 --- a/ccsrc/include/experimental/simulator/config.hpp +++ /dev/null @@ -1,20 +0,0 @@ -// Copyright 2022 -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef SIMULATOR_CONFIG_HPP -#define SIMULATOR_CONFIG_HPP - -#include "experimental/core/config.hpp" - -#endif /* SIMULATOR_CONFIG_HPP */ diff --git a/ccsrc/include/experimental/simulator/projectq_simulator.hpp b/ccsrc/include/experimental/simulator/projectq_simulator.hpp deleted file mode 100644 index cfa79f271..000000000 --- a/ccsrc/include/experimental/simulator/projectq_simulator.hpp +++ /dev/null @@ -1,77 +0,0 @@ -// Copyright 2022 -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef PROJECTQ_SIMULATOR_HPP -#define PROJECTQ_SIMULATOR_HPP - -#include -#include - -#include "projectq/backends/_sim/_cppkernels/simulator.hpp" - -#include "experimental/core/types.hpp" -#include "experimental/simulator/config.hpp" -#include "experimental/simulator/simulator_base.hpp" - -namespace mindquantum::simulation::projectq { -class Simulator : public BaseSimulator { - public: - //! Simple constructor - /*! - * \param seed Seed for random generator. - */ - explicit Simulator(uint32_t seed = 0); - - //! Check whether a qubit is already allocated by the simulator - /*! - * \param qubit A qubit ID - * \return True if the qubit is allocated, false otherwise - */ - MQ_NODISCARD bool has_qubit(const qubit_t& qubit) const; - - //! Check whether a qubit is already allocated by the simulator - /*! - * \param qubit qubits A list of qubits to allocate - * \return True if the allocation was successful, false otherwise - */ - MQ_NODISCARD bool allocate_qubits(const qubits_t& qubits); - - //! Check whether a qubit is already allocated by the simulator - /*! - * \param inst A quantum instruction - * \return True if running the instruction was successful, false otherwise - */ - MQ_NODISCARD bool run_instruction(const instruction_t& inst); - - //! Access to the current state vector - MQ_NODISCARD auto cheat() { - return sim_.cheat(); - } - - //! Perform a measurement on a set of qubits - /*! - * \param qubits List of qubits to measure - */ - MQ_NODISCARD auto measure_qubits_return(const qubits_t& qubits) { - std::vector targets; - std::for_each(begin(qubits), end(qubits), - [&targets](const auto& qubit) { targets.emplace_back(qubit_id_t{qubit}); }); - } - - private: - ::projectq::Simulator sim_; -}; -} // namespace mindquantum::simulation::projectq - -#endif /* PROJECTQ_SIMULATOR_HPP */ diff --git a/ccsrc/include/experimental/simulator/simulator_base.hpp b/ccsrc/include/experimental/simulator/simulator_base.hpp deleted file mode 100644 index 1a929576e..000000000 --- a/ccsrc/include/experimental/simulator/simulator_base.hpp +++ /dev/null @@ -1,70 +0,0 @@ -// Copyright 2022 -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef SIMULATOR_BASE_HPP -#define SIMULATOR_BASE_HPP - -#include - -#include "experimental/core/circuit_block.hpp" -#include "experimental/core/types.hpp" -#include "experimental/simulator/config.hpp" -#if MQ_HAS_CONCEPTS -# include "experimental/simulator/concepts.hpp" -#endif // MQ_HAS_CONCEPTS - -namespace mindquantum::simulation { -//! A base class for all simulators -template -class BaseSimulator { - public: - using base_t = BaseSimulator; - using parent_t = BaseSimulator; - - //! Simple constructor - /*! - * \param seed Random seed to initialiue the random number generator. - */ - explicit BaseSimulator(uint32_t seed = 0); - - // ------------------------------------------------------------------------- - // Methods that need to be implemented in the child class - // - // bool has_qubit(const qubit_t& qubit); - // bool allocate_qubits(const qubits_t& qubits); - // bool run_instruction(const instruction_t& inst); - - // ============================================================================= - - //! Run a quantum circuit using a simulator - /*! - * \param circuit A quantum circuit - * - * \note This function will call - */ -#if MQ_HAS_CONCEPTS - template -#else - template -#endif // MQ_HAS_CONCEPTS - MQ_NODISCARD bool run_circuit(const circuit_like_t& circuit); - - private: - uint32_t seed_; -}; -} // namespace mindquantum::simulation - -#include "simulator_base.tpp" - -#endif /* SIMULATOR_BASE_HPP */ diff --git a/ccsrc/include/experimental/simulator/simulator_base.tpp b/ccsrc/include/experimental/simulator/simulator_base.tpp deleted file mode 100644 index b9c7f41b7..000000000 --- a/ccsrc/include/experimental/simulator/simulator_base.tpp +++ /dev/null @@ -1,66 +0,0 @@ -// Copyright 2022 -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef SIMULATOR_BASE_TPP -#define SIMULATOR_BASE_TPP - -#ifndef SIMULATOR_BASE_HPP -# error This file must only be included by simulator/simulator_base.hpp! -#endif // SIMULATOR_BASE_HPP - -// NB: This is mainly for syntax checkers and completion helpers as this file -// is only intended to be included directly by simulator_base.hpp -#include "experimental/simulator/simulator_base.hpp" - -namespace mindquantum::simulation { -template -BaseSimulator::BaseSimulator(uint32_t seed) : seed_(seed) { -#if MQ_HAS_CONCEPTS - static_assert(concepts::CircuitSimulator); -#endif // MQ_HAS_CONCEPTS -} - -// ============================================================================= - -template -#if MQ_HAS_CONCEPTS -template -#else -template -#endif // MQ_HAS_CONCEPTS -bool BaseSimulator::run_circuit(const circuit_like_t& circuit) { - auto* simulator{static_cast(this)}; - - qubits_t qubits_to_allocate; - for (const auto& qubit : circuit.qubits()) { - if (!simulator->has_qubit(qubit)) { - qubits_to_allocate.push_back(qubit); - } - } - - if (!simulator->allocate_qubits(qubits_to_allocate)) { - return false; - } - - auto run_ok = true; - circuit.foreach_instruction([&simulator, &run_ok](const instruction_t& inst) { - if (run_ok) { - run_ok &= simulator->run_instruction(inst); - } - }); - - return run_ok; -} -} // namespace mindquantum::simulation -#endif /* SIMULATOR_BASE_TPP */ diff --git a/ccsrc/include/math/operators/fermion_operator_view.hpp b/ccsrc/include/math/operators/fermion_operator_view.h similarity index 90% rename from ccsrc/include/math/operators/fermion_operator_view.hpp rename to ccsrc/include/math/operators/fermion_operator_view.h index af20ec72d..90c0421c0 100644 --- a/ccsrc/include/math/operators/fermion_operator_view.hpp +++ b/ccsrc/include/math/operators/fermion_operator_view.h @@ -1,16 +1,18 @@ -// Copyright 2023 -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. +/** + * Copyright (c) Huawei Technologies Co., Ltd. 2023. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ #ifndef MATH_OPERATORS_FERMION_OPERATOR_VIEW_HPP_ #define MATH_OPERATORS_FERMION_OPERATOR_VIEW_HPP_ @@ -24,11 +26,11 @@ #include #include -#include "math/operators/utils.hpp" -#include "math/pr/parameter_resolver.hpp" -#include "math/tensor/ops/concrete_tensor.hpp" -#include "math/tensor/tensor.hpp" -#include "math/tensor/traits.hpp" +#include "math/operators/utils.h" +#include "math/pr/parameter_resolver.h" +#include "math/tensor/ops/concrete_tensor.h" +#include "math/tensor/tensor.h" +#include "math/tensor/traits.h" namespace operators::fermion { namespace tn = tensor; enum class TermValue : uint64_t { diff --git a/ccsrc/include/math/operators/qubit_operator_view.hpp b/ccsrc/include/math/operators/qubit_operator_view.h similarity index 90% rename from ccsrc/include/math/operators/qubit_operator_view.hpp rename to ccsrc/include/math/operators/qubit_operator_view.h index 48f9618f9..2461cdf3f 100644 --- a/ccsrc/include/math/operators/qubit_operator_view.hpp +++ b/ccsrc/include/math/operators/qubit_operator_view.h @@ -1,16 +1,18 @@ -// Copyright 2023 -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. +/** + * Copyright (c) Huawei Technologies Co., Ltd. 2023. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ #ifndef MATH_OPERATORS_QUBIT_OPERATOR_VIEW_HPP_ #define MATH_OPERATORS_QUBIT_OPERATOR_VIEW_HPP_ @@ -23,12 +25,12 @@ #include #include -#include "math/operators/utils.hpp" -#include "math/pr/parameter_resolver.hpp" -#include "math/tensor/ops.hpp" -#include "math/tensor/ops/memory_operator.hpp" -#include "math/tensor/tensor.hpp" -#include "math/tensor/traits.hpp" +#include "math/operators/utils.h" +#include "math/pr/parameter_resolver.h" +#include "math/tensor/ops.h" +#include "math/tensor/ops/memory_operator.h" +#include "math/tensor/tensor.h" +#include "math/tensor/traits.h" namespace operators::qubit { namespace tn = tensor; diff --git a/ccsrc/include/math/operators/transform.hpp b/ccsrc/include/math/operators/transform.h similarity index 68% rename from ccsrc/include/math/operators/transform.hpp rename to ccsrc/include/math/operators/transform.h index c3837c56f..b35a82715 100644 --- a/ccsrc/include/math/operators/transform.hpp +++ b/ccsrc/include/math/operators/transform.h @@ -1,16 +1,18 @@ -// Copyright 2023 -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. +/** + * Copyright (c) Huawei Technologies Co., Ltd. 2023. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ #ifndef MATH_OPERATORS_TRANSFORM #define MATH_OPERATORS_TRANSFORM @@ -20,8 +22,8 @@ #include #include -#include "math/operators/fermion_operator_view.hpp" -#include "math/operators/qubit_operator_view.hpp" +#include "math/operators/fermion_operator_view.h" +#include "math/operators/qubit_operator_view.h" namespace operators::transform { namespace tn = tensor; @@ -62,21 +64,22 @@ edge_matrix_t get_edge_matrix(const fermion_op_t& ops); edge_enum_t enumerate_edges(const edge_matrix_t& edge_matrix); -qubit_op_t get_b(int i, const edge_matrix_t& edge_matrix, edge_enum_t& edge_enum); +qubit_op_t get_b(int i, const edge_matrix_t& edge_matrix, const edge_enum_t& edge_enum); -qubit_op_t get_a(int i, int j, const edge_matrix_t& edge_matrix, edge_enum_t& edge_enum); +qubit_op_t get_a(int i, int j, const edge_matrix_t& edge_matrix, const edge_enum_t& edge_enum); -qubit_op_t transformed_number_operator(int i, const edge_matrix_t& edge_matrix, edge_enum_t& edge_enum); +qubit_op_t transformed_number_operator(int i, const edge_matrix_t& edge_matrix, const edge_enum_t& edge_enum); -qubit_op_t transformed_excitation_operator(int i, int j, const edge_matrix_t& edge_matrix, edge_enum_t& edge_enum); +qubit_op_t transformed_excitation_operator(int i, int j, const edge_matrix_t& edge_matrix, + const edge_enum_t& edge_enum); -qubit_op_t transformed_exchange_operator(int i, int j, const edge_matrix_t& edge_matrix, edge_enum_t& edge_enum); +qubit_op_t transformed_exchange_operator(int i, int j, const edge_matrix_t& edge_matrix, const edge_enum_t& edge_enum); qubit_op_t transformed_number_excitation_operator(int i, int j, int k, const edge_matrix_t& edge_matrix, - edge_enum_t& edge_enum); + const edge_enum_t& edge_enum); qubit_op_t transformed_double_excitation_operator(int i, int j, int k, int l, const edge_matrix_t& edge_matrix, - edge_enum_t& edge_enum); + const edge_enum_t& edge_enum); qubit_op_t bravyi_kitaev_superfast(const fermion_op_t& ops); } // namespace operators::transform diff --git a/ccsrc/include/math/operators/utils.hpp b/ccsrc/include/math/operators/utils.h similarity index 79% rename from ccsrc/include/math/operators/utils.hpp rename to ccsrc/include/math/operators/utils.h index e3615cc37..7a445e3ba 100644 --- a/ccsrc/include/math/operators/utils.hpp +++ b/ccsrc/include/math/operators/utils.h @@ -1,16 +1,18 @@ -// Copyright 2023 -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. +/** + * Copyright (c) Huawei Technologies Co., Ltd. 2023. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ #ifndef MATH_OPERATORS_UTILS #define MATH_OPERATORS_UTILS @@ -20,7 +22,7 @@ #include #include -#include "math/pr/parameter_resolver.hpp" +#include "math/pr/parameter_resolver.h" namespace operators { using key_t = std::vector; using value_t = parameter::ParameterResolver; diff --git a/ccsrc/include/math/pr/parameter_resolver.hpp b/ccsrc/include/math/pr/parameter_resolver.h similarity index 90% rename from ccsrc/include/math/pr/parameter_resolver.hpp rename to ccsrc/include/math/pr/parameter_resolver.h index 6a2259c57..36dee930f 100644 --- a/ccsrc/include/math/pr/parameter_resolver.hpp +++ b/ccsrc/include/math/pr/parameter_resolver.h @@ -1,16 +1,18 @@ -// Copyright 2023 -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. +/** + * Copyright (c) Huawei Technologies Co., Ltd. 2023. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ #ifndef MATH_PR_PARAMETER_RESOLVER_HPP_ #define MATH_PR_PARAMETER_RESOLVER_HPP_ @@ -23,14 +25,13 @@ #include #include -#include "config/config.hpp" - -#include "math/tensor/matrix.hpp" -#include "math/tensor/ops.hpp" -#include "math/tensor/ops/memory_operator.hpp" -#include "math/tensor/ops_cpu/memory_operator.hpp" -#include "math/tensor/tensor.hpp" -#include "math/tensor/traits.hpp" +#include "config/config.h" +#include "math/tensor/matrix.h" +#include "math/tensor/ops.h" +#include "math/tensor/ops/memory_operator.h" +#include "math/tensor/ops_cpu/memory_operator.h" +#include "math/tensor/tensor.h" +#include "math/tensor/traits.h" namespace parameter { namespace tn = tensor; diff --git a/ccsrc/include/math/tensor/csr_matrix.hpp b/ccsrc/include/math/tensor/csr_matrix.h similarity index 59% rename from ccsrc/include/math/tensor/csr_matrix.hpp rename to ccsrc/include/math/tensor/csr_matrix.h index 53535cb85..fe9256b63 100644 --- a/ccsrc/include/math/tensor/csr_matrix.hpp +++ b/ccsrc/include/math/tensor/csr_matrix.h @@ -1,16 +1,18 @@ -// Copyright 2023 -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. +/** + * Copyright (c) Huawei Technologies Co., Ltd. 2023. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ #ifndef MATH_TENSOR_CSR_MATRIX_HPP_ #define MATH_TENSOR_CSR_MATRIX_HPP_ @@ -19,8 +21,8 @@ #include #include -#include "math/tensor/tensor.hpp" -#include "math/tensor/traits.hpp" +#include "math/tensor/tensor.h" +#include "math/tensor/traits.h" namespace tensor { struct CsrMatrix { size_t n_row = 0; diff --git a/ccsrc/include/math/tensor/matrix.hpp b/ccsrc/include/math/tensor/matrix.h similarity index 58% rename from ccsrc/include/math/tensor/matrix.hpp rename to ccsrc/include/math/tensor/matrix.h index e78a77fed..a27db77b9 100644 --- a/ccsrc/include/math/tensor/matrix.hpp +++ b/ccsrc/include/math/tensor/matrix.h @@ -1,24 +1,28 @@ -// Copyright 2023 -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. +/** + * Copyright (c) Huawei Technologies Co., Ltd. 2023. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ #ifndef MATH_TENSOR_MATRIX #define MATH_TENSOR_MATRIX +#include +#include #include #include -#include "math/tensor/tensor.hpp" -#include "math/tensor/traits.hpp" +#include "math/tensor/tensor.h" +#include "math/tensor/traits.h" namespace tensor { struct Matrix : public Tensor { @@ -40,20 +44,18 @@ struct Matrix : public Tensor { } std::vector tmp; for (auto& row : m) { - for (auto& data : row) { - tmp.push_back(data); - } + std::copy(row.begin(), row.end(), std::back_inserter(tmp)); } auto t = Tensor(tmp); this->dtype = t.dtype; - this->device = t.device; + this->device = device; this->data = t.data; this->dim = t.dim; t.data = nullptr; } Matrix() = default; - Matrix(TDtype dtype, TDevice device, void* data, size_t n_col, size_t n_row) - : n_col(n_col), n_row(n_row), Tensor(dtype, device, data, n_col * n_row) { + Matrix(TDtype dtype, TDevice device, void* data, size_t n_row, size_t n_col) + : Tensor(dtype, device, data, n_col * n_row), n_row(n_row), n_col(n_col) { } Matrix(Tensor&& other, size_t n_row, size_t n_col) : n_row(n_row), n_col(n_col) { if (n_col * n_row != other.dim) { diff --git a/ccsrc/include/math/tensor/ops.h b/ccsrc/include/math/tensor/ops.h new file mode 100644 index 000000000..ac8551016 --- /dev/null +++ b/ccsrc/include/math/tensor/ops.h @@ -0,0 +1,25 @@ +/** + * Copyright (c) Huawei Technologies Co., Ltd. 2023. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef MATH_TENSOR_OPS_HPP_ +#define MATH_TENSOR_OPS_HPP_ +#include +#include + +#include "math/tensor/ops/advance_math.h" +#include "math/tensor/ops/basic_math.h" +#include "math/tensor/ops/concrete_tensor.h" +#include "math/tensor/ops/memory_operator.h" +#endif diff --git a/ccsrc/include/math/tensor/ops.hpp b/ccsrc/include/math/tensor/ops.hpp deleted file mode 100644 index 94cd416f1..000000000 --- a/ccsrc/include/math/tensor/ops.hpp +++ /dev/null @@ -1,23 +0,0 @@ -// Copyright 2023 -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -#ifndef MATH_TENSOR_OPS_HPP_ -#define MATH_TENSOR_OPS_HPP_ -#include -#include - -#include "math/tensor/ops/advance_math.hpp" -#include "math/tensor/ops/basic_math.hpp" -#include "math/tensor/ops/concrete_tensor.hpp" -#include "math/tensor/ops/memory_operator.hpp" -#endif diff --git a/ccsrc/include/math/tensor/ops/advance_math.hpp b/ccsrc/include/math/tensor/ops/advance_math.h similarity index 64% rename from ccsrc/include/math/tensor/ops/advance_math.hpp rename to ccsrc/include/math/tensor/ops/advance_math.h index e6e3cf20b..ba8d09ef0 100644 --- a/ccsrc/include/math/tensor/ops/advance_math.hpp +++ b/ccsrc/include/math/tensor/ops/advance_math.h @@ -1,25 +1,27 @@ -// Copyright 2023 -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. +/** + * Copyright (c) Huawei Technologies Co., Ltd. 2023. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ #ifndef MATH_TENSOR_OPS_ADVANCE_MATH_HPP #define MATH_TENSOR_OPS_ADVANCE_MATH_HPP #include #include -#include "math/tensor/ops/memory_operator.hpp" -#include "math/tensor/tensor.hpp" -#include "math/tensor/traits.hpp" +#include "math/tensor/ops/memory_operator.h" +#include "math/tensor/tensor.h" +#include "math/tensor/traits.h" namespace tensor::ops { /** diff --git a/ccsrc/include/math/tensor/ops/basic_math.hpp b/ccsrc/include/math/tensor/ops/basic_math.h similarity index 81% rename from ccsrc/include/math/tensor/ops/basic_math.hpp rename to ccsrc/include/math/tensor/ops/basic_math.h index 8c82885db..420d7f6db 100644 --- a/ccsrc/include/math/tensor/ops/basic_math.hpp +++ b/ccsrc/include/math/tensor/ops/basic_math.h @@ -1,26 +1,28 @@ -// Copyright 2023 -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. +/** + * Copyright (c) Huawei Technologies Co., Ltd. 2023. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ #ifndef MATH_TENSOR_OPS_BASIC_MATH_HPP_ #define MATH_TENSOR_OPS_BASIC_MATH_HPP_ #include -#include "math/tensor/csr_matrix.hpp" -#include "math/tensor/matrix.hpp" -#include "math/tensor/tensor.hpp" -#include "math/tensor/traits.hpp" +#include "math/tensor/csr_matrix.h" +#include "math/tensor/matrix.h" +#include "math/tensor/tensor.h" +#include "math/tensor/traits.h" namespace tensor::ops { void inplace_add(Tensor* t, float a); diff --git a/ccsrc/include/math/tensor/ops/concrete_tensor.hpp b/ccsrc/include/math/tensor/ops/concrete_tensor.h similarity index 56% rename from ccsrc/include/math/tensor/ops/concrete_tensor.hpp rename to ccsrc/include/math/tensor/ops/concrete_tensor.h index f2e0e8929..977ae02df 100644 --- a/ccsrc/include/math/tensor/ops/concrete_tensor.hpp +++ b/ccsrc/include/math/tensor/ops/concrete_tensor.h @@ -1,24 +1,26 @@ -// Copyright 2023 -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. +/** + * Copyright (c) Huawei Technologies Co., Ltd. 2023. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ #ifndef MATH_TENSOR_OPS_CONCRETE_TENSOR_HPP_ #define MATH_TENSOR_OPS_CONCRETE_TENSOR_HPP_ #include #include -#include "math/tensor/tensor.hpp" -#include "math/tensor/traits.hpp" +#include "math/tensor/tensor.h" +#include "math/tensor/traits.h" namespace tensor::ops { // Concrete initialize operator diff --git a/ccsrc/include/math/tensor/ops/memory_operator.hpp b/ccsrc/include/math/tensor/ops/memory_operator.h similarity index 76% rename from ccsrc/include/math/tensor/ops/memory_operator.hpp rename to ccsrc/include/math/tensor/ops/memory_operator.h index eaa80e414..41d436ca4 100644 --- a/ccsrc/include/math/tensor/ops/memory_operator.hpp +++ b/ccsrc/include/math/tensor/ops/memory_operator.h @@ -1,16 +1,18 @@ -// Copyright 2023 -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. +/** + * Copyright (c) Huawei Technologies Co., Ltd. 2023. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ #ifndef MATH_TENSOR_OPS_MEMORY_OPERATOR_HPP_ #define MATH_TENSOR_OPS_MEMORY_OPERATOR_HPP_ @@ -20,8 +22,8 @@ #include #include -#include "math/tensor/tensor.hpp" -#include "math/tensor/traits.hpp" +#include "math/tensor/tensor.h" +#include "math/tensor/traits.h" namespace tensor::ops { // Memory operator diff --git a/ccsrc/include/math/tensor/ops_cpu/advance_math.hpp b/ccsrc/include/math/tensor/ops_cpu/advance_math.h similarity index 75% rename from ccsrc/include/math/tensor/ops_cpu/advance_math.hpp rename to ccsrc/include/math/tensor/ops_cpu/advance_math.h index 8fad8cab5..35f6455b6 100644 --- a/ccsrc/include/math/tensor/ops_cpu/advance_math.hpp +++ b/ccsrc/include/math/tensor/ops_cpu/advance_math.h @@ -1,16 +1,18 @@ -// Copyright 2023 -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. +/** + * Copyright (c) Huawei Technologies Co., Ltd. 2023. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ #ifndef MATH_TENSOR_OPS_CPU_ADVANCE_MATH_HPP_ #define MATH_TENSOR_OPS_CPU_ADVANCE_MATH_HPP_ @@ -19,14 +21,14 @@ #include #include -#include "math/tensor/ops/advance_math.hpp" -#include "math/tensor/ops/memory_operator.hpp" -#include "math/tensor/ops_cpu/basic_math.hpp" -#include "math/tensor/ops_cpu/concrete_tensor.hpp" -#include "math/tensor/ops_cpu/memory_operator.hpp" -#include "math/tensor/ops_cpu/utils.hpp" -#include "math/tensor/tensor.hpp" -#include "math/tensor/traits.hpp" +#include "math/tensor/ops/advance_math.h" +#include "math/tensor/ops/memory_operator.h" +#include "math/tensor/ops_cpu/basic_math.h" +#include "math/tensor/ops_cpu/concrete_tensor.h" +#include "math/tensor/ops_cpu/memory_operator.h" +#include "math/tensor/ops_cpu/utils.h" +#include "math/tensor/tensor.h" +#include "math/tensor/traits.h" namespace tensor::ops::cpu { template Tensor real(void* data, size_t len) { @@ -48,6 +50,9 @@ template Tensor imag(void* data, size_t len) { constexpr TDtype real_t = to_real_dtype_t; if constexpr (dtype == real_t) { + if (data == nullptr) { + throw std::runtime_error("data cannot be nullptr."); + } return cpu::zeros(len, dtype); } else { auto out = ops::cpu::init(len); @@ -116,11 +121,12 @@ bool is_all_zero(void* data, size_t len) { auto c_data = reinterpret_cast*>(data); for (size_t i = 0; i < len; i++) { if constexpr (is_complex_v>) { - if (std::real(c_data[i]) != 0 || std::imag(c_data[i]) != 0) { + if ((std::real(c_data[i]) > 0) || (std::real(c_data[i]) < 0) || (std::imag(c_data[i]) > 0) + || (std::imag(c_data[i]) < 0)) { return false; } } else { - if (c_data[i] != 0) { + if ((c_data[i] > 0) || (c_data[i] < 0)) { return false; } } @@ -132,17 +138,17 @@ bool is_all_zero(const Tensor& t); // ----------------------------------------------------------------------------- template bool operator==(T1 a, const std::complex& b) { - return a == b.real(); + return (!(a > b.real())) && (!(a < b.real())); } template bool operator==(const std::complex& a, T2 b) { - return a.real() == b; + return (!(a.real() > b)) && (!(a.real() < b)); } template bool operator==(const std::complex& a, const std::complex b) { - return (a.real() == b.real()) && (a.imag() == b.imag()); + return !(a.real() > b.real()) && !(a.real() < b.real()) && !(a.imag() > b.imag()) && !(a.imag() < b.imag()); } template @@ -155,19 +161,36 @@ std::vector is_equal_to(void* lhs, size_t lhs_len, void* rhs, size_t rhs_l auto c_lhs = reinterpret_cast(lhs); auto c_rhs = reinterpret_cast(rhs); std::vector out; - if (lhs_len == 1) { - for (size_t i = 0; i < rhs_len; i++) { - out.push_back(c_lhs[0] == c_rhs[i]); - } - } else if (rhs_len == 1) { - for (size_t i = 0; i < lhs_len; i++) { - out.push_back(c_lhs[i] == c_rhs[0]); + if constexpr (!is_complex_dtype_v && !is_complex_dtype_v) { + if (lhs_len == 1) { + for (size_t i = 0; i < rhs_len; i++) { + out.push_back(!(c_lhs[0] > c_rhs[i]) && !(c_lhs[0] < c_rhs[i])); + } + } else if (rhs_len == 1) { + for (size_t i = 0; i < lhs_len; i++) { + out.push_back(!(c_lhs[i] > c_rhs[0]) && !(c_lhs[i] < c_rhs[0])); + } + } else { + for (size_t i = 0; i < lhs_len; i++) { + out.push_back(!(c_lhs[i] > c_rhs[i]) && !(c_lhs[i] < c_rhs[i])); + } } } else { - for (size_t i = 0; i < lhs_len; i++) { - out.push_back(c_lhs[i] == c_rhs[i]); + if (lhs_len == 1) { + for (size_t i = 0; i < rhs_len; i++) { + out.push_back(c_lhs[0] == c_rhs[i]); + } + } else if (rhs_len == 1) { + for (size_t i = 0; i < lhs_len; i++) { + out.push_back(c_lhs[i] == c_rhs[0]); + } + } else { + for (size_t i = 0; i < lhs_len; i++) { + out.push_back(c_lhs[i] == c_rhs[i]); + } } } + return out; } @@ -244,6 +267,7 @@ Tensor ElementFunc(const Tensor& t, TDtype out_dtype, F&& func) { } } break; } + return Tensor(); } // ----------------------------------------------------------------------------- diff --git a/ccsrc/include/math/tensor/ops_cpu/basic_math.hpp b/ccsrc/include/math/tensor/ops_cpu/basic_math.h similarity index 92% rename from ccsrc/include/math/tensor/ops_cpu/basic_math.hpp rename to ccsrc/include/math/tensor/ops_cpu/basic_math.h index be985b6ee..81c934b4f 100644 --- a/ccsrc/include/math/tensor/ops_cpu/basic_math.hpp +++ b/ccsrc/include/math/tensor/ops_cpu/basic_math.h @@ -1,16 +1,18 @@ -// Copyright 2023 -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. +/** + * Copyright (c) Huawei Technologies Co., Ltd. 2023. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ #ifndef MATH_TENSOR_OPS_CPU_BASIC_MATH_HPP_ #define MATH_TENSOR_OPS_CPU_BASIC_MATH_HPP_ @@ -19,32 +21,18 @@ #include #include -#include "core/mq_base_types.hpp" -#include "core/utils.hpp" -#include "math/tensor/csr_matrix.hpp" -#include "math/tensor/matrix.hpp" -#include "math/tensor/ops_cpu/concrete_tensor.hpp" -#include "math/tensor/ops_cpu/memory_operator.hpp" -#include "math/tensor/ops_cpu/utils.hpp" -#include "math/tensor/tensor.hpp" -#include "math/tensor/traits.hpp" +#include "config/openmp.h" +#include "core/mq_base_types.h" +#include "core/utils.h" +#include "math/tensor/csr_matrix.h" +#include "math/tensor/matrix.h" +#include "math/tensor/ops_cpu/concrete_tensor.h" +#include "math/tensor/ops_cpu/memory_operator.h" +#include "math/tensor/ops_cpu/utils.h" +#include "math/tensor/tensor.h" +#include "math/tensor/traits.h" namespace tensor::ops::cpu { -template -struct cast_value { - des_t operator()(const src_t& a) const { - if constexpr (std::is_same_v) { - return a; - } else if constexpr (!is_complex_v && is_complex_v) { - return std::real(a); - } else if constexpr (is_complex_v && is_complex_v) { - return {std::real(a), std::imag(a)}; - } else { - return a; - } - } -}; - template class binary_ops> void InplaceBinary(void* data, size_t len, void* other) { @@ -54,7 +42,6 @@ void InplaceBinary(void* data, size_t len, void* other) { auto c_other = reinterpret_cast(other); auto ops = binary_ops<>(); auto caster = cast_value(); - auto first = c_other[0]; for (size_t i = 0; i < len; i++) { if constexpr (is_array) { if constexpr (reverse) { @@ -64,9 +51,9 @@ void InplaceBinary(void* data, size_t len, void* other) { } } else { if constexpr (reverse) { - c_data[i] = ops(caster(first), c_data[i]); + c_data[i] = ops(caster(c_other[0]), c_data[i]); } else { - c_data[i] = ops(c_data[i], caster(first)); + c_data[i] = ops(c_data[i], caster(c_other[0])); } } } @@ -83,7 +70,6 @@ Tensor GenerateBinary(void* data, size_t len, void* other) { auto ops = binary_ops<>(); auto caster0 = cast_value, to_device_t>(); auto caster1 = cast_value, to_device_t>(); - auto first = c_other[0]; for (size_t i = 0; i < len; i++) { if constexpr (is_array) { if constexpr (reverse) { @@ -93,9 +79,9 @@ Tensor GenerateBinary(void* data, size_t len, void* other) { } } else { if constexpr (reverse) { - c_des[i] = ops(caster1(first), caster0(c_data[i])); + c_des[i] = ops(caster1(c_other[0]), caster0(c_data[i])); } else { - c_des[i] = ops(caster0(c_data[i]), caster1(first)); + c_des[i] = ops(caster0(c_data[i]), caster1(c_other[0])); } } } @@ -174,6 +160,7 @@ Tensor generate_binary(void* data, TDtype dtype, size_t len, T a) { return GenerateBinary(data, len, other); } } + return Tensor(); } // vector = number + vector @@ -195,6 +182,7 @@ Tensor generate_binary_rev(void* data, TDtype dtype, size_t len, T a) { return GenerateBinary(data, len, other); } } + return Tensor(); } // ----------------------------------------------------------------------------- @@ -267,6 +255,7 @@ Tensor generate_binary_array(void* data, TDtype dtype, size_t len, void* other) return GenerateBinary(data, len, other); } } + return Tensor(); } // vector = vector2 + vector1 @@ -287,6 +276,7 @@ Tensor generate_binary_array_rev(void* data, TDtype dtype, size_t len, void* oth return GenerateBinary(data, len, other); } } + return Tensor(); } // ----------------------------------------------------------------------------- @@ -462,6 +452,7 @@ Tensor generate_binary_array(void* data, TDtype src, size_t len, const Tensor& a } else { throw std::runtime_error("Dimension miss match."); } + return Tensor(); } template