From b368a329e95a9af2ecc88947826eee749425c4f3 Mon Sep 17 00:00:00 2001 From: "Lee J. O'Riordan" Date: Fri, 8 Oct 2021 12:36:28 +0100 Subject: [PATCH 01/45] Enable clang-tidy in CI checks --- .github/workflows/format.yml | 21 +++++++++++++++++++++ CMakeLists.txt | 10 ++++++++++ 2 files changed, 31 insertions(+) diff --git a/.github/workflows/format.yml b/.github/workflows/format.yml index d1dc026f22..8e1c9dde0e 100644 --- a/.github/workflows/format.yml +++ b/.github/workflows/format.yml @@ -32,6 +32,27 @@ jobs: - name: Run Black run: black -l 100 pennylane_lightning/ --check + tidy-cpp: + name: Tidy (C++) + runs-on: ubuntu-20.04 + + steps: + - name: Cancel previous runs + uses: styfle/cancel-workflow-action@0.4.1 + with: + access_token: ${{ github.token }} + + - name: Install dependencies + run: sudo apt update && sudo apt -y install clang-tidy-11 python3 cmake g++ + + - name: Checkout code + uses: actions/checkout@v2 + + - name: Run clang-tidy compilation + run: | + cmake -BBuild -DENABLE_CLANG_TIDY=on . + cmake --build ./Build + format-cpp: name: Format (C++) runs-on: ubuntu-20.04 diff --git a/CMakeLists.txt b/CMakeLists.txt index 6b8b0f5354..dfea9f746c 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -29,6 +29,16 @@ endif() option(ENABLE_NATIVE "Enable native CPU build tuning" OFF) option(BUILD_TESTS "Build cpp tests" OFF) option(ENABLE_WARNINGS "Enable warnings" ON) +option(ENABLE_CLANG_TIDY "Enable clang-tidy build checks" OFF) + +if(ENABLE_CLANG_TIDY) + set(CMAKE_CXX_CLANG_TIDY clang-tidy; + -extra-arg=-std=c++17; + -warnings-as-errors=*; + -header-filter=.*; + -checks=-*,-llvmlibc-*,modernize-*,clang-analyzer-cplusplus*,openmp-*,performance-*,portability-*,readability-*; + ) +endif() # Add pybind11 include(FetchContent) From aeda5907e5ac146674fe3807cb3b4c9064547d2b Mon Sep 17 00:00:00 2001 From: "Lee J. O'Riordan" Date: Fri, 8 Oct 2021 13:53:27 +0100 Subject: [PATCH 02/45] Update clang-tidy binary name --- .github/workflows/format.yml | 3 ++- CMakeLists.txt | 5 ++++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/.github/workflows/format.yml b/.github/workflows/format.yml index 8e1c9dde0e..6b69ffadef 100644 --- a/.github/workflows/format.yml +++ b/.github/workflows/format.yml @@ -44,13 +44,14 @@ jobs: - name: Install dependencies run: sudo apt update && sudo apt -y install clang-tidy-11 python3 cmake g++ + env: DEBIAN_FRONTEND=noninteractive - name: Checkout code uses: actions/checkout@v2 - name: Run clang-tidy compilation run: | - cmake -BBuild -DENABLE_CLANG_TIDY=on . + cmake -BBuild -DENABLE_CLANG_TIDY=on -DCLANT_TIDY_BINARY=clang-tidy-11 . cmake --build ./Build format-cpp: diff --git a/CMakeLists.txt b/CMakeLists.txt index dfea9f746c..c3146c8223 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -32,7 +32,10 @@ option(ENABLE_WARNINGS "Enable warnings" ON) option(ENABLE_CLANG_TIDY "Enable clang-tidy build checks" OFF) if(ENABLE_CLANG_TIDY) - set(CMAKE_CXX_CLANG_TIDY clang-tidy; + if (NOT DEFINED CLANG_TIDY_BINARY) + set(CLANG_TIDY_BINARY clang-tidy) + endif() + set(CMAKE_CXX_CLANG_TIDY ${CLANG_TIDY_BINARY}; -extra-arg=-std=c++17; -warnings-as-errors=*; -header-filter=.*; From e530112ef47900673f62787e4043021deba188d4 Mon Sep 17 00:00:00 2001 From: "Lee J. O'Riordan" Date: Fri, 8 Oct 2021 13:57:09 +0100 Subject: [PATCH 03/45] Ensure formatting run within PRs --- .github/workflows/format.yml | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/.github/workflows/format.yml b/.github/workflows/format.yml index 6b69ffadef..a873f5166d 100644 --- a/.github/workflows/format.yml +++ b/.github/workflows/format.yml @@ -1,12 +1,15 @@ name: Formatting check on: pull_request: - push: - branches: - - master - paths: - - "pennylane_lightning/**" - - "tests/**" + paths: + - "pennylane_lightning/**" + - "tests/**" + push: + branches: + - master + paths: + - "pennylane_lightning/**" + - "tests/**" jobs: black: From 4b996070279883d29e822d778a2818dc7a7e966b Mon Sep 17 00:00:00 2001 From: "Lee J. O'Riordan" Date: Fri, 8 Oct 2021 13:58:59 +0100 Subject: [PATCH 04/45] Remove path details from CI --- .github/workflows/format.yml | 6 ------ 1 file changed, 6 deletions(-) diff --git a/.github/workflows/format.yml b/.github/workflows/format.yml index a873f5166d..c049712b63 100644 --- a/.github/workflows/format.yml +++ b/.github/workflows/format.yml @@ -1,15 +1,9 @@ name: Formatting check on: pull_request: - paths: - - "pennylane_lightning/**" - - "tests/**" push: branches: - master - paths: - - "pennylane_lightning/**" - - "tests/**" jobs: black: From df8751dac362539753da69e4a8842cae064d0396 Mon Sep 17 00:00:00 2001 From: "Lee J. O'Riordan" Date: Fri, 8 Oct 2021 14:29:13 +0100 Subject: [PATCH 05/45] Fix envvar for Github Actions --- .github/workflows/format.yml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.github/workflows/format.yml b/.github/workflows/format.yml index c049712b63..aa419e8fdc 100644 --- a/.github/workflows/format.yml +++ b/.github/workflows/format.yml @@ -41,7 +41,8 @@ jobs: - name: Install dependencies run: sudo apt update && sudo apt -y install clang-tidy-11 python3 cmake g++ - env: DEBIAN_FRONTEND=noninteractive + env: + DEBIAN_FRONTEND: noninteractive - name: Checkout code uses: actions/checkout@v2 From 16e8787d17b620eb2a7b99dd4271620217b10f6c Mon Sep 17 00:00:00 2001 From: "Lee J. O'Riordan" Date: Fri, 8 Oct 2021 14:31:08 +0100 Subject: [PATCH 06/45] Fix fix binary path for tidy --- .github/workflows/format.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/format.yml b/.github/workflows/format.yml index aa419e8fdc..80218b0422 100644 --- a/.github/workflows/format.yml +++ b/.github/workflows/format.yml @@ -49,7 +49,7 @@ jobs: - name: Run clang-tidy compilation run: | - cmake -BBuild -DENABLE_CLANG_TIDY=on -DCLANT_TIDY_BINARY=clang-tidy-11 . + cmake -BBuild -DENABLE_CLANG_TIDY=on -DCLANG_TIDY_BINARY=clang-tidy-11 . cmake --build ./Build format-cpp: From ab2771c186e4c36341338b03a43a0d5df0fa09a0 Mon Sep 17 00:00:00 2001 From: "Lee J. O'Riordan" Date: Fri, 8 Oct 2021 14:44:08 +0100 Subject: [PATCH 07/45] Favour trailing return type in gate definition templates --- pennylane_lightning/src/simulator/Gates.hpp | 74 +++++++++++---------- 1 file changed, 38 insertions(+), 36 deletions(-) diff --git a/pennylane_lightning/src/simulator/Gates.hpp b/pennylane_lightning/src/simulator/Gates.hpp index 3a74d24ad4..9485878b44 100644 --- a/pennylane_lightning/src/simulator/Gates.hpp +++ b/pennylane_lightning/src/simulator/Gates.hpp @@ -23,7 +23,7 @@ namespace Gates { * @return constexpr std::vector> Return constant expression of * PauliX data. */ -template static constexpr std::vector> getPauliX() { +template static constexpr auto getPauliX() -> std::vector> { return {ZERO(), ONE(), ONE(), ZERO()}; } @@ -35,7 +35,7 @@ template static constexpr std::vector> getPauliX() { * @return constexpr std::vector> Return constant expression of * PauliY data. */ -template static constexpr std::vector> getPauliY() { +template static constexpr auto getPauliY() -> std::vector> { return {ZERO(), -IMAG(), IMAG(), ZERO()}; } @@ -47,7 +47,7 @@ template static constexpr std::vector> getPauliY() { * @return constexpr std::vector> Return constant expression of * PauliZ data. */ -template static constexpr std::vector> getPauliZ() { +template static constexpr auto getPauliZ() -> std::vector> { return {ONE(), ZERO(), ZERO(), -ONE()}; } @@ -59,7 +59,7 @@ template static constexpr std::vector> getPauliZ() { * @return constexpr std::vector> Return constant expression of * Hadamard data. */ -template static constexpr std::vector> getHadamard() { +template static constexpr auto getHadamard() -> std::vector> { return {INVSQRT2(), INVSQRT2(), INVSQRT2(), -INVSQRT2()}; } @@ -70,7 +70,7 @@ template static constexpr std::vector> getHadamard() { * @return constexpr std::vector> Return constant expression of * S gate data. */ -template static constexpr std::vector> getS() { +template static constexpr auto getS() -> std::vector> { return {ONE(), ZERO(), ZERO(), IMAG()}; } @@ -81,7 +81,7 @@ template static constexpr std::vector> getS() { * @return constexpr std::vector> Return constant expression of * T gate data. */ -template static constexpr std::vector> getT() { +template static constexpr auto getT() -> std::vector> { return {ONE(), ZERO(), ZERO(), IMAG()}; } @@ -93,7 +93,7 @@ template static constexpr std::vector> getT() { * @return constexpr std::vector> Return constant expression of * CNOT gate data. */ -template static constexpr std::vector> getCNOT() { +template static constexpr auto getCNOT() -> std::vector> { return {ONE(), ZERO(), ZERO(), ZERO(), ZERO(), ONE(), ZERO(), ZERO(), ZERO(), ZERO(), ZERO(), ONE(), ZERO(), ZERO(), ONE(), ZERO()}; @@ -107,7 +107,7 @@ template static constexpr std::vector> getCNOT() { * @return constexpr std::vector> Return constant expression of * SWAP gate data. */ -template static constexpr std::vector> getSWAP() { +template static constexpr auto getSWAP() -> std::vector> { return {ONE(), ZERO(), ZERO(), ZERO(), ZERO(), ZERO(), ONE(), ZERO(), ZERO(), ONE(), ZERO(), ZERO(), ZERO(), ZERO(), ZERO(), ONE()}; @@ -121,7 +121,7 @@ template static constexpr std::vector> getSWAP() { * @return constexpr std::vector> Return constant expression of * SWAP gate data. */ -template static constexpr std::vector> getCZ() { +template static constexpr auto getCZ() -> std::vector> { return {ONE(), ZERO(), ZERO(), ZERO(), ZERO(), ONE(), ZERO(), ZERO(), ZERO(), ZERO(), ONE(), ZERO(), ZERO(), ZERO(), ZERO(), -ONE()}; @@ -135,7 +135,7 @@ template static constexpr std::vector> getCZ() { * @return constexpr std::vector> Return constant expression of * CSWAP gate data. */ -template static constexpr std::vector> getCSWAP() { +template static constexpr auto getCSWAP() -> std::vector> { return {ONE(), ZERO(), ZERO(), ZERO(), ZERO(), ZERO(), ZERO(), ZERO(), ZERO(), ONE(), ZERO(), ZERO(), ZERO(), ZERO(), ZERO(), ZERO(), ZERO(), ZERO(), @@ -157,7 +157,7 @@ template static constexpr std::vector> getCSWAP() { * @return constexpr std::vector> Return constant expression of * Toffoli gate data. */ -template static constexpr std::vector> getToffoli() { +template static constexpr auto getToffoli() -> std::vector> { return {ONE(), ZERO(), ZERO(), ZERO(), ZERO(), ZERO(), ZERO(), ZERO(), ZERO(), ONE(), ZERO(), ZERO(), ZERO(), ZERO(), ZERO(), ZERO(), ZERO(), ZERO(), @@ -182,7 +182,7 @@ template static constexpr std::vector> getToffoli() { * data. */ template -static const std::vector> getPhaseShift(U angle) { +static auto getPhaseShift(U angle) -> const std::vector> { return {ONE(), ZERO(), ZERO(), std::exp(IMAG() * angle)}; } @@ -197,8 +197,8 @@ static const std::vector> getPhaseShift(U angle) { * data. */ template -static const std::vector> -getPhaseShift(const std::vector ¶ms) { +static auto +getPhaseShift(const std::vector ¶ms) -> const std::vector> { return getPhaseShift(params.front()); } @@ -212,7 +212,7 @@ getPhaseShift(const std::vector ¶ms) { * @return const std::vector> Return const RX gate data. */ template -static const std::vector> getRX(U angle) { +static auto getRX(U angle) -> const std::vector> { const std::complex c(std::cos(angle / 2), 0); const std::complex js(0, -std::sin(angle / 2)); return {c, js, js, c}; @@ -228,7 +228,7 @@ static const std::vector> getRX(U angle) { * @return const std::vector> Return const RX gate data. */ template -static const std::vector> getRX(const std::vector ¶ms) { +static auto getRX(const std::vector ¶ms) -> const std::vector> { return getRX(params.front()); } @@ -242,7 +242,7 @@ static const std::vector> getRX(const std::vector ¶ms) { * @return const std::vector> Return const RY gate data. */ template -static const std::vector> getRY(U angle) { +static auto getRY(U angle) -> const std::vector> { const std::complex c(std::cos(angle / 2), 0); const std::complex s(std::sin(angle / 2), 0); return {c, -s, s, c}; @@ -258,7 +258,7 @@ static const std::vector> getRY(U angle) { * @return const std::vector> Return const RY gate data. */ template -static const std::vector> getRY(const std::vector ¶ms) { +static auto getRY(const std::vector ¶ms) -> const std::vector> { return getRY(params.front()); } @@ -272,7 +272,7 @@ static const std::vector> getRY(const std::vector ¶ms) { * @return const std::vector> Return const RZ gate data. */ template -static const std::vector> getRZ(U angle) { +static auto getRZ(U angle) -> const std::vector> { return {std::exp(-IMAG() * (angle / 2)), ZERO(), ZERO(), std::exp(IMAG() * (angle / 2))}; } @@ -287,7 +287,7 @@ static const std::vector> getRZ(U angle) { * @return const std::vector> Return const RZ gate data. */ template -static const std::vector getRZ(const std::vector ¶ms) { +static auto getRZ(const std::vector ¶ms) -> const std::vector { return getRZ(params.front()); } @@ -310,9 +310,11 @@ e^{-i(\phi-\omega)/2}\sin(\theta/2) & e^{i(\phi+\omega)/2}\cos(\theta/2) * @return const std::vector> Return const Rot gate data. */ template -static const std::vector> getRot(U phi, U theta, U omega) { - const std::complex c(std::cos(theta / 2), 0), s(std::sin(theta / 2), 0); - const U p{phi + omega}, m{phi - omega}; +static auto getRot(U phi, U theta, U omega) -> const std::vector> { + const std::complex c(std::cos(theta / 2), 0); + const std::complex s(std::sin(theta / 2), 0); + const U p{phi + omega}; + const U m{phi - omega}; return {std::exp(static_cast(p / 2) * (-IMAG())) * c, -std::exp(static_cast(m / 2) * IMAG()) * s, std::exp(static_cast(m / 2) * (-IMAG())) * s, @@ -337,7 +339,7 @@ e^{-i(\phi-\omega)/2}\sin(\theta/2) & e^{i(\phi+\omega)/2}\cos(\theta/2) * @return const std::vector> Return const Rot gate data. */ template -static const std::vector> getRot(const std::vector ¶ms) { +static auto getRot(const std::vector ¶ms) -> const std::vector> { return getRot(params[0], params[1], params[2]); } @@ -351,7 +353,7 @@ static const std::vector> getRot(const std::vector ¶ms) { * @return const std::vector> Return const RX gate data. */ template -static const std::vector> getCRX(U angle) { +static auto getCRX(U angle) -> const std::vector> { const std::complex rx{getRX(angle)}; return {ONE(), ZERO(), ZERO(), ZERO(), ZERO(), ONE(), ZERO(), ZERO(), ZERO(), ZERO(), rx[0], rx[1], @@ -368,7 +370,7 @@ static const std::vector> getCRX(U angle) { * @return const std::vector> Return const RX gate data. */ template -static const std::vector> getCRX(const std::vector ¶ms) { +static auto getCRX(const std::vector ¶ms) -> const std::vector> { return getCRX(params.front()); } @@ -382,7 +384,7 @@ static const std::vector> getCRX(const std::vector ¶ms) { * @return const std::vector> Return const RY gate data. */ template -static const std::vector> getCRY(U angle) { +static auto getCRY(U angle) -> const std::vector> { const std::complex ry{getRY(angle)}; return {ONE(), ZERO(), ZERO(), ZERO(), ZERO(), ONE(), ZERO(), ZERO(), ZERO(), ZERO(), ry[0], ry[1], @@ -399,7 +401,7 @@ static const std::vector> getCRY(U angle) { * @return const std::vector> Return const RY gate data. */ template -static const std::vector> getCRY(const std::vector ¶ms) { +static auto getCRY(const std::vector ¶ms) -> const std::vector> { return getCRY(params.front()); } @@ -413,7 +415,7 @@ static const std::vector> getCRY(const std::vector ¶ms) { * @return const std::vector> Return const RZ gate data. */ template -static const std::vector> getCRZ(U angle) { +static auto getCRZ(U angle) -> const std::vector> { const std::complex first = std::exp(-IMAG() * (angle / 2)); const std::complex second = std::exp(IMAG() * (angle / 2)); return {ONE(), ZERO(), ZERO(), ZERO(), ZERO(), @@ -431,7 +433,7 @@ static const std::vector> getCRZ(U angle) { * @return const std::vector> Return const RZ gate data. */ template -static const std::vector> getCRZ(const std::vector ¶ms) { +static auto getCRZ(const std::vector ¶ms) -> const std::vector> { return getCRZ(params.front()); } @@ -442,7 +444,7 @@ row-major format. * @see `getRot(U phi, U theta, U omega)`. */ template -static const std::vector> getCRot(U phi, U theta, U omega) { +static auto getCRot(U phi, U theta, U omega) -> const std::vector> { const std::vector> rot{ std::move(getRot(phi, theta, omega))}; return {ONE(), ZERO(), ZERO(), ZERO(), ZERO(), ONE(), @@ -457,8 +459,8 @@ row-major format. * @see `getRot(const std::vector ¶ms)`. */ template -static const std::vector> -getCRot(const std::vector ¶ms) { +static auto +getCRot(const std::vector ¶ms) -> const std::vector> { return getCRot(params[0], params[1], params[2]); } @@ -469,7 +471,7 @@ in row-major format. * @see `getPhaseShift(U angle)`. */ template -static const std::vector> getControlledPhaseShift(U angle) { +static auto getControlledPhaseShift(U angle) -> const std::vector> { return {ONE(), ZERO(), ZERO(), ZERO(), ZERO(), ONE(), ZERO(), ZERO(), ZERO(), ZERO(), ONE(), ZERO(), @@ -483,8 +485,8 @@ in row-major format. * @see `getPhaseShift(const std::vector ¶ms)`. */ template -static const std::vector> -getControlledPhaseShift(const std::vector ¶ms) { +static auto +getControlledPhaseShift(const std::vector ¶ms) -> const std::vector> { return getControlledPhaseShift(params.front()); } From 44661756f6b0d494548fc72006bae2c52f17b321 Mon Sep 17 00:00:00 2001 From: "Lee J. O'Riordan" Date: Fri, 8 Oct 2021 14:50:52 +0100 Subject: [PATCH 08/45] Fix formatting after tidying --- pennylane_lightning/src/simulator/Gates.hpp | 72 +++++++++++++-------- 1 file changed, 46 insertions(+), 26 deletions(-) diff --git a/pennylane_lightning/src/simulator/Gates.hpp b/pennylane_lightning/src/simulator/Gates.hpp index 9485878b44..f2eb4f612a 100644 --- a/pennylane_lightning/src/simulator/Gates.hpp +++ b/pennylane_lightning/src/simulator/Gates.hpp @@ -23,7 +23,8 @@ namespace Gates { * @return constexpr std::vector> Return constant expression of * PauliX data. */ -template static constexpr auto getPauliX() -> std::vector> { +template +static constexpr auto getPauliX() -> std::vector> { return {ZERO(), ONE(), ONE(), ZERO()}; } @@ -35,7 +36,8 @@ template static constexpr auto getPauliX() -> std::vector> Return constant expression of * PauliY data. */ -template static constexpr auto getPauliY() -> std::vector> { +template +static constexpr auto getPauliY() -> std::vector> { return {ZERO(), -IMAG(), IMAG(), ZERO()}; } @@ -47,7 +49,8 @@ template static constexpr auto getPauliY() -> std::vector> Return constant expression of * PauliZ data. */ -template static constexpr auto getPauliZ() -> std::vector> { +template +static constexpr auto getPauliZ() -> std::vector> { return {ONE(), ZERO(), ZERO(), -ONE()}; } @@ -59,7 +62,8 @@ template static constexpr auto getPauliZ() -> std::vector> Return constant expression of * Hadamard data. */ -template static constexpr auto getHadamard() -> std::vector> { +template +static constexpr auto getHadamard() -> std::vector> { return {INVSQRT2(), INVSQRT2(), INVSQRT2(), -INVSQRT2()}; } @@ -70,7 +74,8 @@ template static constexpr auto getHadamard() -> std::vector> Return constant expression of * S gate data. */ -template static constexpr auto getS() -> std::vector> { +template +static constexpr auto getS() -> std::vector> { return {ONE(), ZERO(), ZERO(), IMAG()}; } @@ -81,7 +86,8 @@ template static constexpr auto getS() -> std::vector> * @return constexpr std::vector> Return constant expression of * T gate data. */ -template static constexpr auto getT() -> std::vector> { +template +static constexpr auto getT() -> std::vector> { return {ONE(), ZERO(), ZERO(), IMAG()}; } @@ -93,7 +99,8 @@ template static constexpr auto getT() -> std::vector> * @return constexpr std::vector> Return constant expression of * CNOT gate data. */ -template static constexpr auto getCNOT() -> std::vector> { +template +static constexpr auto getCNOT() -> std::vector> { return {ONE(), ZERO(), ZERO(), ZERO(), ZERO(), ONE(), ZERO(), ZERO(), ZERO(), ZERO(), ZERO(), ONE(), ZERO(), ZERO(), ONE(), ZERO()}; @@ -107,7 +114,8 @@ template static constexpr auto getCNOT() -> std::vector> Return constant expression of * SWAP gate data. */ -template static constexpr auto getSWAP() -> std::vector> { +template +static constexpr auto getSWAP() -> std::vector> { return {ONE(), ZERO(), ZERO(), ZERO(), ZERO(), ZERO(), ONE(), ZERO(), ZERO(), ONE(), ZERO(), ZERO(), ZERO(), ZERO(), ZERO(), ONE()}; @@ -121,7 +129,8 @@ template static constexpr auto getSWAP() -> std::vector> Return constant expression of * SWAP gate data. */ -template static constexpr auto getCZ() -> std::vector> { +template +static constexpr auto getCZ() -> std::vector> { return {ONE(), ZERO(), ZERO(), ZERO(), ZERO(), ONE(), ZERO(), ZERO(), ZERO(), ZERO(), ONE(), ZERO(), ZERO(), ZERO(), ZERO(), -ONE()}; @@ -135,7 +144,8 @@ template static constexpr auto getCZ() -> std::vector> * @return constexpr std::vector> Return constant expression of * CSWAP gate data. */ -template static constexpr auto getCSWAP() -> std::vector> { +template +static constexpr auto getCSWAP() -> std::vector> { return {ONE(), ZERO(), ZERO(), ZERO(), ZERO(), ZERO(), ZERO(), ZERO(), ZERO(), ONE(), ZERO(), ZERO(), ZERO(), ZERO(), ZERO(), ZERO(), ZERO(), ZERO(), @@ -157,7 +167,8 @@ template static constexpr auto getCSWAP() -> std::vector> Return constant expression of * Toffoli gate data. */ -template static constexpr auto getToffoli() -> std::vector> { +template +static constexpr auto getToffoli() -> std::vector> { return {ONE(), ZERO(), ZERO(), ZERO(), ZERO(), ZERO(), ZERO(), ZERO(), ZERO(), ONE(), ZERO(), ZERO(), ZERO(), ZERO(), ZERO(), ZERO(), ZERO(), ZERO(), @@ -197,8 +208,8 @@ static auto getPhaseShift(U angle) -> const std::vector> { * data. */ template -static auto -getPhaseShift(const std::vector ¶ms) -> const std::vector> { +static auto getPhaseShift(const std::vector ¶ms) + -> const std::vector> { return getPhaseShift(params.front()); } @@ -228,7 +239,8 @@ static auto getRX(U angle) -> const std::vector> { * @return const std::vector> Return const RX gate data. */ template -static auto getRX(const std::vector ¶ms) -> const std::vector> { +static auto getRX(const std::vector ¶ms) + -> const std::vector> { return getRX(params.front()); } @@ -258,7 +270,8 @@ static auto getRY(U angle) -> const std::vector> { * @return const std::vector> Return const RY gate data. */ template -static auto getRY(const std::vector ¶ms) -> const std::vector> { +static auto getRY(const std::vector ¶ms) + -> const std::vector> { return getRY(params.front()); } @@ -310,7 +323,8 @@ e^{-i(\phi-\omega)/2}\sin(\theta/2) & e^{i(\phi+\omega)/2}\cos(\theta/2) * @return const std::vector> Return const Rot gate data. */ template -static auto getRot(U phi, U theta, U omega) -> const std::vector> { +static auto getRot(U phi, U theta, U omega) + -> const std::vector> { const std::complex c(std::cos(theta / 2), 0); const std::complex s(std::sin(theta / 2), 0); const U p{phi + omega}; @@ -339,7 +353,8 @@ e^{-i(\phi-\omega)/2}\sin(\theta/2) & e^{i(\phi+\omega)/2}\cos(\theta/2) * @return const std::vector> Return const Rot gate data. */ template -static auto getRot(const std::vector ¶ms) -> const std::vector> { +static auto getRot(const std::vector ¶ms) + -> const std::vector> { return getRot(params[0], params[1], params[2]); } @@ -370,7 +385,8 @@ static auto getCRX(U angle) -> const std::vector> { * @return const std::vector> Return const RX gate data. */ template -static auto getCRX(const std::vector ¶ms) -> const std::vector> { +static auto getCRX(const std::vector ¶ms) + -> const std::vector> { return getCRX(params.front()); } @@ -401,7 +417,8 @@ static auto getCRY(U angle) -> const std::vector> { * @return const std::vector> Return const RY gate data. */ template -static auto getCRY(const std::vector ¶ms) -> const std::vector> { +static auto getCRY(const std::vector ¶ms) + -> const std::vector> { return getCRY(params.front()); } @@ -433,7 +450,8 @@ static auto getCRZ(U angle) -> const std::vector> { * @return const std::vector> Return const RZ gate data. */ template -static auto getCRZ(const std::vector ¶ms) -> const std::vector> { +static auto getCRZ(const std::vector ¶ms) + -> const std::vector> { return getCRZ(params.front()); } @@ -444,7 +462,8 @@ row-major format. * @see `getRot(U phi, U theta, U omega)`. */ template -static auto getCRot(U phi, U theta, U omega) -> const std::vector> { +static auto getCRot(U phi, U theta, U omega) + -> const std::vector> { const std::vector> rot{ std::move(getRot(phi, theta, omega))}; return {ONE(), ZERO(), ZERO(), ZERO(), ZERO(), ONE(), @@ -459,8 +478,8 @@ row-major format. * @see `getRot(const std::vector ¶ms)`. */ template -static auto -getCRot(const std::vector ¶ms) -> const std::vector> { +static auto getCRot(const std::vector ¶ms) + -> const std::vector> { return getCRot(params[0], params[1], params[2]); } @@ -471,7 +490,8 @@ in row-major format. * @see `getPhaseShift(U angle)`. */ template -static auto getControlledPhaseShift(U angle) -> const std::vector> { +static auto getControlledPhaseShift(U angle) + -> const std::vector> { return {ONE(), ZERO(), ZERO(), ZERO(), ZERO(), ONE(), ZERO(), ZERO(), ZERO(), ZERO(), ONE(), ZERO(), @@ -485,8 +505,8 @@ in row-major format. * @see `getPhaseShift(const std::vector ¶ms)`. */ template -static auto -getControlledPhaseShift(const std::vector ¶ms) -> const std::vector> { +static auto getControlledPhaseShift(const std::vector ¶ms) + -> const std::vector> { return getControlledPhaseShift(params.front()); } From a300c19b76ac1599a84a2892bd489f0afc7d8102 Mon Sep 17 00:00:00 2001 From: "Lee J. O'Riordan" Date: Fri, 8 Oct 2021 14:51:15 +0100 Subject: [PATCH 09/45] Ensure consistent use of trailing returns --- pennylane_lightning/src/util/Util.hpp | 88 +++++++++++++++------------ 1 file changed, 49 insertions(+), 39 deletions(-) diff --git a/pennylane_lightning/src/util/Util.hpp b/pennylane_lightning/src/util/Util.hpp index 784e0e1156..247c702acc 100644 --- a/pennylane_lightning/src/util/Util.hpp +++ b/pennylane_lightning/src/util/Util.hpp @@ -40,7 +40,6 @@ /// @endcond namespace Pennylane { - namespace Util { /** @@ -53,7 +52,8 @@ namespace Util { * @return constexpr std::complex */ template -inline static constexpr std::complex ConstMult(U a, std::complex b) { +inline static constexpr auto ConstMult(U a, std::complex b) + -> std::complex { return {a * b.real(), a * b.imag()}; } @@ -67,14 +67,14 @@ inline static constexpr std::complex ConstMult(U a, std::complex b) { * @return constexpr std::complex */ template -inline static constexpr std::complex ConstMult(std::complex a, - std::complex b) { +inline static constexpr auto ConstMult(std::complex a, std::complex b) + -> std::complex { return {a.real() * b.real() - a.imag() * b.imag(), a.real() * b.imag() + a.imag() * b.real()}; } template -inline static constexpr std::complex ConstMultConj(std::complex a, - std::complex b) { +inline static constexpr auto ConstMultConj(std::complex a, std::complex b) + -> std::complex { return {a.real() * b.real() + a.imag() * b.imag(), -a.imag() * b.real() + a.real() * b.imag()}; } @@ -89,8 +89,8 @@ inline static constexpr std::complex ConstMultConj(std::complex a, * @return constexpr std::complex */ template -inline static constexpr std::complex ConstSum(std::complex a, - std::complex b) { +inline static constexpr auto ConstSum(std::complex a, std::complex b) + -> std::complex { return a + b; } @@ -100,7 +100,7 @@ inline static constexpr std::complex ConstSum(std::complex a, * @tparam T Floating point precision type. Accepts `double` and `float`. * @return constexpr std::complex{1,0} */ -template inline static constexpr std::complex ONE() { +template inline static constexpr auto ONE() -> std::complex { return {1, 0}; } @@ -110,7 +110,7 @@ template inline static constexpr std::complex ONE() { * @tparam T Floating point precision type. Accepts `double` and `float`. * @return constexpr std::complex{0,0} */ -template inline static constexpr std::complex ZERO() { +template inline static constexpr auto ZERO() -> std::complex { return {0, 0}; } @@ -120,7 +120,7 @@ template inline static constexpr std::complex ZERO() { * @tparam T Floating point precision type. Accepts `double` and `float`. * @return constexpr std::complex{0,1} */ -template inline static constexpr std::complex IMAG() { +template inline static constexpr auto IMAG() -> std::complex { return {0, 1}; } @@ -130,9 +130,9 @@ template inline static constexpr std::complex IMAG() { * @tparam T Precision of result. `double`, `float` are accepted values. * @return constexpr T sqrt(2) */ -template inline static constexpr T SQRT2() { +template inline static constexpr auto SQRT2() -> T { if constexpr (std::is_same_v) { - return {0x1.6a09e6p+0f}; + return {0x1.6a09e6p+0F}; } else { return {0x1.6a09e667f3bcdp+0}; } @@ -144,7 +144,7 @@ template inline static constexpr T SQRT2() { * @tparam T Precision of result. `double`, `float` are accepted values. * @return constexpr T 1/sqrt(2) */ -template inline static constexpr T INVSQRT2() { +template inline static constexpr auto INVSQRT2() -> T { return {1 / SQRT2()}; } @@ -154,7 +154,9 @@ template inline static constexpr T INVSQRT2() { * @param n the exponent * @return value of 2^n */ -inline size_t exp2(const size_t &n) { return static_cast(1) << n; } +inline auto exp2(const size_t &n) -> size_t { + return static_cast(1) << n; +} /** * @brief Log2 calculation. @@ -162,7 +164,7 @@ inline size_t exp2(const size_t &n) { return static_cast(1) << n; } * @param value Value to calculate for. * @return size_t */ -inline size_t log2(size_t value) { +inline auto log2(size_t value) -> size_t { return static_cast(std::log2(value)); } @@ -173,7 +175,7 @@ inline size_t log2(size_t value) { * @param qubits the number of qubits in the circuit * @return decimal value for the qubit at specified index */ -inline size_t maxDecimalForQubit(size_t qubitIndex, size_t qubits) { +inline auto maxDecimalForQubit(size_t qubitIndex, size_t qubits) -> size_t { assert(qubitIndex < qubits); return exp2(qubits - qubitIndex - 1); } @@ -185,16 +187,19 @@ inline size_t maxDecimalForQubit(size_t qubitIndex, size_t qubits) { * @param data Gate matrix data. * @return size_t Number of wires. */ -template inline size_t dimSize(const std::vector &data) { +template inline auto dimSize(const std::vector &data) -> size_t { const size_t s = data.size(); - const size_t s_sqrt = static_cast(std::floor(std::sqrt(s))); + const auto s_sqrt = static_cast(std::floor(std::sqrt(s))); - if (s < 4) + if (s < 4) { throw std::invalid_argument("The dataset must be at least 2x2"); - if (((s == 0) || (s & (s - 1)))) + } + if (((s == 0) || (s & (s - 1)))) { throw std::invalid_argument("The dataset must be a power of 2"); - if (s_sqrt * s_sqrt != s) + } + if (s_sqrt * s_sqrt != s) { throw std::invalid_argument("The dataset must be a perfect square"); + } return static_cast(log2(s_sqrt)); } @@ -209,16 +214,16 @@ template inline size_t dimSize(const std::vector &data) { * @return std::complex Result of inner product operation. */ template -std::complex innerProd(const std::complex *data_1, - const std::complex *data_2, - const size_t data_size) { +auto innerProd(const std::complex *data_1, const std::complex *data_2, + const size_t data_size) -> std::complex { std::complex result(0, 0); if constexpr (USE_CBLAS) { - if constexpr (std::is_same_v) + if constexpr (std::is_same_v) { cblas_cdotu_sub(data_size, data_1, 1, data_2, 1, &result); - else if constexpr (std::is_same_v) + } else if constexpr (std::is_same_v) { cblas_zdotu_sub(data_size, data_1, 1, data_2, 1, &result); + } } else { result = std::inner_product( data_1, data_1 + data_size, data_2, std::complex(), ConstSum, @@ -239,16 +244,16 @@ std::complex innerProd(const std::complex *data_1, * @return std::complex Result of inner product operation. */ template -std::complex innerProdC(const std::complex *data_1, - const std::complex *data_2, - const size_t data_size) { +auto innerProdC(const std::complex *data_1, const std::complex *data_2, + const size_t data_size) -> std::complex { std::complex result(0, 0); if constexpr (USE_CBLAS) { - if constexpr (std::is_same_v) + if constexpr (std::is_same_v) { cblas_cdotc_sub(data_size, data_1, 1, data_2, 1, &result); - else if constexpr (std::is_same_v) + } else if constexpr (std::is_same_v) { cblas_zdotc_sub(data_size, data_1, 1, data_2, 1, &result); + } } else { result = std::inner_product(data_1, data_1 + data_size, data_2, std::complex(), ConstSum, @@ -264,8 +269,9 @@ std::complex innerProdC(const std::complex *data_1, * const size_t data_size) */ template -inline std::complex innerProd(const std::vector> &data_1, - const std::vector> &data_2) { +inline auto innerProd(const std::vector> &data_1, + const std::vector> &data_2) + -> std::complex { return innerProd(data_1.data(), data_2.data(), data_1.size()); } @@ -277,8 +283,9 @@ inline std::complex innerProd(const std::vector> &data_1, * const size_t data_size) */ template -inline std::complex innerProdC(const std::vector> &data_1, - const std::vector> &data_2) { +inline auto innerProdC(const std::vector> &data_1, + const std::vector> &data_2) + -> std::complex { return innerProdC(data_1.data(), data_2.data(), data_1.size()); } @@ -291,7 +298,8 @@ inline std::complex innerProdC(const std::vector> &data_1, * @return std::ostream& */ template -inline std::ostream &operator<<(std::ostream &os, const std::vector &vec) { +inline auto operator<<(std::ostream &os, const std::vector &vec) + -> std::ostream & { os << '['; for (size_t i = 0; i < vec.size(); i++) { os << vec[i] << ","; @@ -309,7 +317,8 @@ inline std::ostream &operator<<(std::ostream &os, const std::vector &vec) { * @return std::ostream& */ template -inline std::ostream &operator<<(std::ostream &os, const std::set &s) { +inline auto operator<<(std::ostream &os, const std::set &s) + -> std::ostream & { os << '{'; for (const auto &e : s) { os << e << ","; @@ -327,7 +336,8 @@ inline std::ostream &operator<<(std::ostream &os, const std::set &s) { * @param num_points Number of data-points in range. * @return std::vector */ -template std::vector linspace(T start, T end, size_t num_points) { +template +auto linspace(T start, T end, size_t num_points) -> std::vector { std::vector data(num_points); T step = (end - start) / (num_points - 1); for (size_t i = 0; i < num_points; i++) { From b25c863d1ff386490f23f127b0109c03d1ba76e2 Mon Sep 17 00:00:00 2001 From: "Lee J. O'Riordan" Date: Fri, 8 Oct 2021 14:52:38 +0100 Subject: [PATCH 10/45] Update error objects --- pennylane_lightning/src/util/Error.hpp | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/pennylane_lightning/src/util/Error.hpp b/pennylane_lightning/src/util/Error.hpp index b763f05ce4..c4ff8b87ff 100644 --- a/pennylane_lightning/src/util/Error.hpp +++ b/pennylane_lightning/src/util/Error.hpp @@ -13,6 +13,7 @@ #include #include #include +#include /** * @brief Macro that throws `%LightningException` with given message. @@ -67,13 +68,13 @@ class LightningException : public std::exception { * * @param err_msg Error message explaining the exception condition. */ - explicit LightningException(const std::string &err_msg) noexcept - : err_msg(err_msg) {} + explicit LightningException(std::string err_msg) noexcept + : err_msg(std::move(err_msg)) {} /** * @brief Destroys the `%LightningException` object. */ - virtual ~LightningException() = default; + ~LightningException() override = default; /** * @brief Returns a string containing the exception message. Overrides @@ -81,7 +82,9 @@ class LightningException : public std::exception { * * @return Exception message. */ - const char *what() const noexcept { return err_msg.c_str(); } + [[nodiscard]] auto what() const noexcept override -> const char * { + return err_msg.c_str(); + } private: std::string err_msg; From cc6e91f3e768737ac5dcee319cc9eaff0e90fb2a Mon Sep 17 00:00:00 2001 From: "Lee J. O'Riordan" Date: Fri, 8 Oct 2021 15:32:36 +0100 Subject: [PATCH 11/45] Remove redundant const in gate defns --- pennylane_lightning/src/simulator/Gates.hpp | 47 ++++++++++----------- 1 file changed, 22 insertions(+), 25 deletions(-) diff --git a/pennylane_lightning/src/simulator/Gates.hpp b/pennylane_lightning/src/simulator/Gates.hpp index f2eb4f612a..f3e3d7549f 100644 --- a/pennylane_lightning/src/simulator/Gates.hpp +++ b/pennylane_lightning/src/simulator/Gates.hpp @@ -193,7 +193,7 @@ static constexpr auto getToffoli() -> std::vector> { * data. */ template -static auto getPhaseShift(U angle) -> const std::vector> { +static auto getPhaseShift(U angle) -> std::vector> { return {ONE(), ZERO(), ZERO(), std::exp(IMAG() * angle)}; } @@ -209,7 +209,7 @@ static auto getPhaseShift(U angle) -> const std::vector> { */ template static auto getPhaseShift(const std::vector ¶ms) - -> const std::vector> { + -> std::vector> { return getPhaseShift(params.front()); } @@ -223,7 +223,7 @@ static auto getPhaseShift(const std::vector ¶ms) * @return const std::vector> Return const RX gate data. */ template -static auto getRX(U angle) -> const std::vector> { +static auto getRX(U angle) -> std::vector> { const std::complex c(std::cos(angle / 2), 0); const std::complex js(0, -std::sin(angle / 2)); return {c, js, js, c}; @@ -240,7 +240,7 @@ static auto getRX(U angle) -> const std::vector> { */ template static auto getRX(const std::vector ¶ms) - -> const std::vector> { + -> std::vector> { return getRX(params.front()); } @@ -254,7 +254,7 @@ static auto getRX(const std::vector ¶ms) * @return const std::vector> Return const RY gate data. */ template -static auto getRY(U angle) -> const std::vector> { +static auto getRY(U angle) -> std::vector> { const std::complex c(std::cos(angle / 2), 0); const std::complex s(std::sin(angle / 2), 0); return {c, -s, s, c}; @@ -271,7 +271,7 @@ static auto getRY(U angle) -> const std::vector> { */ template static auto getRY(const std::vector ¶ms) - -> const std::vector> { + -> std::vector> { return getRY(params.front()); } @@ -285,7 +285,7 @@ static auto getRY(const std::vector ¶ms) * @return const std::vector> Return const RZ gate data. */ template -static auto getRZ(U angle) -> const std::vector> { +static auto getRZ(U angle) -> std::vector> { return {std::exp(-IMAG() * (angle / 2)), ZERO(), ZERO(), std::exp(IMAG() * (angle / 2))}; } @@ -300,7 +300,7 @@ static auto getRZ(U angle) -> const std::vector> { * @return const std::vector> Return const RZ gate data. */ template -static auto getRZ(const std::vector ¶ms) -> const std::vector { +static auto getRZ(const std::vector ¶ms) -> std::vector { return getRZ(params.front()); } @@ -323,10 +323,9 @@ e^{-i(\phi-\omega)/2}\sin(\theta/2) & e^{i(\phi+\omega)/2}\cos(\theta/2) * @return const std::vector> Return const Rot gate data. */ template -static auto getRot(U phi, U theta, U omega) - -> const std::vector> { - const std::complex c(std::cos(theta / 2), 0); - const std::complex s(std::sin(theta / 2), 0); +static auto getRot(U phi, U theta, U omega) -> std::vector> { + const T c = std::cos(theta / 2); + const T s = std::sin(theta / 2); const U p{phi + omega}; const U m{phi - omega}; return {std::exp(static_cast(p / 2) * (-IMAG())) * c, @@ -354,7 +353,7 @@ e^{-i(\phi-\omega)/2}\sin(\theta/2) & e^{i(\phi+\omega)/2}\cos(\theta/2) */ template static auto getRot(const std::vector ¶ms) - -> const std::vector> { + -> std::vector> { return getRot(params[0], params[1], params[2]); } @@ -368,7 +367,7 @@ static auto getRot(const std::vector ¶ms) * @return const std::vector> Return const RX gate data. */ template -static auto getCRX(U angle) -> const std::vector> { +static auto getCRX(U angle) -> std::vector> { const std::complex rx{getRX(angle)}; return {ONE(), ZERO(), ZERO(), ZERO(), ZERO(), ONE(), ZERO(), ZERO(), ZERO(), ZERO(), rx[0], rx[1], @@ -386,7 +385,7 @@ static auto getCRX(U angle) -> const std::vector> { */ template static auto getCRX(const std::vector ¶ms) - -> const std::vector> { + -> std::vector> { return getCRX(params.front()); } @@ -400,7 +399,7 @@ static auto getCRX(const std::vector ¶ms) * @return const std::vector> Return const RY gate data. */ template -static auto getCRY(U angle) -> const std::vector> { +static auto getCRY(U angle) -> std::vector> { const std::complex ry{getRY(angle)}; return {ONE(), ZERO(), ZERO(), ZERO(), ZERO(), ONE(), ZERO(), ZERO(), ZERO(), ZERO(), ry[0], ry[1], @@ -418,7 +417,7 @@ static auto getCRY(U angle) -> const std::vector> { */ template static auto getCRY(const std::vector ¶ms) - -> const std::vector> { + -> std::vector> { return getCRY(params.front()); } @@ -432,7 +431,7 @@ static auto getCRY(const std::vector ¶ms) * @return const std::vector> Return const RZ gate data. */ template -static auto getCRZ(U angle) -> const std::vector> { +static auto getCRZ(U angle) -> std::vector> { const std::complex first = std::exp(-IMAG() * (angle / 2)); const std::complex second = std::exp(IMAG() * (angle / 2)); return {ONE(), ZERO(), ZERO(), ZERO(), ZERO(), @@ -451,7 +450,7 @@ static auto getCRZ(U angle) -> const std::vector> { */ template static auto getCRZ(const std::vector ¶ms) - -> const std::vector> { + -> std::vector> { return getCRZ(params.front()); } @@ -462,8 +461,7 @@ row-major format. * @see `getRot(U phi, U theta, U omega)`. */ template -static auto getCRot(U phi, U theta, U omega) - -> const std::vector> { +static auto getCRot(U phi, U theta, U omega) -> std::vector> { const std::vector> rot{ std::move(getRot(phi, theta, omega))}; return {ONE(), ZERO(), ZERO(), ZERO(), ZERO(), ONE(), @@ -479,7 +477,7 @@ row-major format. */ template static auto getCRot(const std::vector ¶ms) - -> const std::vector> { + -> std::vector> { return getCRot(params[0], params[1], params[2]); } @@ -490,8 +488,7 @@ in row-major format. * @see `getPhaseShift(U angle)`. */ template -static auto getControlledPhaseShift(U angle) - -> const std::vector> { +static auto getControlledPhaseShift(U angle) -> std::vector> { return {ONE(), ZERO(), ZERO(), ZERO(), ZERO(), ONE(), ZERO(), ZERO(), ZERO(), ZERO(), ONE(), ZERO(), @@ -506,7 +503,7 @@ in row-major format. */ template static auto getControlledPhaseShift(const std::vector ¶ms) - -> const std::vector> { + -> std::vector> { return getControlledPhaseShift(params.front()); } From 41b1029ad8d7a58a451968774e077df780ea3f04 Mon Sep 17 00:00:00 2001 From: "Lee J. O'Riordan" Date: Fri, 8 Oct 2021 15:33:45 +0100 Subject: [PATCH 12/45] Ensure perfect forwarding of exception strings --- pennylane_lightning/src/util/Error.hpp | 23 +++++++++++++++++------ 1 file changed, 17 insertions(+), 6 deletions(-) diff --git a/pennylane_lightning/src/util/Error.hpp b/pennylane_lightning/src/util/Error.hpp index c4ff8b87ff..00cc1190d9 100644 --- a/pennylane_lightning/src/util/Error.hpp +++ b/pennylane_lightning/src/util/Error.hpp @@ -13,6 +13,8 @@ #include #include #include +#include +#include #include /** @@ -62,14 +64,26 @@ namespace Pennylane::Util { * */ class LightningException : public std::exception { + private: + const std::string err_msg; + template struct remove_cvref { + using type = std::remove_cv_t>; + }; + template using remove_cvref_t = typename remove_cvref::type; + public: /** * @brief Constructs a new `%LightningException` exception. * * @param err_msg Error message explaining the exception condition. */ - explicit LightningException(std::string err_msg) noexcept - : err_msg(std::move(err_msg)) {} + + template < + typename T, + std::enable_if_t, std::string>, + int> = 0> + explicit LightningException(T &&err_msg) noexcept + : err_msg{std::forward(err_msg)} {} /** * @brief Destroys the `%LightningException` object. @@ -82,12 +96,9 @@ class LightningException : public std::exception { * * @return Exception message. */ - [[nodiscard]] auto what() const noexcept override -> const char * { + [[nodiscard]] auto what() const noexcept -> const char * override { return err_msg.c_str(); } - - private: - std::string err_msg; }; /** From 3694768a2a4763f176867ac8485bc26e7511d68f Mon Sep 17 00:00:00 2001 From: "Lee J. O'Riordan" Date: Fri, 8 Oct 2021 15:34:13 +0100 Subject: [PATCH 13/45] Define literals before returns --- pennylane_lightning/src/util/Util.hpp | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/pennylane_lightning/src/util/Util.hpp b/pennylane_lightning/src/util/Util.hpp index 247c702acc..a028cdcf2b 100644 --- a/pennylane_lightning/src/util/Util.hpp +++ b/pennylane_lightning/src/util/Util.hpp @@ -131,10 +131,12 @@ template inline static constexpr auto IMAG() -> std::complex { * @return constexpr T sqrt(2) */ template inline static constexpr auto SQRT2() -> T { + constexpr auto f = 0x1.6a09e6p+0F; + constexpr auto d = 0x1.6a09e667f3bcdp+0; if constexpr (std::is_same_v) { - return {0x1.6a09e6p+0F}; + return f; } else { - return {0x1.6a09e667f3bcdp+0}; + return d; } } From 3c267505d55367ef606dc3a227029db982c2c137 Mon Sep 17 00:00:00 2001 From: "Lee J. O'Riordan" Date: Fri, 8 Oct 2021 15:35:28 +0100 Subject: [PATCH 14/45] Ensure trialing returns, replace of bind with lambda and const adjustments --- .../src/simulator/StateVector.hpp | 278 +++++++++++++----- 1 file changed, 200 insertions(+), 78 deletions(-) diff --git a/pennylane_lightning/src/simulator/StateVector.hpp b/pennylane_lightning/src/simulator/StateVector.hpp index 1ad2efde7b..4cdd0d1277 100644 --- a/pennylane_lightning/src/simulator/StateVector.hpp +++ b/pennylane_lightning/src/simulator/StateVector.hpp @@ -85,11 +85,11 @@ template class StateVector { //***********************************************************************// - CFP_t *arr_; - size_t length_; - size_t num_qubits_; + CFP_t *arr_{nullptr}; + size_t length_{0}; + size_t num_qubits_{0}; const std::unordered_map gate_wires_; - const FMap gates_; + const FMap gates_{}; public: /** @@ -97,8 +97,7 @@ template class StateVector { */ using scalar_type_t = fp_t; - StateVector() - : arr_{nullptr}, length_{0}, num_qubits_{0}, gate_wires_{}, gates_{} {}; + StateVector() : gate_wires_{} {}; /** * @brief Construct a new `%StateVector` object from a given complex data @@ -125,56 +124,165 @@ template class StateVector { // dispatch. Non-parametric gate-calls will ignore the parameter // arguments if unused. {"PauliX", - bind(&StateVector::applyPauliX_, this, _1, _2, _3, _4)}, + [this](auto &&PH1, auto &&PH2, auto &&PH3, auto &&PH4) { + applyPauliX_(std::forward(PH1), + std::forward(PH2), + std::forward(PH3), + std::forward(PH4)); + }}, {"PauliY", - bind(&StateVector::applyPauliY_, this, _1, _2, _3, _4)}, + [this](auto &&PH1, auto &&PH2, auto &&PH3, auto &&PH4) { + applyPauliY_(std::forward(PH1), + std::forward(PH2), + std::forward(PH3), + std::forward(PH4)); + }}, {"PauliZ", - bind(&StateVector::applyPauliZ_, this, _1, _2, _3, _4)}, + [this](auto &&PH1, auto &&PH2, auto &&PH3, auto &&PH4) { + applyPauliZ_(std::forward(PH1), + std::forward(PH2), + std::forward(PH3), + std::forward(PH4)); + }}, {"Hadamard", - bind(&StateVector::applyHadamard_, this, _1, _2, _3, _4)}, - {"S", bind(&StateVector::applyS_, this, _1, _2, _3, _4)}, - {"T", bind(&StateVector::applyT_, this, _1, _2, _3, _4)}, + [this](auto &&PH1, auto &&PH2, auto &&PH3, auto &&PH4) { + applyHadamard_(std::forward(PH1), + std::forward(PH2), + std::forward(PH3), + std::forward(PH4)); + }}, + {"S", + [this](auto &&PH1, auto &&PH2, auto &&PH3, auto &&PH4) { + applyS_(std::forward(PH1), + std::forward(PH2), + std::forward(PH3), + std::forward(PH4)); + }}, + {"T", + [this](auto &&PH1, auto &&PH2, auto &&PH3, auto &&PH4) { + applyT_(std::forward(PH1), + std::forward(PH2), + std::forward(PH3), + std::forward(PH4)); + }}, {"CNOT", - bind(&StateVector::applyCNOT_, this, _1, _2, _3, _4)}, + [this](auto &&PH1, auto &&PH2, auto &&PH3, auto &&PH4) { + applyCNOT_(std::forward(PH1), + std::forward(PH2), + std::forward(PH3), + std::forward(PH4)); + }}, {"SWAP", - bind(&StateVector::applySWAP_, this, _1, _2, _3, _4)}, + [this](auto &&PH1, auto &&PH2, auto &&PH3, auto &&PH4) { + applySWAP_(std::forward(PH1), + std::forward(PH2), + std::forward(PH3), + std::forward(PH4)); + }}, {"CSWAP", - bind(&StateVector::applyCSWAP_, this, _1, _2, _3, _4)}, - {"CZ", bind(&StateVector::applyCZ_, this, _1, _2, _3, _4)}, + [this](auto &&PH1, auto &&PH2, auto &&PH3, auto &&PH4) { + applyCSWAP_(std::forward(PH1), + std::forward(PH2), + std::forward(PH3), + std::forward(PH4)); + }}, + {"CZ", + [this](auto &&PH1, auto &&PH2, auto &&PH3, auto &&PH4) { + applyCZ_(std::forward(PH1), + std::forward(PH2), + std::forward(PH3), + std::forward(PH4)); + }}, {"Toffoli", - bind(&StateVector::applyToffoli_, this, _1, _2, _3, _4)}, - {"PhaseShift", bind(&StateVector::applyPhaseShift_, this, - _1, _2, _3, _4)}, + [this](auto &&PH1, auto &&PH2, auto &&PH3, auto &&PH4) { + applyToffoli_(std::forward(PH1), + std::forward(PH2), + std::forward(PH3), + std::forward(PH4)); + }}, + {"PhaseShift", + [this](auto &&PH1, auto &&PH2, auto &&PH3, auto &&PH4) { + applyPhaseShift_(std::forward(PH1), + std::forward(PH2), + std::forward(PH3), + std::forward(PH4)); + }}, {"ControlledPhaseShift", - bind(&StateVector::applyControlledPhaseShift_, this, _1, - _2, _3, _4)}, - {"RX", bind(&StateVector::applyRX_, this, _1, _2, _3, _4)}, - {"RY", bind(&StateVector::applyRY_, this, _1, _2, _3, _4)}, - {"RZ", bind(&StateVector::applyRZ_, this, _1, _2, _3, _4)}, + [this](auto &&PH1, auto &&PH2, auto &&PH3, auto &&PH4) { + applyControlledPhaseShift_(std::forward(PH1), + std::forward(PH2), + std::forward(PH3), + std::forward(PH4)); + }}, + {"RX", + [this](auto &&PH1, auto &&PH2, auto &&PH3, auto &&PH4) { + applyRX_(std::forward(PH1), + std::forward(PH2), + std::forward(PH3), + std::forward(PH4)); + }}, + {"RY", + [this](auto &&PH1, auto &&PH2, auto &&PH3, auto &&PH4) { + applyRY_(std::forward(PH1), + std::forward(PH2), + std::forward(PH3), + std::forward(PH4)); + }}, + {"RZ", + [this](auto &&PH1, auto &&PH2, auto &&PH3, auto &&PH4) { + applyRZ_(std::forward(PH1), + std::forward(PH2), + std::forward(PH3), + std::forward(PH4)); + }}, {"Rot", - bind(&StateVector::applyRot_, this, _1, _2, _3, _4)}, + [this](auto &&PH1, auto &&PH2, auto &&PH3, auto &&PH4) { + applyRot_(std::forward(PH1), + std::forward(PH2), + std::forward(PH3), + std::forward(PH4)); + }}, {"CRX", - bind(&StateVector::applyCRX_, this, _1, _2, _3, _4)}, + [this](auto &&PH1, auto &&PH2, auto &&PH3, auto &&PH4) { + applyCRX_(std::forward(PH1), + std::forward(PH2), + std::forward(PH3), + std::forward(PH4)); + }}, {"CRY", - bind(&StateVector::applyCRY_, this, _1, _2, _3, _4)}, + [this](auto &&PH1, auto &&PH2, auto &&PH3, auto &&PH4) { + applyCRY_(std::forward(PH1), + std::forward(PH2), + std::forward(PH3), + std::forward(PH4)); + }}, {"CRZ", - bind(&StateVector::applyCRZ_, this, _1, _2, _3, _4)}, - {"CRot", - bind(&StateVector::applyCRot_, this, _1, _2, _3, _4)}} {}; + [this](auto &&PH1, auto &&PH2, auto &&PH3, auto &&PH4) { + applyCRZ_(std::forward(PH1), + std::forward(PH2), + std::forward(PH3), + std::forward(PH4)); + }}, + {"CRot", [this](auto &&PH1, auto &&PH2, auto &&PH3, auto &&PH4) { + applyCRot_(std::forward(PH1), + std::forward(PH2), + std::forward(PH3), + std::forward(PH4)); + }}} {}; /** * @brief Get the underlying data pointer. * * @return const CFP_t* Pointer to statevector data. */ - CFP_t *getData() const { return arr_; } + auto getData() const -> CFP_t * { return arr_; } /** * @brief Get the underlying data pointer. * * @return CFP_t* Pointer to statevector data. */ - CFP_t *getData() { return arr_; } + auto getData() -> CFP_t * { return arr_; } /** * @brief Redefine statevector data pointer. @@ -208,14 +316,14 @@ template class StateVector { * * @return std::size_t */ - std::size_t getLength() const { return length_; } + auto getLength() const -> std::size_t { return length_; } /** * @brief Get the number of qubits represented by the statevector data. * * @return std::size_t */ - std::size_t getNumQubits() const { return num_qubits_; } + auto getNumQubits() const -> std::size_t { return num_qubits_; } /** * @brief Apply a single gate to the state-vector. @@ -228,11 +336,12 @@ template class StateVector { void applyOperation(const string &opName, const vector &wires, bool inverse = false, const vector ¶ms = {}) { const auto gate = gates_.at(opName); - if (gate_wires_.at(opName) != wires.size()) + if (gate_wires_.at(opName) != wires.size()) { throw std::invalid_argument( string("The gate of type ") + opName + " requires " + std::to_string(gate_wires_.at(opName)) + " wires, but " + std::to_string(wires.size()) + " were supplied"); + } const vector internalIndices = generateBitPatterns(wires); const vector externalWires = getIndicesAfterExclusion(wires); @@ -254,11 +363,12 @@ template class StateVector { [[maybe_unused]] const vector ¶ms = {}) { auto dim = Util::dimSize(matrix); - if (dim != wires.size()) + if (dim != wires.size()) { throw std::invalid_argument(string("The supplied gate requires ") + std::to_string(dim) + " wires, but " + std::to_string(wires.size()) + " were supplied."); + } const vector internalIndices = generateBitPatterns(wires); const vector externalWires = getIndicesAfterExclusion(wires); @@ -281,10 +391,11 @@ template class StateVector { const vector &inverse, const vector> ¶ms) { const size_t numOperations = ops.size(); - if (numOperations != wires.size() || numOperations != params.size()) + if (numOperations != wires.size() || numOperations != params.size()) { throw std::invalid_argument( "Invalid arguments: number of operations, wires, and " "parameters must all be equal"); + } for (size_t i = 0; i < numOperations; i++) { applyOperation(ops[i], wires[i], inverse[i], params[i]); @@ -301,10 +412,11 @@ template class StateVector { const vector> &wires, const vector &inverse) { const size_t numOperations = ops.size(); - if (numOperations != wires.size()) + if (numOperations != wires.size()) { throw std::invalid_argument( "Invalid arguments: number of operations, wires, and " "parameters must all be equal"); + } for (size_t i = 0; i < numOperations; i++) { applyOperation(ops[i], wires[i], inverse[i]); @@ -319,8 +431,8 @@ template class StateVector { * @param num_qubits Total number of qubits for statevector. * @return vector */ - vector static getIndicesAfterExclusion( - const vector &indicesToExclude, size_t num_qubits) { + auto static getIndicesAfterExclusion(const vector &indicesToExclude, + size_t num_qubits) -> vector { std::set indices; for (size_t i = 0; i < num_qubits; i++) { indices.emplace(i); @@ -337,8 +449,8 @@ template class StateVector { * @see `getIndicesAfterExclusion( const vector &indicesToExclude, size_t num_qubits)` */ - vector - getIndicesAfterExclusion(const vector &indicesToExclude) { + auto getIndicesAfterExclusion(const vector &indicesToExclude) + -> vector { return getIndicesAfterExclusion(indicesToExclude, num_qubits_); } @@ -352,8 +464,8 @@ template class StateVector { * @param num_qubits Number of qubits in register. * @return vector */ - static vector - generateBitPatterns(const vector &qubitIndices, size_t num_qubits) { + static auto generateBitPatterns(const vector &qubitIndices, + size_t num_qubits) -> vector { vector indices; indices.reserve(Util::exp2(qubitIndices.size())); indices.emplace_back(0); @@ -376,7 +488,8 @@ template class StateVector { * @see `generateBitPatterns(const vector &qubitIndices, size_t * num_qubits)`. */ - vector generateBitPatterns(const vector &qubitIndices) { + auto generateBitPatterns(const vector &qubitIndices) + -> vector { return generateBitPatterns(qubitIndices, num_qubits_); } @@ -392,9 +505,10 @@ template class StateVector { const vector &externalIndices, bool inverse) { if (static_cast(1ULL << (Util::log2(indices.size()) + Util::log2(externalIndices.size()))) != - length_) + length_) { throw std::out_of_range( "The given indices do not match the state-vector length."); + } vector v(indices.size()); for (const size_t &externalIndex : externalIndices) { @@ -411,7 +525,7 @@ template class StateVector { size_t index = indices[i]; shiftedState[index] = 0; - if (inverse == true) { + if (inverse) { for (size_t j = 0; j < indices.size(); j++) { const size_t baseIndex = j * indices.size(); shiftedState[index] += @@ -440,9 +554,10 @@ template class StateVector { const vector &externalIndices, bool inverse) { if (static_cast(1ULL << (Util::log2(indices.size()) + Util::log2(externalIndices.size()))) != - length_) + length_) { throw std::out_of_range( "The given indices do not match the state-vector length."); + } vector v(indices.size()); for (const size_t &externalIndex : externalIndices) { @@ -459,7 +574,7 @@ template class StateVector { size_t index = indices[i]; shiftedState[index] = 0; - if (inverse == true) { + if (inverse) { for (size_t j = 0; j < indices.size(); j++) { const size_t baseIndex = j * indices.size(); shiftedState[index] += @@ -567,7 +682,7 @@ template class StateVector { void applyS(const vector &indices, const vector &externalIndices, bool inverse) { const CFP_t shift = - (inverse == true) ? -Util::IMAG() : Util::IMAG(); + (inverse) ? -Util::IMAG() : Util::IMAG(); for (const size_t &externalIndex : externalIndices) { CFP_t *shiftedState = arr_ + externalIndex; @@ -587,7 +702,7 @@ template class StateVector { void applyT(const vector &indices, const vector &externalIndices, bool inverse) { const CFP_t shift = - (inverse == true) + (inverse) ? std::conj(std::exp(CFP_t(0, static_cast(M_PI / 4)))) : std::exp(CFP_t(0, static_cast(M_PI / 4))); @@ -614,8 +729,8 @@ template class StateVector { const vector &externalIndices, bool inverse, Param_t angle) { const CFP_t c(std::cos(angle / 2), 0); - const CFP_t js = (inverse == true) ? CFP_t(0, -std::sin(-angle / 2)) - : CFP_t(0, std::sin(-angle / 2)); + const CFP_t js = (inverse) ? CFP_t(0, -std::sin(-angle / 2)) + : CFP_t(0, std::sin(-angle / 2)); for (const size_t &externalIndex : externalIndices) { CFP_t *shiftedState = arr_ + externalIndex; @@ -642,8 +757,8 @@ template class StateVector { const vector &externalIndices, bool inverse, Param_t angle) { const CFP_t c(std::cos(angle / 2), 0); - const CFP_t s = (inverse == true) ? CFP_t(-std::sin(angle / 2), 0) - : CFP_t(std::sin(angle / 2), 0); + const CFP_t s = (inverse) ? CFP_t(-std::sin(angle / 2), 0) + : CFP_t(std::sin(angle / 2), 0); for (const size_t &externalIndex : externalIndices) { CFP_t *shiftedState = arr_ + externalIndex; @@ -671,8 +786,8 @@ template class StateVector { Param_t angle) { const CFP_t first = std::exp(CFP_t(0, -angle / 2)); const CFP_t second = std::exp(CFP_t(0, angle / 2)); - const CFP_t shift1 = (inverse == true) ? std::conj(first) : first; - const CFP_t shift2 = (inverse == true) ? std::conj(second) : second; + const CFP_t shift1 = (inverse) ? std::conj(first) : first; + const CFP_t shift2 = (inverse) ? std::conj(second) : second; for (const size_t &externalIndex : externalIndices) { CFP_t *shiftedState = arr_ + externalIndex; @@ -750,10 +865,10 @@ template class StateVector { Param_t phi, Param_t theta, Param_t omega) { const vector rot = Gates::getRot(phi, theta, omega); - const CFP_t t1 = (inverse == true) ? std::conj(rot[0]) : rot[0]; - const CFP_t t2 = (inverse == true) ? -rot[1] : rot[1]; - const CFP_t t3 = (inverse == true) ? -rot[2] : rot[2]; - const CFP_t t4 = (inverse == true) ? std::conj(rot[3]) : rot[3]; + const CFP_t t1 = (inverse) ? std::conj(rot[0]) : rot[0]; + const CFP_t t2 = (inverse) ? -rot[1] : rot[1]; + const CFP_t t3 = (inverse) ? -rot[2] : rot[2]; + const CFP_t t4 = (inverse) ? std::conj(rot[3]) : rot[3]; for (const size_t &externalIndex : externalIndices) { CFP_t *shiftedState = arr_ + externalIndex; @@ -834,8 +949,8 @@ template class StateVector { const vector &externalIndices, bool inverse, Param_t angle) { const CFP_t c(std::cos(angle / 2), 0); - const CFP_t js = (inverse == true) ? CFP_t(0, -std::sin(-angle / 2)) - : CFP_t(0, std::sin(-angle / 2)); + const CFP_t js = (inverse) ? CFP_t(0, -std::sin(-angle / 2)) + : CFP_t(0, std::sin(-angle / 2)); for (const size_t &externalIndex : externalIndices) { CFP_t *shiftedState = arr_ + externalIndex; @@ -863,8 +978,8 @@ template class StateVector { const vector &externalIndices, bool inverse, Param_t angle) { const CFP_t c(std::cos(angle / 2), 0); - const CFP_t s = (inverse == true) ? CFP_t(-std::sin(angle / 2), 0) - : CFP_t(std::sin(angle / 2), 0); + const CFP_t s = (inverse) ? CFP_t(-std::sin(angle / 2), 0) + : CFP_t(std::sin(angle / 2), 0); for (const size_t &externalIndex : externalIndices) { CFP_t *shiftedState = arr_ + externalIndex; @@ -891,12 +1006,10 @@ template class StateVector { void applyCRZ(const vector &indices, const vector &externalIndices, bool inverse, Param_t angle) { - const CFP_t m00 = (inverse == true) - ? std::conj(std::exp(CFP_t(0, -angle / 2))) - : std::exp(CFP_t(0, -angle / 2)); - const CFP_t m11 = (inverse == true) - ? std::conj(std::exp(CFP_t(0, angle / 2))) - : std::exp(CFP_t(0, angle / 2)); + const CFP_t m00 = (inverse) ? std::conj(std::exp(CFP_t(0, -angle / 2))) + : std::exp(CFP_t(0, -angle / 2)); + const CFP_t m11 = (inverse) ? std::conj(std::exp(CFP_t(0, angle / 2))) + : std::exp(CFP_t(0, angle / 2)); for (const size_t &externalIndex : externalIndices) { CFP_t *shiftedState = arr_ + externalIndex; shiftedState[indices[2]] *= m00; @@ -925,10 +1038,10 @@ template class StateVector { Param_t phi, Param_t theta, Param_t omega) { const auto rot = Gates::getRot(phi, theta, omega); - const CFP_t t1 = (inverse == true) ? std::conj(rot[0]) : rot[0]; - const CFP_t t2 = (inverse == true) ? -rot[1] : rot[1]; - const CFP_t t3 = (inverse == true) ? -rot[2] : rot[2]; - const CFP_t t4 = (inverse == true) ? std::conj(rot[3]) : rot[3]; + const CFP_t t1 = (inverse) ? std::conj(rot[0]) : rot[0]; + const CFP_t t2 = (inverse) ? -rot[1] : rot[1]; + const CFP_t t3 = (inverse) ? -rot[2] : rot[2]; + const CFP_t t4 = (inverse) ? std::conj(rot[3]) : rot[3]; for (const size_t &externalIndex : externalIndices) { CFP_t *shiftedState = arr_ + externalIndex; @@ -951,9 +1064,13 @@ template class StateVector { void applyToffoli(const vector &indices, const vector &externalIndices, [[maybe_unused]] bool inverse) { + // Participating swapped indices + static const size_t op_idx0 = 6; + static const size_t op_idx1 = 7; for (const size_t &externalIndex : externalIndices) { CFP_t *shiftedState = arr_ + externalIndex; - std::swap(shiftedState[indices[6]], shiftedState[indices[7]]); + std::swap(shiftedState[indices[op_idx0]], + shiftedState[indices[op_idx1]]); } } @@ -969,9 +1086,13 @@ template class StateVector { void applyCSWAP(const vector &indices, const vector &externalIndices, [[maybe_unused]] bool inverse) { + // Participating swapped indices + static const size_t op_idx0 = 5; + static const size_t op_idx1 = 6; for (const size_t &externalIndex : externalIndices) { CFP_t *shiftedState = arr_ + externalIndex; - std::swap(shiftedState[indices[5]], shiftedState[indices[6]]); + std::swap(shiftedState[indices[op_idx0]], + shiftedState[indices[op_idx1]]); } } @@ -1108,7 +1229,8 @@ template class StateVector { * @return std::ostream& */ template -inline std::ostream &operator<<(std::ostream &out, const StateVector &sv) { +inline auto operator<<(std::ostream &out, const StateVector &sv) + -> std::ostream & { const auto length = sv.getLength(); const auto qubits = sv.getNumQubits(); const auto data = sv.getData(); From 741d422299e5cf7454777704c51351142bcebe31 Mon Sep 17 00:00:00 2001 From: "Lee J. O'Riordan" Date: Tue, 12 Oct 2021 12:44:14 +0100 Subject: [PATCH 15/45] Enable C++20-like remove cv-ness --- pennylane_lightning/src/util/Util.hpp | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/pennylane_lightning/src/util/Util.hpp b/pennylane_lightning/src/util/Util.hpp index a028cdcf2b..56bdcb3afb 100644 --- a/pennylane_lightning/src/util/Util.hpp +++ b/pennylane_lightning/src/util/Util.hpp @@ -364,5 +364,10 @@ class NotImplementedException : public std::logic_error { fname){}; }; +// Enable until C++20 support is explicitly allowed +template struct remove_cvref { + using type = std::remove_cv_t>; +}; + } // namespace Util } // namespace Pennylane From 65f3dbf263a8d0a24955a085caf05ca616192a88 Mon Sep 17 00:00:00 2001 From: "Lee J. O'Riordan" Date: Tue, 12 Oct 2021 12:44:41 +0100 Subject: [PATCH 16/45] Ensure correct offloading handled in lightning error types --- pennylane_lightning/src/util/Error.hpp | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/pennylane_lightning/src/util/Error.hpp b/pennylane_lightning/src/util/Error.hpp index 00cc1190d9..7cdda41ecf 100644 --- a/pennylane_lightning/src/util/Error.hpp +++ b/pennylane_lightning/src/util/Error.hpp @@ -17,6 +17,8 @@ #include #include +#include "Util.hpp" + /** * @brief Macro that throws `%LightningException` with given message. * @@ -66,10 +68,6 @@ namespace Pennylane::Util { class LightningException : public std::exception { private: const std::string err_msg; - template struct remove_cvref { - using type = std::remove_cv_t>; - }; - template using remove_cvref_t = typename remove_cvref::type; public: /** @@ -80,7 +78,7 @@ class LightningException : public std::exception { template < typename T, - std::enable_if_t, std::string>, + std::enable_if_t::type, std::string>::value, int> = 0> explicit LightningException(T &&err_msg) noexcept : err_msg{std::forward(err_msg)} {} From 7592f1adb8ccb4938d63ed6dc73df0a455539bf1 Mon Sep 17 00:00:00 2001 From: "Lee J. O'Riordan" Date: Tue, 12 Oct 2021 12:45:13 +0100 Subject: [PATCH 17/45] Favour trailing return types for SV managed --- .../src/simulator/StateVectorManaged.hpp | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/pennylane_lightning/src/simulator/StateVectorManaged.hpp b/pennylane_lightning/src/simulator/StateVectorManaged.hpp index df7c0d7327..2ede5988ca 100644 --- a/pennylane_lightning/src/simulator/StateVectorManaged.hpp +++ b/pennylane_lightning/src/simulator/StateVectorManaged.hpp @@ -57,7 +57,7 @@ class StateVectorManaged : public StateVector { StateVector::setData(data_.data()); } - StateVectorManaged &operator=(const StateVectorManaged &other) { + auto operator=(const StateVectorManaged &other) -> StateVectorManaged & { if (this != &other) { if (data_.size() != other.getLength()) { data_.resize(other.getLength()); @@ -69,16 +69,16 @@ class StateVectorManaged : public StateVector { } return *this; } - std::vector &getDataVector() { return data_; } - const std::vector &getDataVector() const { return data_; } + auto getDataVector() -> std::vector & { return data_; } + auto getDataVector() const -> const std::vector & { return data_; } - std::vector - getInternalIndices(const std::vector &qubit_indices) { + auto + getInternalIndices(const std::vector &qubit_indices) -> std::vector { return StateVector::generateBitPatterns(qubit_indices, Util::log2(data_.size())); } - std::vector - getExternalIndices(const std::vector &qubit_indices) { + auto + getExternalIndices(const std::vector &qubit_indices) -> std::vector { std::vector externalWires = StateVector::getIndicesAfterExclusion( qubit_indices, Util::log2(data_.size())); From 0b0857fa8c3493a6a08d75c5758c8029c9fd2600 Mon Sep 17 00:00:00 2001 From: "Lee J. O'Riordan" Date: Tue, 12 Oct 2021 12:46:05 +0100 Subject: [PATCH 18/45] Update init'ing and add nosdiscard where applicable to SV --- pennylane_lightning/src/simulator/StateVector.hpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/pennylane_lightning/src/simulator/StateVector.hpp b/pennylane_lightning/src/simulator/StateVector.hpp index 4cdd0d1277..5437da7e91 100644 --- a/pennylane_lightning/src/simulator/StateVector.hpp +++ b/pennylane_lightning/src/simulator/StateVector.hpp @@ -89,7 +89,7 @@ template class StateVector { size_t length_{0}; size_t num_qubits_{0}; const std::unordered_map gate_wires_; - const FMap gates_{}; + const FMap gates_; public: /** @@ -316,14 +316,14 @@ template class StateVector { * * @return std::size_t */ - auto getLength() const -> std::size_t { return length_; } + [[nodiscard]] auto getLength() const -> std::size_t { return length_; } /** * @brief Get the number of qubits represented by the statevector data. * * @return std::size_t */ - auto getNumQubits() const -> std::size_t { return num_qubits_; } + [[nodiscard]] auto getNumQubits() const -> std::size_t { return num_qubits_; } /** * @brief Apply a single gate to the state-vector. From 6d6590e1824acffd57aa3b829205736bfa8d4dec Mon Sep 17 00:00:00 2001 From: "Lee J. O'Riordan" Date: Tue, 12 Oct 2021 12:46:35 +0100 Subject: [PATCH 19/45] Move clang-tidy options to source tree --- CMakeLists.txt | 3 - pennylane_lightning/src/.clang-tidy | 233 ++++++++++++++++++++++++++++ 2 files changed, 233 insertions(+), 3 deletions(-) create mode 100644 pennylane_lightning/src/.clang-tidy diff --git a/CMakeLists.txt b/CMakeLists.txt index c3146c8223..c6617bc066 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -37,9 +37,6 @@ if(ENABLE_CLANG_TIDY) endif() set(CMAKE_CXX_CLANG_TIDY ${CLANG_TIDY_BINARY}; -extra-arg=-std=c++17; - -warnings-as-errors=*; - -header-filter=.*; - -checks=-*,-llvmlibc-*,modernize-*,clang-analyzer-cplusplus*,openmp-*,performance-*,portability-*,readability-*; ) endif() diff --git a/pennylane_lightning/src/.clang-tidy b/pennylane_lightning/src/.clang-tidy new file mode 100644 index 0000000000..dc64a71352 --- /dev/null +++ b/pennylane_lightning/src/.clang-tidy @@ -0,0 +1,233 @@ +--- +Checks: 'clang-diagnostic-*,clang-analyzer-*,-*,-llvmlibc-*,modernize-*,clang-analyzer-cplusplus*,openmp-*,performance-*,portability-*,readability-*' +WarningsAsErrors: '*' +HeaderFilterRegex: '.*' +AnalyzeTemporaryDtors: false +FormatStyle: none +InheritParentConfig: true +User: mlxd +CheckOptions: + - key: modernize-replace-auto-ptr.IncludeStyle + value: llvm + - key: performance-move-const-arg.CheckTriviallyCopyableMove + value: 'true' + - key: modernize-use-auto.MinTypeNameLength + value: '5' + - key: readability-static-accessed-through-instance.NameSpecifierNestingThreshold + value: '3' + - key: readability-function-size.VariableThreshold + value: '4294967295' + - key: cert-dcl16-c.NewSuffixes + value: 'L;LL;LU;LLU' + - key: readability-identifier-naming.GetConfigPerFile + value: 'true' + - key: readability-inconsistent-declaration-parameter-name.Strict + value: 'false' + - key: readability-magic-numbers.IgnoredIntegerValues + value: '1;2;3;4;' + - key: modernize-use-default-member-init.UseAssignment + value: 'false' + - key: readability-function-size.NestingThreshold + value: '4294967295' + - key: modernize-use-override.AllowOverrideAndFinal + value: 'false' + - key: readability-function-size.ParameterThreshold + value: '4294967295' + - key: openmp-exception-escape.IgnoredExceptions + value: '' + - key: modernize-pass-by-value.ValuesOnly + value: 'false' + - key: modernize-loop-convert.IncludeStyle + value: llvm + - key: cert-str34-c.DiagnoseSignedUnsignedCharComparisons + value: '0' + - key: readability-identifier-naming.AggressiveDependentMemberLookup + value: 'false' + - key: readability-redundant-smartptr-get.IgnoreMacros + value: 'true' + - key: modernize-use-emplace.TupleTypes + value: '::std::pair;::std::tuple' + - key: modernize-use-emplace.TupleMakeFunctions + value: '::std::make_pair;::std::make_tuple' + - key: modernize-use-nodiscard.ReplacementString + value: '[[nodiscard]]' + - key: modernize-loop-convert.MakeReverseRangeHeader + value: '' + - key: modernize-replace-random-shuffle.IncludeStyle + value: llvm + - key: modernize-use-bool-literals.IgnoreMacros + value: 'true' + - key: google-readability-namespace-comments.ShortNamespaceLines + value: '10' + - key: modernize-avoid-bind.PermissiveParameterList + value: 'false' + - key: modernize-use-override.FinalSpelling + value: final + - key: performance-move-constructor-init.IncludeStyle + value: llvm + - key: modernize-loop-convert.UseCxx20ReverseRanges + value: 'true' + - key: modernize-use-noexcept.ReplacementString + value: '' + - key: modernize-use-using.IgnoreMacros + value: 'true' + - key: performance-type-promotion-in-math-fn.IncludeStyle + value: llvm + - key: modernize-loop-convert.NamingStyle + value: CamelCase + - key: modernize-loop-convert.MakeReverseRangeFunction + value: '' + - key: readability-inconsistent-declaration-parameter-name.IgnoreMacros + value: 'true' + - key: performance-no-automatic-move.AllowedTypes + value: '' + - key: performance-for-range-copy.WarnOnAllAutoCopies + value: 'false' + - key: readability-identifier-naming.IgnoreFailedSplit + value: 'false' + - key: modernize-pass-by-value.IncludeStyle + value: llvm + - key: readability-qualified-auto.AddConstToQualified + value: 'true' + - key: readability-simplify-boolean-expr.ChainedConditionalReturn + value: 'false' + - key: readability-else-after-return.WarnOnConditionVariables + value: 'true' + - key: readability-uppercase-literal-suffix.IgnoreMacros + value: 'true' + - key: modernize-use-nullptr.NullMacros + value: 'NULL' + - key: modernize-make-shared.IgnoreMacros + value: 'true' + - key: performance-unnecessary-copy-initialization.AllowedTypes + value: '' + - key: modernize-use-transparent-functors.SafeMode + value: 'false' + - key: modernize-make-shared.IgnoreDefaultInitialization + value: 'true' + - key: modernize-make-shared.IncludeStyle + value: llvm + - key: readability-simplify-boolean-expr.ChainedConditionalAssignment + value: 'false' + - key: cert-oop54-cpp.WarnOnlyIfThisHasSuspiciousField + value: '0' + - key: readability-function-size.LineThreshold + value: '4294967295' + - key: performance-inefficient-vector-operation.EnableProto + value: 'false' + - key: modernize-use-override.IgnoreDestructors + value: 'false' + - key: modernize-loop-convert.MaxCopySize + value: '16' + - key: modernize-make-shared.MakeSmartPtrFunction + value: 'std::make_shared' + - key: portability-simd-intrinsics.Suggest + value: 'false' + - key: cppcoreguidelines-explicit-virtual-functions.IgnoreDestructors + value: '1' + - key: modernize-make-unique.IgnoreMacros + value: 'true' + - key: modernize-make-shared.MakeSmartPtrFunctionHeader + value: '' + - key: performance-for-range-copy.AllowedTypes + value: '' + - key: readability-redundant-string-init.StringNames + value: '::std::basic_string_view;::std::basic_string' + - key: modernize-make-unique.IgnoreDefaultInitialization + value: 'true' + - key: modernize-use-emplace.ContainersWithPushBack + value: '::std::vector;::std::list;::std::deque' + - key: readability-magic-numbers.IgnoreBitFieldsWidths + value: 'true' + - key: modernize-make-unique.IncludeStyle + value: llvm + - key: readability-braces-around-statements.ShortStatementLines + value: '0' + - key: modernize-use-override.OverrideSpelling + value: override + - key: readability-magic-numbers.IgnoredFloatingPointValues + value: '1.0;100.0;' + - key: performance-inefficient-string-concatenation.StrictMode + value: 'false' + - key: readability-implicit-bool-conversion.AllowPointerConditions + value: 'false' + - key: readability-redundant-declaration.IgnoreMacros + value: 'true' + - key: google-readability-braces-around-statements.ShortStatementLines + value: '1' + - key: modernize-make-unique.MakeSmartPtrFunction + value: 'std::make_unique' + - key: portability-restrict-system-includes.Includes + value: '*' + - key: readability-else-after-return.WarnOnUnfixable + value: 'true' + - key: modernize-use-emplace.IgnoreImplicitConstructors + value: 'false' + - key: modernize-make-unique.MakeSmartPtrFunctionHeader + value: '' + - key: modernize-use-equals-delete.IgnoreMacros + value: 'true' + - key: readability-magic-numbers.IgnoreAllFloatingPointValues + value: 'false' + - key: readability-uppercase-literal-suffix.NewSuffixes + value: '' + - key: modernize-loop-convert.MinConfidence + value: reasonable + - key: performance-unnecessary-value-param.AllowedTypes + value: '' + - key: modernize-use-noexcept.UseNoexceptFalse + value: 'true' + - key: google-readability-namespace-comments.SpacesBeforeComments + value: '2' + - key: readability-function-cognitive-complexity.Threshold + value: '40' + - key: readability-function-cognitive-complexity.IgnoreMacros + value: 'true' + - key: cppcoreguidelines-non-private-member-variables-in-classes.IgnoreClassesWithAllMemberVariablesBeingPublic + value: '1' + - key: performance-faster-string-find.StringLikeClasses + value: '::std::basic_string;::std::basic_string_view' + - key: readability-function-size.BranchThreshold + value: '4294967295' + - key: readability-implicit-bool-conversion.AllowIntegerConditions + value: 'false' + - key: readability-function-size.StatementThreshold + value: '800' + - key: modernize-use-default-member-init.IgnoreMacros + value: 'true' + - key: llvm-qualified-auto.AddConstToQualified + value: '0' + - key: readability-identifier-naming.IgnoreMainLikeFunctions + value: 'false' + - key: google-readability-function-size.StatementThreshold + value: '800' + - key: llvm-else-after-return.WarnOnConditionVariables + value: '0' + - key: modernize-raw-string-literal.DelimiterStem + value: lit + - key: modernize-use-equals-default.IgnoreMacros + value: 'true' + - key: modernize-raw-string-literal.ReplaceShorterLiterals + value: 'false' + - key: modernize-use-emplace.SmartPointers + value: '::std::shared_ptr;::std::unique_ptr;::std::auto_ptr;::std::weak_ptr' + - key: performance-inefficient-vector-operation.VectorLikeClasses + value: '::std::vector' + - key: modernize-use-auto.RemoveStars + value: 'false' + - key: readability-magic-numbers.IgnorePowersOf2IntegerValues + value: 'false' + - key: portability-simd-intrinsics.Std + value: '' + - key: readability-redundant-member-init.IgnoreBaseInCopyConstructors + value: 'false' + - key: performance-unnecessary-value-param.IncludeStyle + value: llvm + - key: modernize-replace-disallow-copy-and-assign-macro.MacroName + value: DISALLOW_COPY_AND_ASSIGN + - key: llvm-else-after-return.WarnOnUnfixable + value: '0' + - key: readability-simplify-subscript-expr.Types + value: '::std::basic_string;::std::basic_string_view;::std::vector;::std::array' +... + From c28d10e9145efd7c344d1f03bfc661e8fc79b1a7 Mon Sep 17 00:00:00 2001 From: "Lee J. O'Riordan" Date: Tue, 12 Oct 2021 12:46:58 +0100 Subject: [PATCH 20/45] Fix env var setup on Github Actions --- .github/workflows/format.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/format.yml b/.github/workflows/format.yml index 80218b0422..1fedc94724 100644 --- a/.github/workflows/format.yml +++ b/.github/workflows/format.yml @@ -41,7 +41,7 @@ jobs: - name: Install dependencies run: sudo apt update && sudo apt -y install clang-tidy-11 python3 cmake g++ - env: + env: DEBIAN_FRONTEND: noninteractive - name: Checkout code From 3d334adbf15c295fb695c23bd41f4902b41091c1 Mon Sep 17 00:00:00 2001 From: "Lee J. O'Riordan" Date: Tue, 12 Oct 2021 12:48:02 +0100 Subject: [PATCH 21/45] Modernize adjoint diff implementation --- .../src/algorithms/AdjointDiff.hpp | 146 ++++++++++++------ 1 file changed, 97 insertions(+), 49 deletions(-) diff --git a/pennylane_lightning/src/algorithms/AdjointDiff.hpp b/pennylane_lightning/src/algorithms/AdjointDiff.hpp index e061428e6c..411bbb702a 100644 --- a/pennylane_lightning/src/algorithms/AdjointDiff.hpp +++ b/pennylane_lightning/src/algorithms/AdjointDiff.hpp @@ -17,6 +17,7 @@ #include #include #include +#include #include #include #include @@ -36,11 +37,11 @@ namespace { using namespace Pennylane; using namespace Pennylane::Util; -template static constexpr std::vector> getP00() { +template static constexpr auto getP00() -> std::vector> { return {ONE(), ZERO(), ZERO(), ZERO()}; } -template static constexpr std::vector> getP11() { +template static constexpr auto getP11() -> std::vector> { return {ZERO(), ZERO(), ZERO(), ONE()}; } @@ -161,11 +162,11 @@ template class ObsDatum { * @param obs_wires Wires upon which to apply operation. Each observable * operation will be a separate nested list. */ - ObsDatum(const std::vector &obs_name, - const std::vector &obs_params, - const std::vector> &obs_wires) - : obs_name_{obs_name}, - obs_params_(obs_params), obs_wires_{obs_wires} {}; + ObsDatum(std::vector obs_name, + std::vector obs_params, + std::vector> obs_wires) + : obs_name_{std::move(obs_name)}, + obs_params_(std::move(obs_params)), obs_wires_{std::move(obs_wires)} {}; /** * @brief Move constructor for an ObsDatum object, representing a given @@ -189,25 +190,25 @@ template class ObsDatum { * * @return size_t */ - size_t getSize() const { return obs_name_.size(); } + [[nodiscard]] auto getSize() const -> size_t { return obs_name_.size(); } /** * @brief Get the name of the observable operations. * * @return const std::vector& */ - const std::vector &getObsName() const { return obs_name_; } + [[nodiscard]] auto getObsName() const -> const std::vector & { return obs_name_; } /** * @brief Get the parameters for the observable operations. * * @return const std::vector>& */ - const std::vector &getObsParams() const { return obs_params_; } + [[nodiscard]] auto getObsParams() const -> const std::vector & { return obs_params_; } /** * @brief Get the wires for each observable operation. * * @return const std::vector>& */ - const std::vector> &getObsWires() const { + [[nodiscard]] auto getObsWires() const -> const std::vector> & { return obs_wires_; } @@ -245,13 +246,13 @@ template class OpsData { * @param ops_matrices Numerical representation of given matrix if not * supported. */ - OpsData(const std::vector &ops_name, + OpsData(std::vector ops_name, const std::vector> &ops_params, - const std::vector> &ops_wires, - const std::vector &ops_inverses, - const std::vector>> &ops_matrices) - : ops_name_{ops_name}, ops_params_{ops_params}, ops_wires_{ops_wires}, - ops_inverses_{ops_inverses}, ops_matrices_{ops_matrices} { + std::vector> ops_wires, + std::vector ops_inverses, + std::vector>> ops_matrices) + : ops_name_{std::move(ops_name)}, ops_params_{ops_params}, ops_wires_{std::move(ops_wires)}, + ops_inverses_{std::move(ops_inverses)}, ops_matrices_{std::move(ops_matrices)} { num_par_ops_ = 0; for (const auto &p : ops_params) { if (p.size() > 0) { @@ -273,10 +274,10 @@ template class OpsData { */ OpsData(const std::vector &ops_name, const std::vector> &ops_params, - const std::vector> &ops_wires, - const std::vector &ops_inverses) - : ops_name_{ops_name}, ops_params_{ops_params}, ops_wires_{ops_wires}, - ops_inverses_{ops_inverses}, ops_matrices_(ops_name.size()) { + std::vector> ops_wires, + std::vector ops_inverses) + : ops_name_{ops_name}, ops_params_{ops_params}, ops_wires_{std::move(ops_wires)}, + ops_inverses_{std::move(ops_inverses)}, ops_matrices_(ops_name.size()) { num_par_ops_ = 0; for (const auto &p : ops_params) { if (p.size() > 0) { @@ -291,21 +292,21 @@ template class OpsData { * * @return size_t Number of operations. */ - size_t getSize() const { return ops_name_.size(); } + [[nodiscard]] auto getSize() const -> size_t { return ops_name_.size(); } /** * @brief Get the names of the operations to be applied. * * @return const std::vector& */ - const std::vector &getOpsName() const { return ops_name_; } + [[nodiscard]] auto getOpsName() const -> const std::vector & { return ops_name_; } /** * @brief Get the (optional) parameters for each operation. Given entries * are empty ({}) if not required. * * @return const std::vector>& */ - const std::vector> &getOpsParams() const { + [[nodiscard]] auto getOpsParams() const -> const std::vector> & { return ops_params_; } /** @@ -313,7 +314,7 @@ template class OpsData { * * @return const std::vector>& */ - const std::vector> &getOpsWires() const { + [[nodiscard]] auto getOpsWires() const -> const std::vector> & { return ops_wires_; } /** @@ -321,14 +322,14 @@ template class OpsData { * * @return const std::vector& */ - const std::vector &getOpsInverses() const { return ops_inverses_; } + [[nodiscard]] auto getOpsInverses() const -> const std::vector & { return ops_inverses_; } /** * @brief Get the numerical matrix for a given unsupported operation. Given * entries are empty ({}) if not required. * * @return const std::vector>>& */ - const std::vector>> &getOpsMatrices() const { + [[nodiscard]] auto getOpsMatrices() const -> const std::vector>> & { return ops_matrices_; } @@ -339,7 +340,7 @@ template class OpsData { * @return true Gate is parametric (has parameters). * @return false Gate in non-parametric. */ - inline bool hasParams(size_t index) const { + [[nodiscard]] inline auto hasParams(size_t index) const -> bool { return !ops_params_[index].empty(); } @@ -348,14 +349,14 @@ template class OpsData { * * @return size_t */ - size_t getNumParOps() const { return num_par_ops_; } + [[nodiscard]] auto getNumParOps() const -> size_t { return num_par_ops_; } /** * @brief Get the number of non-parametric ops. * * @return size_t */ - size_t getNumNonParOps() const { return num_nonpar_ops_; } + [[nodiscard]] auto getNumNonParOps() const -> size_t { return num_nonpar_ops_; } }; /** @@ -366,9 +367,7 @@ template class OpsData { */ template class AdjointJacobian { private: - typedef void (*GeneratorFunc)(StateVectorManaged &sv, - const std::vector &wires, - const bool adj); // function pointer type + using GeneratorFunc = void (*)(StateVectorManaged &, const std::vector &, const bool); // function pointer type // Holds the mapping from gate labels to associated generator functions. const std::unordered_map generator_map{ @@ -498,8 +497,8 @@ template class AdjointJacobian { * @param tp_size * @return size_t */ - inline size_t getJacIndex(size_t obs_index, size_t tp_index, - size_t tp_size) { + inline auto getJacIndex(size_t obs_index, size_t tp_index, + size_t tp_size) -> size_t { return obs_index * tp_size + tp_index; } @@ -510,8 +509,8 @@ template class AdjointJacobian { * @param state_length * @return std::vector> */ - std::vector> - copyStateData(const std::complex *input_state, size_t state_length) { + auto + copyStateData(const std::complex *input_state, size_t state_length) -> std::vector> { return {input_state, input_state + state_length}; } @@ -525,15 +524,15 @@ template class AdjointJacobian { * @param adj Indicate whether to take the adjoint of the operation. * @return T Generator scaling coefficient. */ - inline T applyGenerator(StateVectorManaged &sv, + inline auto applyGenerator(StateVectorManaged &sv, const std::string &op_name, - const std::vector &wires, const bool adj) { + const std::vector &wires, const bool adj) -> T { generator_map.at(op_name)(sv, wires, adj); return scaling_factors.at(op_name); } public: - AdjointJacobian() {} + AdjointJacobian() = default; /** * @brief Utility to create a given operations object. @@ -546,12 +545,12 @@ template class AdjointJacobian { * @param ops_matrices Matrix definition of an operation if unsupported. * @return const OpsData */ - const OpsData createOpsData( + auto createOpsData( const std::vector &ops_name, const std::vector> &ops_params, const std::vector> &ops_wires, const std::vector &ops_inverses, - const std::vector>> &ops_matrices = {{}}) { + const std::vector>> &ops_matrices = {{}}) -> OpsData { return {ops_name, ops_params, ops_wires, ops_inverses, ops_matrices}; } @@ -600,18 +599,45 @@ template class AdjointJacobian { StateVectorManaged lambda(psi, num_elements); // Apply given operations to statevector if requested - if (apply_operations) + if (apply_operations) { applyOperations(lambda, operations); + } // Create observable-applied state-vectors std::vector> H_lambda(num_observables, {lambda.getNumQubits()}); + + // See https://www.openmp.org/wp-content/uploads/openmp-examples-4.5.0.pdf + std::exception_ptr ex = nullptr; + #if defined _OPENMP -#pragma omp parallel for +#pragma omp parallel default(none) shared(H_lambda, lambda, observables, num_observables, ex) +{ +#pragma omp for #endif for (size_t h_i = 0; h_i < num_observables; h_i++) { - H_lambda[h_i].updateData(lambda.getDataVector()); - applyObservable(H_lambda[h_i], observables[h_i]); + try { + H_lambda[h_i].updateData(lambda.getDataVector()); + applyObservable(H_lambda[h_i], observables[h_i]); + } + catch(...){ +#if defined _OPENMP +#pragma omp critical +#endif + ex = std::current_exception(); +#if defined _OPENMP +#pragma omp cancel for +#endif + } + } +#if defined _OPENMP + if(ex){ + #pragma omp cancel parallel + } +} +#endif + if(ex){ + std::rethrow_exception(ex); } StateVectorManaged mu(lambda.getNumQubits()); @@ -637,7 +663,7 @@ template class AdjointJacobian { (2 * (0b1 ^ operations.getOpsInverses()[op_idx]) - 1); #if defined _OPENMP -#pragma omp parallel for +#pragma omp parallel for default(none) shared(H_lambda, jac, mu, scalingFactor, trainableParamNumber, tp_it, num_observables) #endif for (size_t obs_idx = 0; obs_idx < num_observables; obs_idx++) { @@ -651,10 +677,32 @@ template class AdjointJacobian { current_param_idx--; } #if defined _OPENMP -#pragma omp parallel for +#pragma omp parallel default(none) shared(H_lambda, operations, op_idx, num_observables, ex) +{ +#pragma omp for #endif for (size_t obs_idx = 0; obs_idx < num_observables; obs_idx++) { - applyOperationAdj(H_lambda[obs_idx], operations, op_idx); + try{ + applyOperationAdj(H_lambda[obs_idx], operations, op_idx); + } + catch(...){ +#if defined _OPENMP +#pragma omp critical +#endif + ex = std::current_exception(); +#if defined _OPENMP +#pragma omp cancel for +#endif + } + } +#if defined _OPENMP + if(ex){ + #pragma omp cancel parallel + } +} +#endif + if(ex){ + std::rethrow_exception(ex); } } } From d9996b8e53617fda1f404fe4987fcf02e42321a8 Mon Sep 17 00:00:00 2001 From: "Lee J. O'Riordan" Date: Tue, 12 Oct 2021 12:55:22 +0100 Subject: [PATCH 22/45] Add auto fixes to Bindings --- pennylane_lightning/src/bindings/Bindings.cpp | 37 ++++++++++++------- 1 file changed, 23 insertions(+), 14 deletions(-) diff --git a/pennylane_lightning/src/bindings/Bindings.cpp b/pennylane_lightning/src/bindings/Bindings.cpp index 5deca679fe..b2e4ef2733 100644 --- a/pennylane_lightning/src/bindings/Bindings.cpp +++ b/pennylane_lightning/src/bindings/Bindings.cpp @@ -42,16 +42,19 @@ namespace py = pybind11; * @return StateVector `%StateVector` object. */ template -static StateVector create(const py::array_t> *numpyArray) { +static auto create(const py::array_t> *numpyArray) + -> StateVector { py::buffer_info numpyArrayInfo = numpyArray->request(); - if (numpyArrayInfo.ndim != 1) + if (numpyArrayInfo.ndim != 1) { throw std::invalid_argument( "NumPy array must be a 1-dimensional array"); - if (numpyArrayInfo.itemsize != sizeof(complex)) + } + if (numpyArrayInfo.itemsize != sizeof(complex)) { throw std::invalid_argument( "NumPy array must be of type np.complex64 or np.complex128"); - complex *data_ptr = static_cast *>(numpyArrayInfo.ptr); + } + auto *data_ptr = static_cast *>(numpyArrayInfo.ptr); return StateVector( {data_ptr, static_cast(numpyArrayInfo.shape[0])}); } @@ -658,17 +661,21 @@ void lightning_class_bindings(py::module &m) { auto buffer = param.request(); auto ptr = static_cast *>( buffer.ptr); - if (buffer.size > 0) + if (buffer.size > 0) { conv_params[p_idx] = - std::vector>{ - ptr, ptr + buffer.size}; + std::vector> { + ptr, ptr + buffer.size + } + }; } else if constexpr (std::is_same_v) { auto buffer = param.request(); - auto ptr = static_cast(buffer.ptr); - if (buffer.size > 0) - conv_params[p_idx] = std::vector{ - ptr, ptr + buffer.size}; + auto *ptr = static_cast(buffer.ptr); + if (buffer.size > 0) { + conv_params[p_idx] = std::vector { + ptr, ptr + buffer.size + } + }; } else { PL_ABORT( "Parameter datatype not current supported"); @@ -684,8 +691,9 @@ void lightning_class_bindings(py::module &m) { std::ostringstream obs_stream; std::string obs_name = obs.getObsName()[0]; for (size_t o = 1; o < obs.getObsName().size(); o++) { - if (o < obs.getObsName().size()) + if (o < obs.getObsName().size()) { obs_name += " @ "; + } obs_name += obs.getObsName()[o]; } obs_stream << "'wires' : " << obs.getObsWires(); @@ -742,8 +750,9 @@ void lightning_class_bindings(py::module &m) { ops_stream << ", 'params': " << ops.getOpsParams()[op]; ops_stream << ", 'inv': " << ops.getOpsInverses()[op]; ops_stream << "}"; - if (op < ops.getSize() - 1) + if (op < ops.getSize() - 1) { ops_stream << ","; + } } return "Operations: [" + ops_stream.str() + "]"; }); @@ -768,7 +777,7 @@ void lightning_class_bindings(py::module &m) { const auto p_buffer = ops_params[op].request(); const auto m_buffer = ops_matrices[op].request(); if (p_buffer.size > 0) { - const auto p_ptr = + const auto *const p_ptr = static_cast(p_buffer.ptr); conv_params[op] = std::vector{p_ptr, p_ptr + p_buffer.size}; From 66f896d98e62aadfe0c8be69fa2e3b7614241263 Mon Sep 17 00:00:00 2001 From: "Lee J. O'Riordan" Date: Tue, 12 Oct 2021 13:04:50 +0100 Subject: [PATCH 23/45] Fix formatting --- .../src/algorithms/AdjointDiff.hpp | 139 +++++++++++------- .../src/simulator/StateVector.hpp | 4 +- .../src/simulator/StateVectorManaged.hpp | 11 +- pennylane_lightning/src/util/Error.hpp | 6 +- 4 files changed, 98 insertions(+), 62 deletions(-) diff --git a/pennylane_lightning/src/algorithms/AdjointDiff.hpp b/pennylane_lightning/src/algorithms/AdjointDiff.hpp index 411bbb702a..0778dd7fb4 100644 --- a/pennylane_lightning/src/algorithms/AdjointDiff.hpp +++ b/pennylane_lightning/src/algorithms/AdjointDiff.hpp @@ -37,11 +37,13 @@ namespace { using namespace Pennylane; using namespace Pennylane::Util; -template static constexpr auto getP00() -> std::vector> { +template +static constexpr auto getP00() -> std::vector> { return {ONE(), ZERO(), ZERO(), ZERO()}; } -template static constexpr auto getP11() -> std::vector> { +template +static constexpr auto getP11() -> std::vector> { return {ZERO(), ZERO(), ZERO(), ONE()}; } @@ -166,7 +168,8 @@ template class ObsDatum { std::vector obs_params, std::vector> obs_wires) : obs_name_{std::move(obs_name)}, - obs_params_(std::move(obs_params)), obs_wires_{std::move(obs_wires)} {}; + obs_params_(std::move(obs_params)), obs_wires_{ + std::move(obs_wires)} {}; /** * @brief Move constructor for an ObsDatum object, representing a given @@ -196,19 +199,25 @@ template class ObsDatum { * * @return const std::vector& */ - [[nodiscard]] auto getObsName() const -> const std::vector & { return obs_name_; } + [[nodiscard]] auto getObsName() const -> const std::vector & { + return obs_name_; + } /** * @brief Get the parameters for the observable operations. * * @return const std::vector>& */ - [[nodiscard]] auto getObsParams() const -> const std::vector & { return obs_params_; } + [[nodiscard]] auto getObsParams() const + -> const std::vector & { + return obs_params_; + } /** * @brief Get the wires for each observable operation. * * @return const std::vector>& */ - [[nodiscard]] auto getObsWires() const -> const std::vector> & { + [[nodiscard]] auto getObsWires() const + -> const std::vector> & { return obs_wires_; } @@ -251,8 +260,10 @@ template class OpsData { std::vector> ops_wires, std::vector ops_inverses, std::vector>> ops_matrices) - : ops_name_{std::move(ops_name)}, ops_params_{ops_params}, ops_wires_{std::move(ops_wires)}, - ops_inverses_{std::move(ops_inverses)}, ops_matrices_{std::move(ops_matrices)} { + : ops_name_{std::move(ops_name)}, ops_params_{ops_params}, + ops_wires_{std::move(ops_wires)}, + ops_inverses_{std::move(ops_inverses)}, ops_matrices_{ + std::move(ops_matrices)} { num_par_ops_ = 0; for (const auto &p : ops_params) { if (p.size() > 0) { @@ -276,8 +287,10 @@ template class OpsData { const std::vector> &ops_params, std::vector> ops_wires, std::vector ops_inverses) - : ops_name_{ops_name}, ops_params_{ops_params}, ops_wires_{std::move(ops_wires)}, - ops_inverses_{std::move(ops_inverses)}, ops_matrices_(ops_name.size()) { + : ops_name_{ops_name}, ops_params_{ops_params}, + ops_wires_{std::move(ops_wires)}, ops_inverses_{std::move( + ops_inverses)}, + ops_matrices_(ops_name.size()) { num_par_ops_ = 0; for (const auto &p : ops_params) { if (p.size() > 0) { @@ -299,14 +312,17 @@ template class OpsData { * * @return const std::vector& */ - [[nodiscard]] auto getOpsName() const -> const std::vector & { return ops_name_; } + [[nodiscard]] auto getOpsName() const -> const std::vector & { + return ops_name_; + } /** * @brief Get the (optional) parameters for each operation. Given entries * are empty ({}) if not required. * * @return const std::vector>& */ - [[nodiscard]] auto getOpsParams() const -> const std::vector> & { + [[nodiscard]] auto getOpsParams() const + -> const std::vector> & { return ops_params_; } /** @@ -314,7 +330,8 @@ template class OpsData { * * @return const std::vector>& */ - [[nodiscard]] auto getOpsWires() const -> const std::vector> & { + [[nodiscard]] auto getOpsWires() const + -> const std::vector> & { return ops_wires_; } /** @@ -322,14 +339,17 @@ template class OpsData { * * @return const std::vector& */ - [[nodiscard]] auto getOpsInverses() const -> const std::vector & { return ops_inverses_; } + [[nodiscard]] auto getOpsInverses() const -> const std::vector & { + return ops_inverses_; + } /** * @brief Get the numerical matrix for a given unsupported operation. Given * entries are empty ({}) if not required. * * @return const std::vector>>& */ - [[nodiscard]] auto getOpsMatrices() const -> const std::vector>> & { + [[nodiscard]] auto getOpsMatrices() const + -> const std::vector>> & { return ops_matrices_; } @@ -356,7 +376,9 @@ template class OpsData { * * @return size_t */ - [[nodiscard]] auto getNumNonParOps() const -> size_t { return num_nonpar_ops_; } + [[nodiscard]] auto getNumNonParOps() const -> size_t { + return num_nonpar_ops_; + } }; /** @@ -367,7 +389,9 @@ template class OpsData { */ template class AdjointJacobian { private: - using GeneratorFunc = void (*)(StateVectorManaged &, const std::vector &, const bool); // function pointer type + using GeneratorFunc = void (*)(StateVectorManaged &, + const std::vector &, + const bool); // function pointer type // Holds the mapping from gate labels to associated generator functions. const std::unordered_map generator_map{ @@ -497,8 +521,8 @@ template class AdjointJacobian { * @param tp_size * @return size_t */ - inline auto getJacIndex(size_t obs_index, size_t tp_index, - size_t tp_size) -> size_t { + inline auto getJacIndex(size_t obs_index, size_t tp_index, size_t tp_size) + -> size_t { return obs_index * tp_size + tp_index; } @@ -509,8 +533,8 @@ template class AdjointJacobian { * @param state_length * @return std::vector> */ - auto - copyStateData(const std::complex *input_state, size_t state_length) -> std::vector> { + auto copyStateData(const std::complex *input_state, size_t state_length) + -> std::vector> { return {input_state, input_state + state_length}; } @@ -525,8 +549,9 @@ template class AdjointJacobian { * @return T Generator scaling coefficient. */ inline auto applyGenerator(StateVectorManaged &sv, - const std::string &op_name, - const std::vector &wires, const bool adj) -> T { + const std::string &op_name, + const std::vector &wires, const bool adj) + -> T { generator_map.at(op_name)(sv, wires, adj); return scaling_factors.at(op_name); } @@ -550,7 +575,8 @@ template class AdjointJacobian { const std::vector> &ops_params, const std::vector> &ops_wires, const std::vector &ops_inverses, - const std::vector>> &ops_matrices = {{}}) -> OpsData { + const std::vector>> &ops_matrices = {{}}) + -> OpsData { return {ops_name, ops_params, ops_wires, ops_inverses, ops_matrices}; } @@ -607,36 +633,37 @@ template class AdjointJacobian { std::vector> H_lambda(num_observables, {lambda.getNumQubits()}); - // See https://www.openmp.org/wp-content/uploads/openmp-examples-4.5.0.pdf + // See + // https://www.openmp.org/wp-content/uploads/openmp-examples-4.5.0.pdf std::exception_ptr ex = nullptr; #if defined _OPENMP -#pragma omp parallel default(none) shared(H_lambda, lambda, observables, num_observables, ex) -{ +#pragma omp parallel default(none) \ + shared(H_lambda, lambda, observables, num_observables, ex) + { #pragma omp for #endif - for (size_t h_i = 0; h_i < num_observables; h_i++) { - try { - H_lambda[h_i].updateData(lambda.getDataVector()); - applyObservable(H_lambda[h_i], observables[h_i]); - } - catch(...){ + for (size_t h_i = 0; h_i < num_observables; h_i++) { + try { + H_lambda[h_i].updateData(lambda.getDataVector()); + applyObservable(H_lambda[h_i], observables[h_i]); + } catch (...) { #if defined _OPENMP #pragma omp critical #endif - ex = std::current_exception(); + ex = std::current_exception(); #if defined _OPENMP #pragma omp cancel for #endif + } } - } #if defined _OPENMP - if(ex){ - #pragma omp cancel parallel + if (ex) { +#pragma omp cancel parallel + } } -} #endif - if(ex){ + if (ex) { std::rethrow_exception(ex); } @@ -663,7 +690,9 @@ template class AdjointJacobian { (2 * (0b1 ^ operations.getOpsInverses()[op_idx]) - 1); #if defined _OPENMP -#pragma omp parallel for default(none) shared(H_lambda, jac, mu, scalingFactor, trainableParamNumber, tp_it, num_observables) +#pragma omp parallel for default(none) \ + shared(H_lambda, jac, mu, scalingFactor, trainableParamNumber, tp_it, \ + num_observables) #endif for (size_t obs_idx = 0; obs_idx < num_observables; obs_idx++) { @@ -677,31 +706,33 @@ template class AdjointJacobian { current_param_idx--; } #if defined _OPENMP -#pragma omp parallel default(none) shared(H_lambda, operations, op_idx, num_observables, ex) -{ -#pragma omp for +#pragma omp parallel default(none) \ + shared(H_lambda, operations, op_idx, num_observables, ex) + { +#pragma omp for #endif - for (size_t obs_idx = 0; obs_idx < num_observables; obs_idx++) { - try{ - applyOperationAdj(H_lambda[obs_idx], operations, op_idx); - } - catch(...){ + for (size_t obs_idx = 0; obs_idx < num_observables; + obs_idx++) { + try { + applyOperationAdj(H_lambda[obs_idx], operations, + op_idx); + } catch (...) { #if defined _OPENMP #pragma omp critical #endif - ex = std::current_exception(); + ex = std::current_exception(); #if defined _OPENMP #pragma omp cancel for #endif + } } - } #if defined _OPENMP - if(ex){ - #pragma omp cancel parallel + if (ex) { +#pragma omp cancel parallel + } } -} #endif - if(ex){ + if (ex) { std::rethrow_exception(ex); } } diff --git a/pennylane_lightning/src/simulator/StateVector.hpp b/pennylane_lightning/src/simulator/StateVector.hpp index 5437da7e91..11102af327 100644 --- a/pennylane_lightning/src/simulator/StateVector.hpp +++ b/pennylane_lightning/src/simulator/StateVector.hpp @@ -323,7 +323,9 @@ template class StateVector { * * @return std::size_t */ - [[nodiscard]] auto getNumQubits() const -> std::size_t { return num_qubits_; } + [[nodiscard]] auto getNumQubits() const -> std::size_t { + return num_qubits_; + } /** * @brief Apply a single gate to the state-vector. diff --git a/pennylane_lightning/src/simulator/StateVectorManaged.hpp b/pennylane_lightning/src/simulator/StateVectorManaged.hpp index 2ede5988ca..8c81bd5ca6 100644 --- a/pennylane_lightning/src/simulator/StateVectorManaged.hpp +++ b/pennylane_lightning/src/simulator/StateVectorManaged.hpp @@ -57,7 +57,8 @@ class StateVectorManaged : public StateVector { StateVector::setData(data_.data()); } - auto operator=(const StateVectorManaged &other) -> StateVectorManaged & { + auto operator=(const StateVectorManaged &other) + -> StateVectorManaged & { if (this != &other) { if (data_.size() != other.getLength()) { data_.resize(other.getLength()); @@ -72,13 +73,13 @@ class StateVectorManaged : public StateVector { auto getDataVector() -> std::vector & { return data_; } auto getDataVector() const -> const std::vector & { return data_; } - auto - getInternalIndices(const std::vector &qubit_indices) -> std::vector { + auto getInternalIndices(const std::vector &qubit_indices) + -> std::vector { return StateVector::generateBitPatterns(qubit_indices, Util::log2(data_.size())); } - auto - getExternalIndices(const std::vector &qubit_indices) -> std::vector { + auto getExternalIndices(const std::vector &qubit_indices) + -> std::vector { std::vector externalWires = StateVector::getIndicesAfterExclusion( qubit_indices, Util::log2(data_.size())); diff --git a/pennylane_lightning/src/util/Error.hpp b/pennylane_lightning/src/util/Error.hpp index 7cdda41ecf..9fd0c4f677 100644 --- a/pennylane_lightning/src/util/Error.hpp +++ b/pennylane_lightning/src/util/Error.hpp @@ -78,8 +78,10 @@ class LightningException : public std::exception { template < typename T, - std::enable_if_t::type, std::string>::value, - int> = 0> + std::enable_if_t< + std::is_convertible::type, + std::string>::value, + int> = 0> explicit LightningException(T &&err_msg) noexcept : err_msg{std::forward(err_msg)} {} From b533b89dab30f8e50a2d0ffc15c66f89d9c2fc80 Mon Sep 17 00:00:00 2001 From: "Lee J. O'Riordan" Date: Tue, 12 Oct 2021 13:05:38 +0100 Subject: [PATCH 24/45] Fix binding modernization --- pennylane_lightning/src/.clang-tidy | 2 +- pennylane_lightning/src/bindings/Bindings.cpp | 17 ++++++++--------- 2 files changed, 9 insertions(+), 10 deletions(-) diff --git a/pennylane_lightning/src/.clang-tidy b/pennylane_lightning/src/.clang-tidy index dc64a71352..d7ec884d2d 100644 --- a/pennylane_lightning/src/.clang-tidy +++ b/pennylane_lightning/src/.clang-tidy @@ -180,7 +180,7 @@ CheckOptions: - key: google-readability-namespace-comments.SpacesBeforeComments value: '2' - key: readability-function-cognitive-complexity.Threshold - value: '40' + value: '45' - key: readability-function-cognitive-complexity.IgnoreMacros value: 'true' - key: cppcoreguidelines-non-private-member-variables-in-classes.IgnoreClassesWithAllMemberVariablesBeingPublic diff --git a/pennylane_lightning/src/bindings/Bindings.cpp b/pennylane_lightning/src/bindings/Bindings.cpp index b2e4ef2733..c40977b95b 100644 --- a/pennylane_lightning/src/bindings/Bindings.cpp +++ b/pennylane_lightning/src/bindings/Bindings.cpp @@ -663,19 +663,17 @@ void lightning_class_bindings(py::module &m) { buffer.ptr); if (buffer.size > 0) { conv_params[p_idx] = - std::vector> { - ptr, ptr + buffer.size - } - }; + std::vector>{ + ptr, ptr + buffer.size}; + } } else if constexpr (std::is_same_v) { auto buffer = param.request(); auto *ptr = static_cast(buffer.ptr); if (buffer.size > 0) { - conv_params[p_idx] = std::vector { - ptr, ptr + buffer.size - } - }; + conv_params[p_idx] = std::vector{ + ptr, ptr + buffer.size}; + } } else { PL_ABORT( "Parameter datatype not current supported"); @@ -812,7 +810,8 @@ void lightning_class_bindings(py::module &m) { /** * @brief Add C++ classes, methods and functions to Python module. */ -PYBIND11_MODULE(lightning_qubit_ops, m) { +PYBIND11_MODULE(lightning_qubit_ops, + m) { // NOLINT: No control over Pybind internals // Suppress doxygen autogenerated signatures py::options options; From 74584170789e9f9f0d3b7e158dc3e754869377ce Mon Sep 17 00:00:00 2001 From: "Lee J. O'Riordan" Date: Tue, 12 Oct 2021 16:26:32 +0100 Subject: [PATCH 25/45] Fix test conformance --- pennylane_lightning/src/.clang-tidy | 2 +- .../src/algorithms/AdjointDiff.hpp | 4 +- pennylane_lightning/src/bindings/Bindings.cpp | 4 +- pennylane_lightning/src/tests/TestHelpers.hpp | 12 ++- .../src/tests/Test_AdjDiff.cpp | 74 ++++++++++++++----- .../Test_StateVectorManaged_Nonparam.cpp | 11 +-- .../tests/Test_StateVectorManaged_Param.cpp | 4 + .../src/tests/Test_StateVector_Nonparam.cpp | 18 +++-- .../src/tests/Test_StateVector_Param.cpp | 4 + pennylane_lightning/src/tests/Test_Util.cpp | 1 + pennylane_lightning/src/util/Error.hpp | 10 +-- 11 files changed, 95 insertions(+), 49 deletions(-) diff --git a/pennylane_lightning/src/.clang-tidy b/pennylane_lightning/src/.clang-tidy index d7ec884d2d..17f1e2ec5c 100644 --- a/pennylane_lightning/src/.clang-tidy +++ b/pennylane_lightning/src/.clang-tidy @@ -1,5 +1,5 @@ --- -Checks: 'clang-diagnostic-*,clang-analyzer-*,-*,-llvmlibc-*,modernize-*,clang-analyzer-cplusplus*,openmp-*,performance-*,portability-*,readability-*' +Checks: 'clang-diagnostic-*,clang-analyzer-*,-*,-llvmlibc-*,modernize-*,-modernize-use-trailing-return-type,clang-analyzer-cplusplus*,openmp-*,performance-*,portability-*,readability-*' WarningsAsErrors: '*' HeaderFilterRegex: '.*' AnalyzeTemporaryDtors: false diff --git a/pennylane_lightning/src/algorithms/AdjointDiff.hpp b/pennylane_lightning/src/algorithms/AdjointDiff.hpp index 0778dd7fb4..cce0e9ff08 100644 --- a/pennylane_lightning/src/algorithms/AdjointDiff.hpp +++ b/pennylane_lightning/src/algorithms/AdjointDiff.hpp @@ -182,11 +182,11 @@ template class ObsDatum { * @param obs_wires Wires upon which to apply operation. Each observable * operation will be a separate nested list. */ - ObsDatum(std::vector &&obs_name, + /*ObsDatum(std::vector &&obs_name, std::vector &&obs_params, std::vector> &&obs_wires) : obs_name_{std::move(obs_name)}, obs_params_{std::move(obs_params)}, - obs_wires_{std::move(obs_wires)} {}; + obs_wires_{std::move(obs_wires)} {};*/ /** * @brief Get the number of operations in observable. diff --git a/pennylane_lightning/src/bindings/Bindings.cpp b/pennylane_lightning/src/bindings/Bindings.cpp index c40977b95b..1400770fad 100644 --- a/pennylane_lightning/src/bindings/Bindings.cpp +++ b/pennylane_lightning/src/bindings/Bindings.cpp @@ -810,8 +810,8 @@ void lightning_class_bindings(py::module &m) { /** * @brief Add C++ classes, methods and functions to Python module. */ -PYBIND11_MODULE(lightning_qubit_ops, - m) { // NOLINT: No control over Pybind internals +PYBIND11_MODULE(lightning_qubit_ops, // NOLINT: No control over Pybind internals + m) { // Suppress doxygen autogenerated signatures py::options options; diff --git a/pennylane_lightning/src/tests/TestHelpers.hpp b/pennylane_lightning/src/tests/TestHelpers.hpp index 92cd70ffd1..f47639d3cb 100644 --- a/pennylane_lightning/src/tests/TestHelpers.hpp +++ b/pennylane_lightning/src/tests/TestHelpers.hpp @@ -15,8 +15,9 @@ inline bool isApproxEqual( const std::vector &data1, const std::vector &data2, const typename Data_t::value_type eps = std::numeric_limits::epsilon() * 100) { - if (data1.size() != data2.size()) + if (data1.size() != data2.size()) { return false; + } for (size_t i = 0; i < data1.size(); i++) { if (data1[i].real() != Approx(data2[i].real()).epsilon(eps) || @@ -39,14 +40,11 @@ inline bool isApproxEqual( template inline bool isApproxEqual(const Data_t &data1, const Data_t &data2, - const typename Data_t::value_type eps = + typename Data_t::value_type eps = std::numeric_limits::epsilon() * 100) { - if (data1.real() != Approx(data2.real()).epsilon(eps) || - data1.imag() != Approx(data2.imag()).epsilon(eps)) { - return false; - } - return true; + return !(data1.real() != Approx(data2.real()).epsilon(eps) || + data1.imag() != Approx(data2.imag()).epsilon(eps)); } /** diff --git a/pennylane_lightning/src/tests/Test_AdjDiff.cpp b/pennylane_lightning/src/tests/Test_AdjDiff.cpp index 32ce945cf1..13b13c32ec 100644 --- a/pennylane_lightning/src/tests/Test_AdjDiff.cpp +++ b/pennylane_lightning/src/tests/Test_AdjDiff.cpp @@ -35,11 +35,12 @@ TEMPLATE_TEST_CASE("AdjointJacobian::AdjointJacobian", "[AdjointJacobian]", } } -TEST_CASE("AdjointJacobian::adjointJacobian", "[AdjointJacobian]") { +TEST_CASE("AdjointJacobian::adjointJacobian Op=RX, Obs=Z", + "[AdjointJacobian]") { AdjointJacobian adj; std::vector param{-M_PI / 7, M_PI / 5, 2 * M_PI / 3}; - SECTION("RX gradient") { + { const size_t num_qubits = 1; const size_t num_params = 3; const size_t num_obs = 1; @@ -60,8 +61,12 @@ TEST_CASE("AdjointJacobian::adjointJacobian", "[AdjointJacobian]") { CHECK(-sin(p) == Approx(jacobian[0].front())); } } - - SECTION("RY gradient") { +} +TEST_CASE("AdjointJacobian::adjointJacobian Op=RY, Obs=X", + "[AdjointJacobian]") { + AdjointJacobian adj; + std::vector param{-M_PI / 7, M_PI / 5, 2 * M_PI / 3}; + { const size_t num_qubits = 1; const size_t num_params = 3; const size_t num_obs = 1; @@ -85,7 +90,12 @@ TEST_CASE("AdjointJacobian::adjointJacobian", "[AdjointJacobian]") { CHECK(cos(p) == Approx(jacobian[0].front()).margin(1e-7)); } } - SECTION("Single RX gradient, 2 expval") { +} +TEST_CASE("AdjointJacobian::adjointJacobian Op=RX, Obs=[Z,Z]", + "[AdjointJacobian]") { + AdjointJacobian adj; + std::vector param{-M_PI / 7, M_PI / 5, 2 * M_PI / 3}; + { const size_t num_qubits = 2; const size_t num_params = 1; const size_t num_obs = 2; @@ -108,7 +118,12 @@ TEST_CASE("AdjointJacobian::adjointJacobian", "[AdjointJacobian]") { CHECK(-sin(param[0]) == Approx(jacobian[0][0]).margin(1e-7)); CHECK(0.0 == Approx(jacobian[1][1]).margin(1e-7)); } - SECTION("Multiple RX gradient, single expval per wire") { +} +TEST_CASE("AdjointJacobian::adjointJacobian Op=[RX,RX,RX], Obs=[Z,Z,Z]", + "[AdjointJacobian]") { + AdjointJacobian adj; + std::vector param{-M_PI / 7, M_PI / 5, 2 * M_PI / 3}; + { const size_t num_qubits = 3; const size_t num_params = 3; const size_t num_obs = 3; @@ -135,7 +150,13 @@ TEST_CASE("AdjointJacobian::adjointJacobian", "[AdjointJacobian]") { CHECK(-sin(param[1]) == Approx(jacobian[1][1]).margin(1e-7)); CHECK(-sin(param[2]) == Approx(jacobian[2][2]).margin(1e-7)); } - SECTION("Multiple RX gradient, single expval per wire, subset of params") { +} +TEST_CASE("AdjointJacobian::adjointJacobian Op=[RX,RX,RX], Obs=[Z,Z,Z], " + "TParams=[0,2]", + "[AdjointJacobian]") { + AdjointJacobian adj; + std::vector param{-M_PI / 7, M_PI / 5, 2 * M_PI / 3}; + { const size_t num_qubits = 3; const size_t num_params = 3; const size_t num_obs = 3; @@ -163,7 +184,12 @@ TEST_CASE("AdjointJacobian::adjointJacobian", "[AdjointJacobian]") { CHECK(0 == Approx(jacobian[1][1]).margin(1e-7)); CHECK(-sin(param[2]) == Approx(jacobian[2][1]).margin(1e-7)); } - SECTION("Multiple RX gradient, tensor expval") { +} +TEST_CASE("AdjointJacobian::adjointJacobian Op=[RX,RX,RX], Obs=[ZZZ]", + "[AdjointJacobian]") { + AdjointJacobian adj; + std::vector param{-M_PI / 7, M_PI / 5, 2 * M_PI / 3}; + { const size_t num_qubits = 3; const size_t num_params = 3; const size_t num_obs = 1; @@ -189,8 +215,12 @@ TEST_CASE("AdjointJacobian::adjointJacobian", "[AdjointJacobian]") { CHECK(0.26478810666384334 == Approx(jacobian[0][1]).margin(1e-7)); CHECK(-0.6312451595102775 == Approx(jacobian[0][2]).margin(1e-7)); } - - SECTION("Mixed gradient, tensor expval") { +} +TEST_CASE("AdjointJacobian::adjointJacobian Op=Mixed, Obs=[XXX]", + "[AdjointJacobian]") { + AdjointJacobian adj; + std::vector param{-M_PI / 7, M_PI / 5, 2 * M_PI / 3}; + { const size_t num_qubits = 3; const size_t num_params = 6; const size_t num_obs = 1; @@ -228,8 +258,13 @@ TEST_CASE("AdjointJacobian::adjointJacobian", "[AdjointJacobian]") { CHECK(-0.0129093062 == Approx(jacobian[0][4]).margin(1e-7)); CHECK(0.323846156 == Approx(jacobian[0][5]).margin(1e-7)); } - - SECTION("Decomposed Rot gate, non computational basis state") { +} +TEST_CASE("AdjointJacobian::adjointJacobian Decomposed Rot gate, non " + "computational basis state", + "[AdjointJacobian]") { + AdjointJacobian adj; + std::vector param{-M_PI / 7, M_PI / 5, 2 * M_PI / 3}; + { const size_t num_qubits = 1; const size_t num_params = 3; const size_t num_obs = 1; @@ -274,7 +309,12 @@ TEST_CASE("AdjointJacobian::adjointJacobian", "[AdjointJacobian]") { Approx(jacobian[0][2]).margin(1e-7)); } } - SECTION("Trainable params subset") { +} +TEST_CASE("AdjointJacobian::adjointJacobian Mixed Ops, Obs and TParams", + "[AdjointJacobian]") { + AdjointJacobian adj; + std::vector param{-M_PI / 7, M_PI / 5, 2 * M_PI / 3}; + { const size_t num_qubits = 2; const std::set t_params{1, 2, 3}; const size_t num_obs = 1; @@ -312,11 +352,11 @@ TEST_CASE("AdjointJacobian::adjointJacobian", "[AdjointJacobian]") { adj.adjointJacobian(psi.getData(), psi.getLength(), jacobian, {obs}, ops, t_params, true); - CAPTURE(jacobian); + std::vector expected{-0.71429188, 0.04998561, -0.71904837}; // Computed with PennyLane using default.qubit - CHECK(-0.71429188 == Approx(jacobian[0][0])); - CHECK(0.04998561 == Approx(jacobian[0][1])); - CHECK(-0.71904837 == Approx(jacobian[0][2])); + CHECK(expected[0] == Approx(jacobian[0][0])); + CHECK(expected[1] == Approx(jacobian[0][1])); + CHECK(expected[2] == Approx(jacobian[0][2])); } } diff --git a/pennylane_lightning/src/tests/Test_StateVectorManaged_Nonparam.cpp b/pennylane_lightning/src/tests/Test_StateVectorManaged_Nonparam.cpp index a0d020d26d..3db5f00942 100644 --- a/pennylane_lightning/src/tests/Test_StateVectorManaged_Nonparam.cpp +++ b/pennylane_lightning/src/tests/Test_StateVectorManaged_Nonparam.cpp @@ -345,6 +345,7 @@ TEMPLATE_TEST_CASE("StateVectorManaged::applyCNOT", } } +// NOLINTNEXTLINE: Avoiding complexity errors TEMPLATE_TEST_CASE("StateVectorManaged::applySWAP", "[StateVectorManaged_Nonparam]", float, double) { using cp_t = std::complex; @@ -532,7 +533,7 @@ TEMPLATE_TEST_CASE("StateVectorManaged::applyCZ", } SECTION("CZ0,2 |+10> -> |+10>") { - std::vector expected{init_state}; + const std::vector &expected{init_state}; StateVectorManaged svdat02{init_state}; StateVectorManaged svdat20{init_state}; @@ -545,7 +546,7 @@ TEMPLATE_TEST_CASE("StateVectorManaged::applyCZ", CHECK(svdat20.getDataVector() == expected); } SECTION("CZ1,2 |+10> -> |+10>") { - std::vector expected{init_state}; + const std::vector &expected{init_state}; StateVectorManaged svdat12{init_state}; StateVectorManaged svdat21{init_state}; @@ -632,7 +633,7 @@ TEMPLATE_TEST_CASE("StateVectorManaged::applyToffoli", CHECK(svdat102.getDataVector() == expected); } SECTION("Toffoli 0,2,1 |+10> -> |+10>") { - std::vector expected{init_state}; + const std::vector &expected{init_state}; StateVectorManaged svdat021{init_state}; @@ -642,7 +643,7 @@ TEMPLATE_TEST_CASE("StateVectorManaged::applyToffoli", CHECK(svdat021.getDataVector() == expected); } SECTION("Toffoli 1,2,0 |+10> -> |+10>") { - std::vector expected{init_state}; + const std::vector &expected{init_state}; StateVectorManaged svdat120{init_state}; @@ -723,7 +724,7 @@ TEMPLATE_TEST_CASE("StateVectorManaged::applyCSWAP", CHECK(svdat102.getDataVector() == expected); } SECTION("CSWAP 2,1,0 |+10> -> |+10>") { - std::vector expected{init_state}; + const std::vector &expected{init_state}; StateVectorManaged svdat021{init_state}; diff --git a/pennylane_lightning/src/tests/Test_StateVectorManaged_Param.cpp b/pennylane_lightning/src/tests/Test_StateVectorManaged_Param.cpp index 2c34314cd6..b553222a13 100644 --- a/pennylane_lightning/src/tests/Test_StateVectorManaged_Param.cpp +++ b/pennylane_lightning/src/tests/Test_StateVectorManaged_Param.cpp @@ -110,6 +110,7 @@ TEMPLATE_TEST_CASE("StateVectorManaged::applyRZ", "[StateVectorManaged_Param]", const cp_t coef(1.0 / (2 * std::sqrt(2)), 0); std::vector> rz_data; + rz_data.reserve(angles.size()); for (auto &a : angles) { rz_data.push_back(Gates::getRZ(a)); } @@ -172,6 +173,7 @@ TEMPLATE_TEST_CASE("StateVectorManaged::applyPhaseShift", const cp_t coef(1.0 / (2 * std::sqrt(2)), 0); std::vector> ps_data; + ps_data.reserve(angles.size()); for (auto &a : angles) { ps_data.push_back(Gates::getPhaseShift(a)); } @@ -235,6 +237,7 @@ TEMPLATE_TEST_CASE("StateVectorManaged::applyControlledPhaseShift", const cp_t coef(1.0 / (2 * std::sqrt(2)), 0); std::vector> ps_data; + ps_data.reserve(angles.size()); for (auto &a : angles) { ps_data.push_back(Gates::getPhaseShift(a)); } @@ -367,6 +370,7 @@ TEMPLATE_TEST_CASE("StateVectorManaged::applyCRot", } } +// NOLINTNEXTLINE: Avoid complexity errors TEMPLATE_TEST_CASE("StateVectorManaged::applyMatrix 1 wire", "[StateVectorManaged_Param]", float, double) { using cp_t = std::complex; diff --git a/pennylane_lightning/src/tests/Test_StateVector_Nonparam.cpp b/pennylane_lightning/src/tests/Test_StateVector_Nonparam.cpp index 18ed35b7e6..5d77cec157 100644 --- a/pennylane_lightning/src/tests/Test_StateVector_Nonparam.cpp +++ b/pennylane_lightning/src/tests/Test_StateVector_Nonparam.cpp @@ -69,9 +69,9 @@ template struct SVData { cdata[0] = std::complex{1, 0}; } explicit SVData(size_t num_qubits, - const std::vector> &cdata_input) + std::vector> cdata_input) : num_qubits{num_qubits}, // qubit_indices{num_qubits}, - cdata(cdata_input), sv{cdata.data(), cdata.size()} {} + cdata(std::move(cdata_input)), sv{cdata.data(), cdata.size()} {} vector getInternalIndices(const std::vector &qubit_indices) { return sv.generateBitPatterns(qubit_indices); @@ -444,6 +444,7 @@ TEMPLATE_TEST_CASE("StateVector::applyCNOT", "[StateVector_Nonparam]", float, } } +// NOLINTNEXTLINE: Avoiding complexity errors TEMPLATE_TEST_CASE("StateVector::applySWAP", "[StateVector_Nonparam]", float, double) { using cp_t = std::complex; @@ -588,6 +589,7 @@ TEMPLATE_TEST_CASE("StateVector::applySWAP", "[StateVector_Nonparam]", float, } } +// NOLINTNEXTLINE: Avoiding complexity errors TEMPLATE_TEST_CASE("StateVector::applyCZ", "[StateVector_Nonparam]", float, double) { using cp_t = std::complex; @@ -631,7 +633,7 @@ TEMPLATE_TEST_CASE("StateVector::applyCZ", "[StateVector_Nonparam]", float, } SECTION("CZ0,2 |+10> -> |+10>") { - std::vector expected{init_state}; + const std::vector &expected{init_state}; SVData svdat02{num_qubits, init_state}; SVData svdat20{num_qubits, init_state}; @@ -644,7 +646,7 @@ TEMPLATE_TEST_CASE("StateVector::applyCZ", "[StateVector_Nonparam]", float, CHECK(svdat20.cdata == expected); } SECTION("CZ1,2 |+10> -> |+10>") { - std::vector expected{init_state}; + const std::vector &expected{init_state}; SVData svdat12{num_qubits, init_state}; SVData svdat21{num_qubits, init_state}; @@ -681,6 +683,7 @@ TEMPLATE_TEST_CASE("StateVector::applyCZ", "[StateVector_Nonparam]", float, } } +// NOLINTNEXTLINE: Avoiding complexity errors TEMPLATE_TEST_CASE("StateVector::applyToffoli", "[StateVector_Nonparam]", float, double) { using cp_t = std::complex; @@ -733,7 +736,7 @@ TEMPLATE_TEST_CASE("StateVector::applyToffoli", "[StateVector_Nonparam]", float, CHECK(svdat102.cdata == expected); } SECTION("Toffoli 0,2,1 |+10> -> |+10>") { - std::vector expected{init_state}; + const std::vector &expected{init_state}; SVData svdat021{num_qubits, init_state}; @@ -744,7 +747,7 @@ TEMPLATE_TEST_CASE("StateVector::applyToffoli", "[StateVector_Nonparam]", float, CHECK(svdat021.cdata == expected); } SECTION("Toffoli 1,2,0 |+10> -> |+10>") { - std::vector expected{init_state}; + const std::vector &expected{init_state}; SVData svdat120{num_qubits, init_state}; @@ -779,6 +782,7 @@ TEMPLATE_TEST_CASE("StateVector::applyToffoli", "[StateVector_Nonparam]", float, } } +// NOLINTNEXTLINE: Avoiding complexity errors TEMPLATE_TEST_CASE("StateVector::applyCSWAP", "[StateVector_Nonparam]", float, double) { using cp_t = std::complex; @@ -826,7 +830,7 @@ TEMPLATE_TEST_CASE("StateVector::applyCSWAP", "[StateVector_Nonparam]", float, CHECK(svdat102.cdata == expected); } SECTION("CSWAP 2,1,0 |+10> -> |+10>") { - std::vector expected{init_state}; + const std::vector &expected{init_state}; SVData svdat021{num_qubits, init_state}; diff --git a/pennylane_lightning/src/tests/Test_StateVector_Param.cpp b/pennylane_lightning/src/tests/Test_StateVector_Param.cpp index 683128a360..62d2fd1d7e 100644 --- a/pennylane_lightning/src/tests/Test_StateVector_Param.cpp +++ b/pennylane_lightning/src/tests/Test_StateVector_Param.cpp @@ -213,6 +213,7 @@ TEMPLATE_TEST_CASE("StateVector::applyRZ", "[StateVector_Param]", float, const cp_t coef(1.0 / (2 * std::sqrt(2)), 0); std::vector> rz_data; + rz_data.reserve(angles.size()); for (auto &a : angles) { rz_data.push_back(Gates::getRZ(a)); } @@ -273,6 +274,7 @@ TEMPLATE_TEST_CASE("StateVector::applyPhaseShift", "[StateVector_Param]", float, const cp_t coef(1.0 / (2 * std::sqrt(2)), 0); std::vector> ps_data; + ps_data.reserve(angles.size()); for (auto &a : angles) { ps_data.push_back(Gates::getPhaseShift(a)); } @@ -334,6 +336,7 @@ TEMPLATE_TEST_CASE("StateVector::applyControlledPhaseShift", const cp_t coef(1.0 / (2 * std::sqrt(2)), 0); std::vector> ps_data; + ps_data.reserve(angles.size()); for (auto &a : angles) { ps_data.push_back(Gates::getPhaseShift(a)); } @@ -462,6 +465,7 @@ TEMPLATE_TEST_CASE("StateVector::applyCRot", "[StateVector_Param]", float, } } +// NOLINTNEXTLINE: Avoid complexity errors TEMPLATE_TEST_CASE("StateVector::applyMatrix 1 wire", "[StateVector_Param]", float, double) { using cp_t = std::complex; diff --git a/pennylane_lightning/src/tests/Test_Util.cpp b/pennylane_lightning/src/tests/Test_Util.cpp index c6cffb29fd..f249e3d9bd 100644 --- a/pennylane_lightning/src/tests/Test_Util.cpp +++ b/pennylane_lightning/src/tests/Test_Util.cpp @@ -55,6 +55,7 @@ TEMPLATE_TEST_CASE("Constant values", "[Util]", float, double) { } } +// NOLINTNEXTLINE: Avoid complexity errors TEMPLATE_TEST_CASE("Utility math functions", "[Util]", float, double) { SECTION("exp2: 2^n") { for (size_t i = 0; i < 10; i++) { diff --git a/pennylane_lightning/src/util/Error.hpp b/pennylane_lightning/src/util/Error.hpp index 9fd0c4f677..0b780e9218 100644 --- a/pennylane_lightning/src/util/Error.hpp +++ b/pennylane_lightning/src/util/Error.hpp @@ -76,14 +76,8 @@ class LightningException : public std::exception { * @param err_msg Error message explaining the exception condition. */ - template < - typename T, - std::enable_if_t< - std::is_convertible::type, - std::string>::value, - int> = 0> - explicit LightningException(T &&err_msg) noexcept - : err_msg{std::forward(err_msg)} {} + explicit LightningException(std::string err_msg) noexcept + : err_msg{std::move(err_msg)} {} /** * @brief Destroys the `%LightningException` object. From 592e963dbd7c895aae1c192bb6a748b64b3600da Mon Sep 17 00:00:00 2001 From: "Lee J. O'Riordan" Date: Tue, 12 Oct 2021 16:30:08 +0100 Subject: [PATCH 26/45] Avoid errors across diff compiler versions --- pennylane_lightning/src/util/Util.hpp | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/pennylane_lightning/src/util/Util.hpp b/pennylane_lightning/src/util/Util.hpp index 56bdcb3afb..b93623b85d 100644 --- a/pennylane_lightning/src/util/Util.hpp +++ b/pennylane_lightning/src/util/Util.hpp @@ -131,12 +131,10 @@ template inline static constexpr auto IMAG() -> std::complex { * @return constexpr T sqrt(2) */ template inline static constexpr auto SQRT2() -> T { - constexpr auto f = 0x1.6a09e6p+0F; - constexpr auto d = 0x1.6a09e667f3bcdp+0; if constexpr (std::is_same_v) { - return f; + return 0x1.6a09e6p+0F; // NOLINT: To be replaced in C++20 } else { - return d; + return 0x1.6a09e667f3bcdp+0; // NOLINT: To be replaced in C++20 } } From eabc84af75e6e00bbf232a0265216a6fd697e10f Mon Sep 17 00:00:00 2001 From: "Lee J. O'Riordan" Date: Tue, 12 Oct 2021 16:57:01 +0100 Subject: [PATCH 27/45] Fix warning in adjdif --- pennylane_lightning/src/algorithms/AdjointDiff.hpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pennylane_lightning/src/algorithms/AdjointDiff.hpp b/pennylane_lightning/src/algorithms/AdjointDiff.hpp index cce0e9ff08..bbe961f94f 100644 --- a/pennylane_lightning/src/algorithms/AdjointDiff.hpp +++ b/pennylane_lightning/src/algorithms/AdjointDiff.hpp @@ -266,7 +266,7 @@ template class OpsData { std::move(ops_matrices)} { num_par_ops_ = 0; for (const auto &p : ops_params) { - if (p.size() > 0) { + if (p.empty()) { num_par_ops_++; } } From 962083aea013bd7583d9bb262080d067259f7d27 Mon Sep 17 00:00:00 2001 From: "Lee J. O'Riordan" Date: Tue, 12 Oct 2021 16:57:33 +0100 Subject: [PATCH 28/45] Avoid OMP compile failure in manylinux2010 gcc --- .github/workflows/wheel_linux_x86_64.yml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.github/workflows/wheel_linux_x86_64.yml b/.github/workflows/wheel_linux_x86_64.yml index 91c34bf441..8925ce5096 100644 --- a/.github/workflows/wheel_linux_x86_64.yml +++ b/.github/workflows/wheel_linux_x86_64.yml @@ -18,6 +18,8 @@ env: CIBW_TEST_COMMAND: | pl-device-test --device=lightning.qubit --skip-ops -x --tb=short --no-flaky-report + CIBW_MANYLINUX_X86_64_IMAGE: manylinux2014 + jobs: linux-wheels-x86-64: strategy: From dd9cce9ac9a127340cedfe21b21858f3743763a3 Mon Sep 17 00:00:00 2001 From: "Lee J. O'Riordan" Date: Tue, 12 Oct 2021 17:21:00 +0100 Subject: [PATCH 29/45] Remove empty lines --- .github/workflows/tests.yml | 1 - 1 file changed, 1 deletion(-) diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 23f6d87ee5..94a650ddc7 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -55,7 +55,6 @@ jobs: os: [ubuntu-20.04] steps: - - name: Checkout PennyLane-Lightning uses: actions/checkout@v2 with: From 2a515865dcbd9f0e11f1026d1465ecfce8848c1d Mon Sep 17 00:00:00 2001 From: "Lee J. O'Riordan" Date: Wed, 13 Oct 2021 09:17:21 +0100 Subject: [PATCH 30/45] Add test-only clang-tidy options --- pennylane_lightning/src/tests/.clang-tidy | 233 ++++++++++++++++++++++ 1 file changed, 233 insertions(+) create mode 100644 pennylane_lightning/src/tests/.clang-tidy diff --git a/pennylane_lightning/src/tests/.clang-tidy b/pennylane_lightning/src/tests/.clang-tidy new file mode 100644 index 0000000000..3ed93f21bf --- /dev/null +++ b/pennylane_lightning/src/tests/.clang-tidy @@ -0,0 +1,233 @@ +--- +Checks: 'clang-diagnostic-*,clang-analyzer-*,-*,-llvmlibc-*,modernize-*,-modernize-use-trailing-return-type,clang-analyzer-cplusplus*,openmp-*,performance-*,portability-*,readability-*,-readability-magic-numbers,-modernize-avoid-c-arrays' +WarningsAsErrors: '*' +HeaderFilterRegex: '.*' +AnalyzeTemporaryDtors: false +FormatStyle: none +InheritParentConfig: true +User: mlxd +CheckOptions: + - key: modernize-replace-auto-ptr.IncludeStyle + value: llvm + - key: performance-move-const-arg.CheckTriviallyCopyableMove + value: 'true' + - key: modernize-use-auto.MinTypeNameLength + value: '5' + - key: readability-static-accessed-through-instance.NameSpecifierNestingThreshold + value: '3' + - key: readability-function-size.VariableThreshold + value: '4294967295' + - key: cert-dcl16-c.NewSuffixes + value: 'L;LL;LU;LLU' + - key: readability-identifier-naming.GetConfigPerFile + value: 'true' + - key: readability-inconsistent-declaration-parameter-name.Strict + value: 'false' + - key: readability-magic-numbers.IgnoredIntegerValues + value: '1;2;3;4;' + - key: modernize-use-default-member-init.UseAssignment + value: 'false' + - key: readability-function-size.NestingThreshold + value: '4294967295' + - key: modernize-use-override.AllowOverrideAndFinal + value: 'false' + - key: readability-function-size.ParameterThreshold + value: '4294967295' + - key: openmp-exception-escape.IgnoredExceptions + value: '' + - key: modernize-pass-by-value.ValuesOnly + value: 'false' + - key: modernize-loop-convert.IncludeStyle + value: llvm + - key: cert-str34-c.DiagnoseSignedUnsignedCharComparisons + value: '0' + - key: readability-identifier-naming.AggressiveDependentMemberLookup + value: 'false' + - key: readability-redundant-smartptr-get.IgnoreMacros + value: 'true' + - key: modernize-use-emplace.TupleTypes + value: '::std::pair;::std::tuple' + - key: modernize-use-emplace.TupleMakeFunctions + value: '::std::make_pair;::std::make_tuple' + - key: modernize-use-nodiscard.ReplacementString + value: '[[nodiscard]]' + - key: modernize-loop-convert.MakeReverseRangeHeader + value: '' + - key: modernize-replace-random-shuffle.IncludeStyle + value: llvm + - key: modernize-use-bool-literals.IgnoreMacros + value: 'true' + - key: google-readability-namespace-comments.ShortNamespaceLines + value: '10' + - key: modernize-avoid-bind.PermissiveParameterList + value: 'false' + - key: modernize-use-override.FinalSpelling + value: final + - key: performance-move-constructor-init.IncludeStyle + value: llvm + - key: modernize-loop-convert.UseCxx20ReverseRanges + value: 'true' + - key: modernize-use-noexcept.ReplacementString + value: '' + - key: modernize-use-using.IgnoreMacros + value: 'true' + - key: performance-type-promotion-in-math-fn.IncludeStyle + value: llvm + - key: modernize-loop-convert.NamingStyle + value: CamelCase + - key: modernize-loop-convert.MakeReverseRangeFunction + value: '' + - key: readability-inconsistent-declaration-parameter-name.IgnoreMacros + value: 'true' + - key: performance-no-automatic-move.AllowedTypes + value: '' + - key: performance-for-range-copy.WarnOnAllAutoCopies + value: 'false' + - key: readability-identifier-naming.IgnoreFailedSplit + value: 'false' + - key: modernize-pass-by-value.IncludeStyle + value: llvm + - key: readability-qualified-auto.AddConstToQualified + value: 'true' + - key: readability-simplify-boolean-expr.ChainedConditionalReturn + value: 'false' + - key: readability-else-after-return.WarnOnConditionVariables + value: 'true' + - key: readability-uppercase-literal-suffix.IgnoreMacros + value: 'true' + - key: modernize-use-nullptr.NullMacros + value: 'NULL' + - key: modernize-make-shared.IgnoreMacros + value: 'true' + - key: performance-unnecessary-copy-initialization.AllowedTypes + value: '' + - key: modernize-use-transparent-functors.SafeMode + value: 'false' + - key: modernize-make-shared.IgnoreDefaultInitialization + value: 'true' + - key: modernize-make-shared.IncludeStyle + value: llvm + - key: readability-simplify-boolean-expr.ChainedConditionalAssignment + value: 'false' + - key: cert-oop54-cpp.WarnOnlyIfThisHasSuspiciousField + value: '0' + - key: readability-function-size.LineThreshold + value: '4294967295' + - key: performance-inefficient-vector-operation.EnableProto + value: 'false' + - key: modernize-use-override.IgnoreDestructors + value: 'false' + - key: modernize-loop-convert.MaxCopySize + value: '16' + - key: modernize-make-shared.MakeSmartPtrFunction + value: 'std::make_shared' + - key: portability-simd-intrinsics.Suggest + value: 'false' + - key: cppcoreguidelines-explicit-virtual-functions.IgnoreDestructors + value: '1' + - key: modernize-make-unique.IgnoreMacros + value: 'true' + - key: modernize-make-shared.MakeSmartPtrFunctionHeader + value: '' + - key: performance-for-range-copy.AllowedTypes + value: '' + - key: readability-redundant-string-init.StringNames + value: '::std::basic_string_view;::std::basic_string' + - key: modernize-make-unique.IgnoreDefaultInitialization + value: 'true' + - key: modernize-use-emplace.ContainersWithPushBack + value: '::std::vector;::std::list;::std::deque' + - key: readability-magic-numbers.IgnoreBitFieldsWidths + value: 'true' + - key: modernize-make-unique.IncludeStyle + value: llvm + - key: readability-braces-around-statements.ShortStatementLines + value: '0' + - key: modernize-use-override.OverrideSpelling + value: override + - key: readability-magic-numbers.IgnoredFloatingPointValues + value: '1.0;100.0;' + - key: performance-inefficient-string-concatenation.StrictMode + value: 'false' + - key: readability-implicit-bool-conversion.AllowPointerConditions + value: 'false' + - key: readability-redundant-declaration.IgnoreMacros + value: 'true' + - key: google-readability-braces-around-statements.ShortStatementLines + value: '1' + - key: modernize-make-unique.MakeSmartPtrFunction + value: 'std::make_unique' + - key: portability-restrict-system-includes.Includes + value: '*' + - key: readability-else-after-return.WarnOnUnfixable + value: 'true' + - key: modernize-use-emplace.IgnoreImplicitConstructors + value: 'false' + - key: modernize-make-unique.MakeSmartPtrFunctionHeader + value: '' + - key: modernize-use-equals-delete.IgnoreMacros + value: 'true' + - key: readability-magic-numbers.IgnoreAllFloatingPointValues + value: 'false' + - key: readability-uppercase-literal-suffix.NewSuffixes + value: '' + - key: modernize-loop-convert.MinConfidence + value: reasonable + - key: performance-unnecessary-value-param.AllowedTypes + value: '' + - key: modernize-use-noexcept.UseNoexceptFalse + value: 'true' + - key: google-readability-namespace-comments.SpacesBeforeComments + value: '2' + - key: readability-function-cognitive-complexity.Threshold + value: '100' + - key: readability-function-cognitive-complexity.IgnoreMacros + value: 'true' + - key: cppcoreguidelines-non-private-member-variables-in-classes.IgnoreClassesWithAllMemberVariablesBeingPublic + value: '1' + - key: performance-faster-string-find.StringLikeClasses + value: '::std::basic_string;::std::basic_string_view' + - key: readability-function-size.BranchThreshold + value: '4294967295' + - key: readability-implicit-bool-conversion.AllowIntegerConditions + value: 'false' + - key: readability-function-size.StatementThreshold + value: '800' + - key: modernize-use-default-member-init.IgnoreMacros + value: 'true' + - key: llvm-qualified-auto.AddConstToQualified + value: '0' + - key: readability-identifier-naming.IgnoreMainLikeFunctions + value: 'false' + - key: google-readability-function-size.StatementThreshold + value: '800' + - key: llvm-else-after-return.WarnOnConditionVariables + value: '0' + - key: modernize-raw-string-literal.DelimiterStem + value: lit + - key: modernize-use-equals-default.IgnoreMacros + value: 'true' + - key: modernize-raw-string-literal.ReplaceShorterLiterals + value: 'false' + - key: modernize-use-emplace.SmartPointers + value: '::std::shared_ptr;::std::unique_ptr;::std::auto_ptr;::std::weak_ptr' + - key: performance-inefficient-vector-operation.VectorLikeClasses + value: '::std::vector' + - key: modernize-use-auto.RemoveStars + value: 'false' + - key: readability-magic-numbers.IgnorePowersOf2IntegerValues + value: 'false' + - key: portability-simd-intrinsics.Std + value: '' + - key: readability-redundant-member-init.IgnoreBaseInCopyConstructors + value: 'false' + - key: performance-unnecessary-value-param.IncludeStyle + value: llvm + - key: modernize-replace-disallow-copy-and-assign-macro.MacroName + value: DISALLOW_COPY_AND_ASSIGN + - key: llvm-else-after-return.WarnOnUnfixable + value: '0' + - key: readability-simplify-subscript-expr.Types + value: '::std::basic_string;::std::basic_string_view;::std::vector;::std::array' +... + From 5024ac5918edee0d386e2fabaf2ffab190424138 Mon Sep 17 00:00:00 2001 From: "Lee J. O'Riordan" Date: Wed, 13 Oct 2021 12:03:46 +0100 Subject: [PATCH 31/45] Fix logic error in adjdiff --- pennylane_lightning/src/algorithms/AdjointDiff.hpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pennylane_lightning/src/algorithms/AdjointDiff.hpp b/pennylane_lightning/src/algorithms/AdjointDiff.hpp index bbe961f94f..048cc651ab 100644 --- a/pennylane_lightning/src/algorithms/AdjointDiff.hpp +++ b/pennylane_lightning/src/algorithms/AdjointDiff.hpp @@ -266,7 +266,7 @@ template class OpsData { std::move(ops_matrices)} { num_par_ops_ = 0; for (const auto &p : ops_params) { - if (p.empty()) { + if (!p.empty()) { num_par_ops_++; } } From 8b90cb468036d15aa0c118b9a10659e382d9a899 Mon Sep 17 00:00:00 2001 From: "Lee J. O'Riordan" Date: Wed, 13 Oct 2021 12:07:06 +0100 Subject: [PATCH 32/45] Add Python setup to format checks --- .github/workflows/format.yml | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/.github/workflows/format.yml b/.github/workflows/format.yml index 1fedc94724..8a32d5aae9 100644 --- a/.github/workflows/format.yml +++ b/.github/workflows/format.yml @@ -39,6 +39,11 @@ jobs: with: access_token: ${{ github.token }} + - name: Set up Python + uses: actions/setup-python@v2 + with: + python-version: 3.8 + - name: Install dependencies run: sudo apt update && sudo apt -y install clang-tidy-11 python3 cmake g++ env: From 6a015b5bea3578012248f3af7f2dc5d35b9aa703 Mon Sep 17 00:00:00 2001 From: "Lee J. O'Riordan" Date: Wed, 13 Oct 2021 12:10:05 +0100 Subject: [PATCH 33/45] Ensure Python env setup prior to test build CI --- .github/workflows/tests.yml | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 94a650ddc7..5e49cb9982 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -21,6 +21,11 @@ jobs: with: access_token: ${{ github.token }} + - uses: actions/setup-python@v2 + name: Install Python + with: + python-version: '3.7' + - uses: actions/checkout@v2 - name: Install dependencies From 8f31cce4dd68ec50f324ef5d7ac4d9a29a19d3f7 Mon Sep 17 00:00:00 2001 From: "Lee J. O'Riordan" Date: Wed, 13 Oct 2021 14:44:25 +0100 Subject: [PATCH 34/45] Refactor adjoint diff to reduce complexity --- .../src/algorithms/AdjointDiff.hpp | 161 +++++++++++------- 1 file changed, 97 insertions(+), 64 deletions(-) diff --git a/pennylane_lightning/src/algorithms/AdjointDiff.hpp b/pennylane_lightning/src/algorithms/AdjointDiff.hpp index 048cc651ab..479e906aa4 100644 --- a/pennylane_lightning/src/algorithms/AdjointDiff.hpp +++ b/pennylane_lightning/src/algorithms/AdjointDiff.hpp @@ -513,6 +513,100 @@ template class AdjointJacobian { } } + /** + * @brief OpenMP accelerated application of observables to given + * statevectors + * + * @param states Vector of statevector copies, one per observable. + * @param reference_state Reference statevector + * @param observables Vector of observables to apply to each statevector. + */ + inline void applyObservables(std::vector> &states, + const StateVectorManaged &reference_state, + const std::vector> &observables) { + // Globally scoped exception value to be captured within OpenMP block. + // See the following for OpenMP design decisions: + // https://www.openmp.org/wp-content/uploads/openmp-examples-4.5.0.pdf + std::exception_ptr ex = nullptr; + size_t num_observables = observables.size(); +#if defined _OPENMP +#pragma omp parallel default(none) \ + shared(states, reference_state, observables, ex, num_observables) + { +#pragma omp for +#endif + for (size_t h_i = 0; h_i < num_observables; h_i++) { + try { + states[h_i].updateData(reference_state.getDataVector()); + applyObservable(states[h_i], observables[h_i]); + } catch (...) { +#if defined _OPENMP +#pragma omp critical +#endif + ex = std::current_exception(); +#if defined _OPENMP +#pragma omp cancel for +#endif + } + } +#if defined _OPENMP + if (ex) { +#pragma omp cancel parallel + } + } +#endif + if (ex) { + std::rethrow_exception(ex); + } + } + + /** + * @brief OpenMP accelerated application of adjoint operations to + * statevectors. + * + * @param states Vector of all statevectors; 1 per observable + * @param operations Operations list. + * @param op_idx Index of given operation within operations list to take + * adjoint of. + */ + inline void applyOperationsAdj(std::vector> &states, + const OpsData &operations, + size_t op_idx) { + // Globally scoped exception value to be captured within OpenMP block. + // See the following for OpenMP design decisions: + // https://www.openmp.org/wp-content/uploads/openmp-examples-4.5.0.pdf + std::exception_ptr ex = nullptr; + size_t num_states = states.size(); +#if defined _OPENMP +#pragma omp parallel default(none) \ + shared(states, operations, op_idx, ex, num_states) + { +#pragma omp for +#endif + for (size_t obs_idx = 0; obs_idx < num_states; obs_idx++) { + try { + applyOperationAdj(states[obs_idx], operations, op_idx); + } catch (...) { +#if defined _OPENMP +#pragma omp critical +#endif + ex = std::current_exception(); +#if defined _OPENMP +#pragma omp cancel for +#endif + } + } +#if defined _OPENMP + if (ex) { +#pragma omp cancel parallel + } + } +#endif + if (ex) { + std::rethrow_exception(ex); + } + } + /** * @brief Inline utility to assist with getting the Jacobian index offset. * @@ -632,40 +726,7 @@ template class AdjointJacobian { // Create observable-applied state-vectors std::vector> H_lambda(num_observables, {lambda.getNumQubits()}); - - // See - // https://www.openmp.org/wp-content/uploads/openmp-examples-4.5.0.pdf - std::exception_ptr ex = nullptr; - -#if defined _OPENMP -#pragma omp parallel default(none) \ - shared(H_lambda, lambda, observables, num_observables, ex) - { -#pragma omp for -#endif - for (size_t h_i = 0; h_i < num_observables; h_i++) { - try { - H_lambda[h_i].updateData(lambda.getDataVector()); - applyObservable(H_lambda[h_i], observables[h_i]); - } catch (...) { -#if defined _OPENMP -#pragma omp critical -#endif - ex = std::current_exception(); -#if defined _OPENMP -#pragma omp cancel for -#endif - } - } -#if defined _OPENMP - if (ex) { -#pragma omp cancel parallel - } - } -#endif - if (ex) { - std::rethrow_exception(ex); - } + applyObservables(H_lambda, lambda, observables); StateVectorManaged mu(lambda.getNumQubits()); @@ -705,36 +766,8 @@ template class AdjointJacobian { } current_param_idx--; } -#if defined _OPENMP -#pragma omp parallel default(none) \ - shared(H_lambda, operations, op_idx, num_observables, ex) - { -#pragma omp for -#endif - for (size_t obs_idx = 0; obs_idx < num_observables; - obs_idx++) { - try { - applyOperationAdj(H_lambda[obs_idx], operations, - op_idx); - } catch (...) { -#if defined _OPENMP -#pragma omp critical -#endif - ex = std::current_exception(); -#if defined _OPENMP -#pragma omp cancel for -#endif - } - } -#if defined _OPENMP - if (ex) { -#pragma omp cancel parallel - } - } -#endif - if (ex) { - std::rethrow_exception(ex); - } + applyOperationsAdj(H_lambda, operations, + static_cast(op_idx)); } } } From 60fea62b9676c046c1e26b40035302dc6f852cb6 Mon Sep 17 00:00:00 2001 From: "Lee J. O'Riordan" Date: Wed, 13 Oct 2021 17:23:09 +0100 Subject: [PATCH 35/45] Update changelog --- .github/CHANGELOG.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.github/CHANGELOG.md b/.github/CHANGELOG.md index bc5b5198ec..93bfe9f1f9 100644 --- a/.github/CHANGELOG.md +++ b/.github/CHANGELOG.md @@ -4,6 +4,9 @@ ### Improvements +* PennyLane-Lightning has been updated to conform with clang-tidy recommendations for modernization, offering performance improvements across all use-cases. +[(#153)](https://github.com/PennyLaneAI/pennylane-lightning/pull/153) + ### Documentation ### Breaking changes From 052ef9caa3b9ccc179b4ae7656a2f33b63a01a6f Mon Sep 17 00:00:00 2001 From: Ali Asadi Date: Wed, 13 Oct 2021 16:31:56 -0400 Subject: [PATCH 36/45] Update .clang-tidy --- pennylane_lightning/src/.clang-tidy | 246 ++++++++++++++-------------- 1 file changed, 123 insertions(+), 123 deletions(-) diff --git a/pennylane_lightning/src/.clang-tidy b/pennylane_lightning/src/.clang-tidy index 17f1e2ec5c..aa5150733b 100644 --- a/pennylane_lightning/src/.clang-tidy +++ b/pennylane_lightning/src/.clang-tidy @@ -9,42 +9,16 @@ User: mlxd CheckOptions: - key: modernize-replace-auto-ptr.IncludeStyle value: llvm - - key: performance-move-const-arg.CheckTriviallyCopyableMove - value: 'true' - key: modernize-use-auto.MinTypeNameLength value: '5' - - key: readability-static-accessed-through-instance.NameSpecifierNestingThreshold - value: '3' - - key: readability-function-size.VariableThreshold - value: '4294967295' - - key: cert-dcl16-c.NewSuffixes - value: 'L;LL;LU;LLU' - - key: readability-identifier-naming.GetConfigPerFile - value: 'true' - - key: readability-inconsistent-declaration-parameter-name.Strict - value: 'false' - - key: readability-magic-numbers.IgnoredIntegerValues - value: '1;2;3;4;' - key: modernize-use-default-member-init.UseAssignment value: 'false' - - key: readability-function-size.NestingThreshold - value: '4294967295' - key: modernize-use-override.AllowOverrideAndFinal value: 'false' - - key: readability-function-size.ParameterThreshold - value: '4294967295' - - key: openmp-exception-escape.IgnoredExceptions - value: '' - key: modernize-pass-by-value.ValuesOnly value: 'false' - key: modernize-loop-convert.IncludeStyle value: llvm - - key: cert-str34-c.DiagnoseSignedUnsignedCharComparisons - value: '0' - - key: readability-identifier-naming.AggressiveDependentMemberLookup - value: 'false' - - key: readability-redundant-smartptr-get.IgnoreMacros - value: 'true' - key: modernize-use-emplace.TupleTypes value: '::std::pair;::std::tuple' - key: modernize-use-emplace.TupleMakeFunctions @@ -57,177 +31,203 @@ CheckOptions: value: llvm - key: modernize-use-bool-literals.IgnoreMacros value: 'true' - - key: google-readability-namespace-comments.ShortNamespaceLines - value: '10' - key: modernize-avoid-bind.PermissiveParameterList value: 'false' - key: modernize-use-override.FinalSpelling value: final - - key: performance-move-constructor-init.IncludeStyle - value: llvm - key: modernize-loop-convert.UseCxx20ReverseRanges value: 'true' - key: modernize-use-noexcept.ReplacementString value: '' - key: modernize-use-using.IgnoreMacros value: 'true' - - key: performance-type-promotion-in-math-fn.IncludeStyle - value: llvm - key: modernize-loop-convert.NamingStyle value: CamelCase - key: modernize-loop-convert.MakeReverseRangeFunction value: '' - - key: readability-inconsistent-declaration-parameter-name.IgnoreMacros - value: 'true' - - key: performance-no-automatic-move.AllowedTypes - value: '' - - key: performance-for-range-copy.WarnOnAllAutoCopies - value: 'false' - - key: readability-identifier-naming.IgnoreFailedSplit - value: 'false' - - key: modernize-pass-by-value.IncludeStyle - value: llvm - - key: readability-qualified-auto.AddConstToQualified - value: 'true' - - key: readability-simplify-boolean-expr.ChainedConditionalReturn - value: 'false' - - key: readability-else-after-return.WarnOnConditionVariables - value: 'true' - - key: readability-uppercase-literal-suffix.IgnoreMacros - value: 'true' - key: modernize-use-nullptr.NullMacros value: 'NULL' - key: modernize-make-shared.IgnoreMacros value: 'true' - - key: performance-unnecessary-copy-initialization.AllowedTypes - value: '' - key: modernize-use-transparent-functors.SafeMode value: 'false' - key: modernize-make-shared.IgnoreDefaultInitialization value: 'true' - key: modernize-make-shared.IncludeStyle value: llvm - - key: readability-simplify-boolean-expr.ChainedConditionalAssignment - value: 'false' - - key: cert-oop54-cpp.WarnOnlyIfThisHasSuspiciousField - value: '0' - - key: readability-function-size.LineThreshold - value: '4294967295' - - key: performance-inefficient-vector-operation.EnableProto - value: 'false' + - key: modernize-pass-by-value.IncludeStyle + value: llvm - key: modernize-use-override.IgnoreDestructors value: 'false' - key: modernize-loop-convert.MaxCopySize value: '16' - key: modernize-make-shared.MakeSmartPtrFunction value: 'std::make_shared' - - key: portability-simd-intrinsics.Suggest - value: 'false' - - key: cppcoreguidelines-explicit-virtual-functions.IgnoreDestructors - value: '1' - key: modernize-make-unique.IgnoreMacros value: 'true' - key: modernize-make-shared.MakeSmartPtrFunctionHeader value: '' - - key: performance-for-range-copy.AllowedTypes - value: '' - - key: readability-redundant-string-init.StringNames - value: '::std::basic_string_view;::std::basic_string' - key: modernize-make-unique.IgnoreDefaultInitialization value: 'true' - key: modernize-use-emplace.ContainersWithPushBack value: '::std::vector;::std::list;::std::deque' - - key: readability-magic-numbers.IgnoreBitFieldsWidths - value: 'true' - key: modernize-make-unique.IncludeStyle value: llvm - - key: readability-braces-around-statements.ShortStatementLines - value: '0' - key: modernize-use-override.OverrideSpelling value: override - - key: readability-magic-numbers.IgnoredFloatingPointValues - value: '1.0;100.0;' - - key: performance-inefficient-string-concatenation.StrictMode - value: 'false' - - key: readability-implicit-bool-conversion.AllowPointerConditions - value: 'false' - - key: readability-redundant-declaration.IgnoreMacros - value: 'true' - - key: google-readability-braces-around-statements.ShortStatementLines - value: '1' - key: modernize-make-unique.MakeSmartPtrFunction value: 'std::make_unique' - - key: portability-restrict-system-includes.Includes - value: '*' - - key: readability-else-after-return.WarnOnUnfixable - value: 'true' - key: modernize-use-emplace.IgnoreImplicitConstructors value: 'false' - key: modernize-make-unique.MakeSmartPtrFunctionHeader value: '' - key: modernize-use-equals-delete.IgnoreMacros value: 'true' - - key: readability-magic-numbers.IgnoreAllFloatingPointValues - value: 'false' - - key: readability-uppercase-literal-suffix.NewSuffixes - value: '' - key: modernize-loop-convert.MinConfidence value: reasonable - - key: performance-unnecessary-value-param.AllowedTypes - value: '' + - key: modernize-raw-string-literal.DelimiterStem + value: lit + - key: modernize-use-equals-default.IgnoreMacros + value: 'true' + - key: modernize-raw-string-literal.ReplaceShorterLiterals + value: 'false' + - key: modernize-use-emplace.SmartPointers + value: '::std::shared_ptr;::std::unique_ptr;::std::auto_ptr;::std::weak_ptr' - key: modernize-use-noexcept.UseNoexceptFalse value: 'true' - - key: google-readability-namespace-comments.SpacesBeforeComments - value: '2' + - key: modernize-use-default-member-init.IgnoreMacros + value: 'true' + - key: modernize-use-auto.RemoveStars + value: 'false' + - key: modernize-replace-disallow-copy-and-assign-macro.MacroName + value: DISALLOW_COPY_AND_ASSIGN + - key: readability-static-accessed-through-instance.NameSpecifierNestingThreshold + value: '3' + - key: readability-function-size.VariableThreshold + value: '4294967295' + - key: readability-identifier-naming.GetConfigPerFile + value: 'true' + - key: readability-inconsistent-declaration-parameter-name.Strict + value: 'false' + - key: readability-magic-numbers.IgnoredIntegerValues + value: '1;2;3;4;' + - key: readability-function-size.NestingThreshold + value: '4294967295' + - key: readability-function-size.ParameterThreshold + value: '4294967295' + - key: readability-identifier-naming.AggressiveDependentMemberLookup + value: 'false' + - key: readability-redundant-smartptr-get.IgnoreMacros + value: 'true' + - key: readability-inconsistent-declaration-parameter-name.IgnoreMacros + value: 'true' + - key: readability-identifier-naming.IgnoreFailedSplit + value: 'false' + - key: readability-qualified-auto.AddConstToQualified + value: 'true' + - key: readability-simplify-boolean-expr.ChainedConditionalReturn + value: 'false' + - key: readability-else-after-return.WarnOnConditionVariables + value: 'true' + - key: readability-uppercase-literal-suffix.IgnoreMacros + value: 'true' + - key: readability-simplify-boolean-expr.ChainedConditionalAssignment + value: 'false' + - key: readability-function-size.LineThreshold + value: '4294967295' + - key: readability-redundant-string-init.StringNames + value: '::std::basic_string_view;::std::basic_string' + - key: readability-magic-numbers.IgnoreBitFieldsWidths + value: 'true' + - key: readability-braces-around-statements.ShortStatementLines + value: '0' + - key: readability-magic-numbers.IgnoredFloatingPointValues + value: '1.0;100.0;' + - key: readability-implicit-bool-conversion.AllowPointerConditions + value: 'false' + - key: readability-redundant-declaration.IgnoreMacros + value: 'true' + - key: readability-else-after-return.WarnOnUnfixable + value: 'true' + - key: readability-magic-numbers.IgnoreAllFloatingPointValues + value: 'false' + - key: readability-uppercase-literal-suffix.NewSuffixes + value: '' - key: readability-function-cognitive-complexity.Threshold value: '45' - key: readability-function-cognitive-complexity.IgnoreMacros value: 'true' - - key: cppcoreguidelines-non-private-member-variables-in-classes.IgnoreClassesWithAllMemberVariablesBeingPublic - value: '1' - - key: performance-faster-string-find.StringLikeClasses - value: '::std::basic_string;::std::basic_string_view' - key: readability-function-size.BranchThreshold value: '4294967295' - key: readability-implicit-bool-conversion.AllowIntegerConditions value: 'false' - key: readability-function-size.StatementThreshold value: '800' - - key: modernize-use-default-member-init.IgnoreMacros - value: 'true' - - key: llvm-qualified-auto.AddConstToQualified - value: '0' + - key: readability-redundant-member-init.IgnoreBaseInCopyConstructors + value: 'false' + - key: readability-simplify-subscript-expr.Types + value: '::std::basic_string;::std::basic_string_view;::std::vector;::std::array' - key: readability-identifier-naming.IgnoreMainLikeFunctions value: 'false' - - key: google-readability-function-size.StatementThreshold - value: '800' - - key: llvm-else-after-return.WarnOnConditionVariables - value: '0' - - key: modernize-raw-string-literal.DelimiterStem - value: lit - - key: modernize-use-equals-default.IgnoreMacros - value: 'true' - - key: modernize-raw-string-literal.ReplaceShorterLiterals + - key: readability-magic-numbers.IgnorePowersOf2IntegerValues value: 'false' - - key: modernize-use-emplace.SmartPointers - value: '::std::shared_ptr;::std::unique_ptr;::std::auto_ptr;::std::weak_ptr' - - key: performance-inefficient-vector-operation.VectorLikeClasses - value: '::std::vector' - - key: modernize-use-auto.RemoveStars + - key: performance-move-const-arg.CheckTriviallyCopyableMove + value: 'true' + - key: performance-move-constructor-init.IncludeStyle + value: llvm + - key: performance-type-promotion-in-math-fn.IncludeStyle + value: llvm + - key: performance-no-automatic-move.AllowedTypes + value: '' + - key: performance-for-range-copy.WarnOnAllAutoCopies value: 'false' - - key: readability-magic-numbers.IgnorePowersOf2IntegerValues + - key: performance-unnecessary-copy-initialization.AllowedTypes + value: '' + - key: performance-inefficient-vector-operation.EnableProto value: 'false' - - key: portability-simd-intrinsics.Std + - key: performance-for-range-copy.AllowedTypes value: '' - - key: readability-redundant-member-init.IgnoreBaseInCopyConstructors + - key: performance-inefficient-string-concatenation.StrictMode value: 'false' + - key: performance-unnecessary-value-param.AllowedTypes + value: '' + - key: performance-faster-string-find.StringLikeClasses + value: '::std::basic_string;::std::basic_string_view' + - key: performance-inefficient-vector-operation.VectorLikeClasses + value: '::std::vector' - key: performance-unnecessary-value-param.IncludeStyle value: llvm - - key: modernize-replace-disallow-copy-and-assign-macro.MacroName - value: DISALLOW_COPY_AND_ASSIGN + - key: cert-dcl16-c.NewSuffixes + value: 'L;LL;LU;LLU' + - key: cert-str34-c.DiagnoseSignedUnsignedCharComparisons + value: '0' + - key: cert-oop54-cpp.WarnOnlyIfThisHasSuspiciousField + value: '0' + - key: portability-simd-intrinsics.Suggest + value: 'false' + - key: portability-simd-intrinsics.Std + value: '' + - key: portability-restrict-system-includes.Includes + value: '*' + - key: cppcoreguidelines-explicit-virtual-functions.IgnoreDestructors + value: '1' + - key: cppcoreguidelines-non-private-member-variables-in-classes.IgnoreClassesWithAllMemberVariablesBeingPublic + value: '1' + - key: google-readability-braces-around-statements.ShortStatementLines + value: '1' + - key: google-readability-namespace-comments.SpacesBeforeComments + value: '2' + - key: google-readability-function-size.StatementThreshold + value: '800' + - key: google-readability-namespace-comments.ShortNamespaceLines + value: '10' + - key: llvm-else-after-return.WarnOnConditionVariables + value: '0' + - key: llvm-qualified-auto.AddConstToQualified + value: '0' - key: llvm-else-after-return.WarnOnUnfixable value: '0' - - key: readability-simplify-subscript-expr.Types - value: '::std::basic_string;::std::basic_string_view;::std::vector;::std::array' + - key: openmp-exception-escape.IgnoredExceptions + value: '' ... From 107d9d4a81a3f72d93b0577b61d111e0714a4cdb Mon Sep 17 00:00:00 2001 From: Ali Asadi Date: Wed, 13 Oct 2021 21:53:18 -0400 Subject: [PATCH 37/45] Update Bindings.cpp --- pennylane_lightning/src/bindings/Bindings.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/pennylane_lightning/src/bindings/Bindings.cpp b/pennylane_lightning/src/bindings/Bindings.cpp index 1400770fad..58026e0ae2 100644 --- a/pennylane_lightning/src/bindings/Bindings.cpp +++ b/pennylane_lightning/src/bindings/Bindings.cpp @@ -661,7 +661,7 @@ void lightning_class_bindings(py::module &m) { auto buffer = param.request(); auto ptr = static_cast *>( buffer.ptr); - if (buffer.size > 0) { + if (buffer.size) { conv_params[p_idx] = std::vector>{ ptr, ptr + buffer.size}; @@ -670,7 +670,7 @@ void lightning_class_bindings(py::module &m) { auto buffer = param.request(); auto *ptr = static_cast(buffer.ptr); - if (buffer.size > 0) { + if (buffer.size) { conv_params[p_idx] = std::vector{ ptr, ptr + buffer.size}; } @@ -774,13 +774,13 @@ void lightning_class_bindings(py::module &m) { for (size_t op = 0; op < ops_name.size(); op++) { const auto p_buffer = ops_params[op].request(); const auto m_buffer = ops_matrices[op].request(); - if (p_buffer.size > 0) { + if (p_buffer.size) { const auto *const p_ptr = static_cast(p_buffer.ptr); conv_params[op] = std::vector{p_ptr, p_ptr + p_buffer.size}; } - if (m_buffer.size > 0) { + if (m_buffer.size) { const auto m_ptr = static_cast *>( m_buffer.ptr); From f160319d8d01f7a2aeb3a9aa08586f8df4e02a8b Mon Sep 17 00:00:00 2001 From: "Lee J. O'Riordan" Date: Thu, 14 Oct 2021 12:12:47 +0100 Subject: [PATCH 38/45] Trigger CI From d758ded320f8bc059cd640978e1da53216b25eb9 Mon Sep 17 00:00:00 2001 From: Ali Asadi Date: Thu, 14 Oct 2021 09:14:36 -0400 Subject: [PATCH 39/45] Revert my changes --- pennylane_lightning/src/.clang-tidy | 247 ++++++++++++++-------------- 1 file changed, 123 insertions(+), 124 deletions(-) diff --git a/pennylane_lightning/src/.clang-tidy b/pennylane_lightning/src/.clang-tidy index aa5150733b..2dba5842f0 100644 --- a/pennylane_lightning/src/.clang-tidy +++ b/pennylane_lightning/src/.clang-tidy @@ -9,16 +9,42 @@ User: mlxd CheckOptions: - key: modernize-replace-auto-ptr.IncludeStyle value: llvm + - key: performance-move-const-arg.CheckTriviallyCopyableMove + value: 'true' - key: modernize-use-auto.MinTypeNameLength value: '5' + - key: readability-static-accessed-through-instance.NameSpecifierNestingThreshold + value: '3' + - key: readability-function-size.VariableThreshold + value: '4294967295' + - key: cert-dcl16-c.NewSuffixes + value: 'L;LL;LU;LLU' + - key: readability-identifier-naming.GetConfigPerFile + value: 'true' + - key: readability-inconsistent-declaration-parameter-name.Strict + value: 'false' + - key: readability-magic-numbers.IgnoredIntegerValues + value: '1;2;3;4;' - key: modernize-use-default-member-init.UseAssignment value: 'false' + - key: readability-function-size.NestingThreshold + value: '4294967295' - key: modernize-use-override.AllowOverrideAndFinal value: 'false' + - key: readability-function-size.ParameterThreshold + value: '4294967295' + - key: openmp-exception-escape.IgnoredExceptions + value: '' - key: modernize-pass-by-value.ValuesOnly value: 'false' - key: modernize-loop-convert.IncludeStyle value: llvm + - key: cert-str34-c.DiagnoseSignedUnsignedCharComparisons + value: '0' + - key: readability-identifier-naming.AggressiveDependentMemberLookup + value: 'false' + - key: readability-redundant-smartptr-get.IgnoreMacros + value: 'true' - key: modernize-use-emplace.TupleTypes value: '::std::pair;::std::tuple' - key: modernize-use-emplace.TupleMakeFunctions @@ -31,203 +57,176 @@ CheckOptions: value: llvm - key: modernize-use-bool-literals.IgnoreMacros value: 'true' + - key: google-readability-namespace-comments.ShortNamespaceLines + value: '10' - key: modernize-avoid-bind.PermissiveParameterList value: 'false' - key: modernize-use-override.FinalSpelling value: final + - key: performance-move-constructor-init.IncludeStyle + value: llvm - key: modernize-loop-convert.UseCxx20ReverseRanges value: 'true' - key: modernize-use-noexcept.ReplacementString value: '' - key: modernize-use-using.IgnoreMacros value: 'true' + - key: performance-type-promotion-in-math-fn.IncludeStyle + value: llvm - key: modernize-loop-convert.NamingStyle value: CamelCase - key: modernize-loop-convert.MakeReverseRangeFunction value: '' + - key: readability-inconsistent-declaration-parameter-name.IgnoreMacros + value: 'true' + - key: performance-no-automatic-move.AllowedTypes + value: '' + - key: performance-for-range-copy.WarnOnAllAutoCopies + value: 'false' + - key: readability-identifier-naming.IgnoreFailedSplit + value: 'false' + - key: modernize-pass-by-value.IncludeStyle + value: llvm + - key: readability-qualified-auto.AddConstToQualified + value: 'true' + - key: readability-simplify-boolean-expr.ChainedConditionalReturn + value: 'false' + - key: readability-else-after-return.WarnOnConditionVariables + value: 'true' + - key: readability-uppercase-literal-suffix.IgnoreMacros + value: 'true' - key: modernize-use-nullptr.NullMacros value: 'NULL' - key: modernize-make-shared.IgnoreMacros value: 'true' + - key: performance-unnecessary-copy-initialization.AllowedTypes + value: '' - key: modernize-use-transparent-functors.SafeMode value: 'false' - key: modernize-make-shared.IgnoreDefaultInitialization value: 'true' - key: modernize-make-shared.IncludeStyle value: llvm - - key: modernize-pass-by-value.IncludeStyle - value: llvm + - key: readability-simplify-boolean-expr.ChainedConditionalAssignment + value: 'false' + - key: cert-oop54-cpp.WarnOnlyIfThisHasSuspiciousField + value: '0' + - key: readability-function-size.LineThreshold + value: '4294967295' + - key: performance-inefficient-vector-operation.EnableProto + value: 'false' - key: modernize-use-override.IgnoreDestructors value: 'false' - key: modernize-loop-convert.MaxCopySize value: '16' - key: modernize-make-shared.MakeSmartPtrFunction value: 'std::make_shared' + - key: portability-simd-intrinsics.Suggest + value: 'false' + - key: cppcoreguidelines-explicit-virtual-functions.IgnoreDestructors + value: '1' - key: modernize-make-unique.IgnoreMacros value: 'true' - key: modernize-make-shared.MakeSmartPtrFunctionHeader value: '' + - key: performance-for-range-copy.AllowedTypes + value: '' + - key: readability-redundant-string-init.StringNames + value: '::std::basic_string_view;::std::basic_string' - key: modernize-make-unique.IgnoreDefaultInitialization value: 'true' - key: modernize-use-emplace.ContainersWithPushBack value: '::std::vector;::std::list;::std::deque' - - key: modernize-make-unique.IncludeStyle - value: llvm - - key: modernize-use-override.OverrideSpelling - value: override - - key: modernize-make-unique.MakeSmartPtrFunction - value: 'std::make_unique' - - key: modernize-use-emplace.IgnoreImplicitConstructors - value: 'false' - - key: modernize-make-unique.MakeSmartPtrFunctionHeader - value: '' - - key: modernize-use-equals-delete.IgnoreMacros - value: 'true' - - key: modernize-loop-convert.MinConfidence - value: reasonable - - key: modernize-raw-string-literal.DelimiterStem - value: lit - - key: modernize-use-equals-default.IgnoreMacros - value: 'true' - - key: modernize-raw-string-literal.ReplaceShorterLiterals - value: 'false' - - key: modernize-use-emplace.SmartPointers - value: '::std::shared_ptr;::std::unique_ptr;::std::auto_ptr;::std::weak_ptr' - - key: modernize-use-noexcept.UseNoexceptFalse - value: 'true' - - key: modernize-use-default-member-init.IgnoreMacros - value: 'true' - - key: modernize-use-auto.RemoveStars - value: 'false' - - key: modernize-replace-disallow-copy-and-assign-macro.MacroName - value: DISALLOW_COPY_AND_ASSIGN - - key: readability-static-accessed-through-instance.NameSpecifierNestingThreshold - value: '3' - - key: readability-function-size.VariableThreshold - value: '4294967295' - - key: readability-identifier-naming.GetConfigPerFile - value: 'true' - - key: readability-inconsistent-declaration-parameter-name.Strict - value: 'false' - - key: readability-magic-numbers.IgnoredIntegerValues - value: '1;2;3;4;' - - key: readability-function-size.NestingThreshold - value: '4294967295' - - key: readability-function-size.ParameterThreshold - value: '4294967295' - - key: readability-identifier-naming.AggressiveDependentMemberLookup - value: 'false' - - key: readability-redundant-smartptr-get.IgnoreMacros - value: 'true' - - key: readability-inconsistent-declaration-parameter-name.IgnoreMacros - value: 'true' - - key: readability-identifier-naming.IgnoreFailedSplit - value: 'false' - - key: readability-qualified-auto.AddConstToQualified - value: 'true' - - key: readability-simplify-boolean-expr.ChainedConditionalReturn - value: 'false' - - key: readability-else-after-return.WarnOnConditionVariables - value: 'true' - - key: readability-uppercase-literal-suffix.IgnoreMacros - value: 'true' - - key: readability-simplify-boolean-expr.ChainedConditionalAssignment - value: 'false' - - key: readability-function-size.LineThreshold - value: '4294967295' - - key: readability-redundant-string-init.StringNames - value: '::std::basic_string_view;::std::basic_string' - key: readability-magic-numbers.IgnoreBitFieldsWidths value: 'true' + - key: modernize-make-unique.IncludeStyle + value: llvm - key: readability-braces-around-statements.ShortStatementLines value: '0' + - key: modernize-use-override.OverrideSpelling + value: override - key: readability-magic-numbers.IgnoredFloatingPointValues value: '1.0;100.0;' + - key: performance-inefficient-string-concatenation.StrictMode + value: 'false' - key: readability-implicit-bool-conversion.AllowPointerConditions value: 'false' - key: readability-redundant-declaration.IgnoreMacros value: 'true' + - key: google-readability-braces-around-statements.ShortStatementLines + value: '1' + - key: modernize-make-unique.MakeSmartPtrFunction + value: 'std::make_unique' + - key: portability-restrict-system-includes.Includes + value: '*' - key: readability-else-after-return.WarnOnUnfixable value: 'true' + - key: modernize-use-emplace.IgnoreImplicitConstructors + value: 'false' + - key: modernize-make-unique.MakeSmartPtrFunctionHeader + value: '' + - key: modernize-use-equals-delete.IgnoreMacros + value: 'true' - key: readability-magic-numbers.IgnoreAllFloatingPointValues value: 'false' - key: readability-uppercase-literal-suffix.NewSuffixes value: '' + - key: modernize-loop-convert.MinConfidence + value: reasonable + - key: performance-unnecessary-value-param.AllowedTypes + value: '' + - key: modernize-use-noexcept.UseNoexceptFalse + value: 'true' + - key: google-readability-namespace-comments.SpacesBeforeComments + value: '2' - key: readability-function-cognitive-complexity.Threshold value: '45' - key: readability-function-cognitive-complexity.IgnoreMacros value: 'true' + - key: cppcoreguidelines-non-private-member-variables-in-classes.IgnoreClassesWithAllMemberVariablesBeingPublic + value: '1' + - key: performance-faster-string-find.StringLikeClasses + value: '::std::basic_string;::std::basic_string_view' - key: readability-function-size.BranchThreshold value: '4294967295' - key: readability-implicit-bool-conversion.AllowIntegerConditions value: 'false' - key: readability-function-size.StatementThreshold value: '800' - - key: readability-redundant-member-init.IgnoreBaseInCopyConstructors - value: 'false' - - key: readability-simplify-subscript-expr.Types - value: '::std::basic_string;::std::basic_string_view;::std::vector;::std::array' + - key: modernize-use-default-member-init.IgnoreMacros + value: 'true' + - key: llvm-qualified-auto.AddConstToQualified + value: '0' - key: readability-identifier-naming.IgnoreMainLikeFunctions value: 'false' - - key: readability-magic-numbers.IgnorePowersOf2IntegerValues - value: 'false' - - key: performance-move-const-arg.CheckTriviallyCopyableMove + - key: google-readability-function-size.StatementThreshold + value: '800' + - key: llvm-else-after-return.WarnOnConditionVariables + value: '0' + - key: modernize-raw-string-literal.DelimiterStem + value: lit + - key: modernize-use-equals-default.IgnoreMacros value: 'true' - - key: performance-move-constructor-init.IncludeStyle - value: llvm - - key: performance-type-promotion-in-math-fn.IncludeStyle - value: llvm - - key: performance-no-automatic-move.AllowedTypes - value: '' - - key: performance-for-range-copy.WarnOnAllAutoCopies - value: 'false' - - key: performance-unnecessary-copy-initialization.AllowedTypes - value: '' - - key: performance-inefficient-vector-operation.EnableProto - value: 'false' - - key: performance-for-range-copy.AllowedTypes - value: '' - - key: performance-inefficient-string-concatenation.StrictMode + - key: modernize-raw-string-literal.ReplaceShorterLiterals value: 'false' - - key: performance-unnecessary-value-param.AllowedTypes - value: '' - - key: performance-faster-string-find.StringLikeClasses - value: '::std::basic_string;::std::basic_string_view' + - key: modernize-use-emplace.SmartPointers + value: '::std::shared_ptr;::std::unique_ptr;::std::auto_ptr;::std::weak_ptr' - key: performance-inefficient-vector-operation.VectorLikeClasses value: '::std::vector' - - key: performance-unnecessary-value-param.IncludeStyle - value: llvm - - key: cert-dcl16-c.NewSuffixes - value: 'L;LL;LU;LLU' - - key: cert-str34-c.DiagnoseSignedUnsignedCharComparisons - value: '0' - - key: cert-oop54-cpp.WarnOnlyIfThisHasSuspiciousField - value: '0' - - key: portability-simd-intrinsics.Suggest + - key: modernize-use-auto.RemoveStars + value: 'false' + - key: readability-magic-numbers.IgnorePowersOf2IntegerValues value: 'false' - key: portability-simd-intrinsics.Std value: '' - - key: portability-restrict-system-includes.Includes - value: '*' - - key: cppcoreguidelines-explicit-virtual-functions.IgnoreDestructors - value: '1' - - key: cppcoreguidelines-non-private-member-variables-in-classes.IgnoreClassesWithAllMemberVariablesBeingPublic - value: '1' - - key: google-readability-braces-around-statements.ShortStatementLines - value: '1' - - key: google-readability-namespace-comments.SpacesBeforeComments - value: '2' - - key: google-readability-function-size.StatementThreshold - value: '800' - - key: google-readability-namespace-comments.ShortNamespaceLines - value: '10' - - key: llvm-else-after-return.WarnOnConditionVariables - value: '0' - - key: llvm-qualified-auto.AddConstToQualified - value: '0' + - key: readability-redundant-member-init.IgnoreBaseInCopyConstructors + value: 'false' + - key: performance-unnecessary-value-param.IncludeStyle + value: llvm + - key: modernize-replace-disallow-copy-and-assign-macro.MacroName + value: DISALLOW_COPY_AND_ASSIGN - key: llvm-else-after-return.WarnOnUnfixable value: '0' - - key: openmp-exception-escape.IgnoredExceptions - value: '' + - key: readability-simplify-subscript-expr.Types + value: '::std::basic_string;::std::basic_string_view;::std::vector;::std::array' ... - From 025d3b13e91bed07995f94ab5867578be0b11dbf Mon Sep 17 00:00:00 2001 From: "Lee J. O'Riordan" Date: Thu, 14 Oct 2021 17:04:04 +0100 Subject: [PATCH 40/45] Disable format rules for OpenMP pragmas --- bin/format | 1 + .../src/algorithms/AdjointDiff.hpp | 73 ++++++++++--------- 2 files changed, 41 insertions(+), 33 deletions(-) diff --git a/bin/format b/bin/format index b2e6fc5e3a..78cf5a8d7e 100755 --- a/bin/format +++ b/bin/format @@ -11,6 +11,7 @@ CLANG_FMT_STYLE_CFG = { "BasedOnStyle": "llvm", "BreakBeforeBraces": "Attach", "IndentWidth": 4, + "IndentPPDirectives": "None", } SRCFILE_EXT = ("c", "cc", "cpp", "cxx", "h", "hh", "hpp", "hxx", "cu", "cuh") diff --git a/pennylane_lightning/src/algorithms/AdjointDiff.hpp b/pennylane_lightning/src/algorithms/AdjointDiff.hpp index 479e906aa4..9c04267c01 100644 --- a/pennylane_lightning/src/algorithms/AdjointDiff.hpp +++ b/pennylane_lightning/src/algorithms/AdjointDiff.hpp @@ -524,40 +524,42 @@ template class AdjointJacobian { inline void applyObservables(std::vector> &states, const StateVectorManaged &reference_state, const std::vector> &observables) { + // clang-format off // Globally scoped exception value to be captured within OpenMP block. // See the following for OpenMP design decisions: // https://www.openmp.org/wp-content/uploads/openmp-examples-4.5.0.pdf std::exception_ptr ex = nullptr; size_t num_observables = observables.size(); -#if defined _OPENMP -#pragma omp parallel default(none) \ - shared(states, reference_state, observables, ex, num_observables) + #if defined _OPENMP + #pragma omp parallel default(none) \ + shared(states, reference_state, observables, ex, num_observables) { -#pragma omp for -#endif + #pragma omp for + #endif for (size_t h_i = 0; h_i < num_observables; h_i++) { try { states[h_i].updateData(reference_state.getDataVector()); applyObservable(states[h_i], observables[h_i]); } catch (...) { -#if defined _OPENMP -#pragma omp critical -#endif + #if defined _OPENMP + #pragma omp critical + #endif ex = std::current_exception(); -#if defined _OPENMP -#pragma omp cancel for -#endif + #if defined _OPENMP + #pragma omp cancel for + #endif } } -#if defined _OPENMP + #if defined _OPENMP if (ex) { -#pragma omp cancel parallel + #pragma omp cancel parallel } } -#endif + #endif if (ex) { std::rethrow_exception(ex); } + // clang-format on } /** @@ -572,39 +574,41 @@ template class AdjointJacobian { inline void applyOperationsAdj(std::vector> &states, const OpsData &operations, size_t op_idx) { + // clang-format off // Globally scoped exception value to be captured within OpenMP block. // See the following for OpenMP design decisions: // https://www.openmp.org/wp-content/uploads/openmp-examples-4.5.0.pdf std::exception_ptr ex = nullptr; size_t num_states = states.size(); -#if defined _OPENMP -#pragma omp parallel default(none) \ - shared(states, operations, op_idx, ex, num_states) + #if defined _OPENMP + #pragma omp parallel default(none) \ + shared(states, operations, op_idx, ex, num_states) { -#pragma omp for -#endif + #pragma omp for + #endif for (size_t obs_idx = 0; obs_idx < num_states; obs_idx++) { try { applyOperationAdj(states[obs_idx], operations, op_idx); } catch (...) { -#if defined _OPENMP -#pragma omp critical -#endif + #if defined _OPENMP + #pragma omp critical + #endif ex = std::current_exception(); -#if defined _OPENMP -#pragma omp cancel for -#endif + #if defined _OPENMP + #pragma omp cancel for + #endif } } -#if defined _OPENMP + #if defined _OPENMP if (ex) { -#pragma omp cancel parallel + #pragma omp cancel parallel } } -#endif + #endif if (ex) { std::rethrow_exception(ex); } + // clang-format on } /** @@ -750,11 +754,14 @@ template class AdjointJacobian { !operations.getOpsInverses()[op_idx]) * (2 * (0b1 ^ operations.getOpsInverses()[op_idx]) - 1); -#if defined _OPENMP -#pragma omp parallel for default(none) \ - shared(H_lambda, jac, mu, scalingFactor, trainableParamNumber, tp_it, \ - num_observables) -#endif +// clang-format off + #if defined _OPENMP + #pragma omp parallel for default(none) \ + shared(H_lambda, jac, mu, scalingFactor, \ + trainableParamNumber, tp_it, \ + num_observables) + #endif + // clang-format on for (size_t obs_idx = 0; obs_idx < num_observables; obs_idx++) { updateJacobian(H_lambda[obs_idx], mu, jac, From 6638b4bbcad64b646f43e42ee1275ae165f35761 Mon Sep 17 00:00:00 2001 From: "Lee J. O'Riordan" Date: Thu, 14 Oct 2021 17:05:42 +0100 Subject: [PATCH 41/45] Fix misplaced format selector --- pennylane_lightning/src/algorithms/AdjointDiff.hpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pennylane_lightning/src/algorithms/AdjointDiff.hpp b/pennylane_lightning/src/algorithms/AdjointDiff.hpp index 9c04267c01..394d934ab3 100644 --- a/pennylane_lightning/src/algorithms/AdjointDiff.hpp +++ b/pennylane_lightning/src/algorithms/AdjointDiff.hpp @@ -754,7 +754,7 @@ template class AdjointJacobian { !operations.getOpsInverses()[op_idx]) * (2 * (0b1 ^ operations.getOpsInverses()[op_idx]) - 1); -// clang-format off + // clang-format off #if defined _OPENMP #pragma omp parallel for default(none) \ shared(H_lambda, jac, mu, scalingFactor, \ From 0d649f42925f9a20c80b7d4c3591f47c64bea24d Mon Sep 17 00:00:00 2001 From: "Lee J. O'Riordan" Date: Thu, 14 Oct 2021 17:08:32 +0100 Subject: [PATCH 42/45] Update formatting CI env --- .github/workflows/format.yml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/format.yml b/.github/workflows/format.yml index 8a32d5aae9..0fec2482b1 100644 --- a/.github/workflows/format.yml +++ b/.github/workflows/format.yml @@ -17,7 +17,7 @@ jobs: - name: Set up Python uses: actions/setup-python@v2 with: - python-version: 3.8 + python-version: 3.7 - name: Install dependencies run: @@ -42,10 +42,10 @@ jobs: - name: Set up Python uses: actions/setup-python@v2 with: - python-version: 3.8 + python-version: 3.7 - name: Install dependencies - run: sudo apt update && sudo apt -y install clang-tidy-11 python3 cmake g++ + run: sudo apt update && sudo apt -y install clang-tidy-11 cmake g++ env: DEBIAN_FRONTEND: noninteractive From 96711f517804f918876240cdcdc4e05e19587ce5 Mon Sep 17 00:00:00 2001 From: "Lee J. O'Riordan" Date: Thu, 14 Oct 2021 17:10:36 +0100 Subject: [PATCH 43/45] Remove deleted method --- .../src/algorithms/AdjointDiff.hpp | 17 ----------------- 1 file changed, 17 deletions(-) diff --git a/pennylane_lightning/src/algorithms/AdjointDiff.hpp b/pennylane_lightning/src/algorithms/AdjointDiff.hpp index 394d934ab3..86254d8258 100644 --- a/pennylane_lightning/src/algorithms/AdjointDiff.hpp +++ b/pennylane_lightning/src/algorithms/AdjointDiff.hpp @@ -171,23 +171,6 @@ template class ObsDatum { obs_params_(std::move(obs_params)), obs_wires_{ std::move(obs_wires)} {}; - /** - * @brief Move constructor for an ObsDatum object, representing a given - * observable. - * - * @param obs_name Name of each operation of the observable. Tensor product - * observables have more than one operation. - * @param obs_params Parameters for a given obserable operation ({} if - * optional). - * @param obs_wires Wires upon which to apply operation. Each observable - * operation will be a separate nested list. - */ - /*ObsDatum(std::vector &&obs_name, - std::vector &&obs_params, - std::vector> &&obs_wires) - : obs_name_{std::move(obs_name)}, obs_params_{std::move(obs_params)}, - obs_wires_{std::move(obs_wires)} {};*/ - /** * @brief Get the number of operations in observable. * From ee5fda328313ff85456319541da806d9d6f1b2d0 Mon Sep 17 00:00:00 2001 From: "Lee J. O'Riordan" Date: Thu, 14 Oct 2021 17:35:05 +0100 Subject: [PATCH 44/45] Fix comment issues for clang-format --- pennylane_lightning/src/algorithms/AdjointDiff.hpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/pennylane_lightning/src/algorithms/AdjointDiff.hpp b/pennylane_lightning/src/algorithms/AdjointDiff.hpp index 86254d8258..3beaf916f8 100644 --- a/pennylane_lightning/src/algorithms/AdjointDiff.hpp +++ b/pennylane_lightning/src/algorithms/AdjointDiff.hpp @@ -738,12 +738,14 @@ template class AdjointJacobian { (2 * (0b1 ^ operations.getOpsInverses()[op_idx]) - 1); // clang-format off + #if defined _OPENMP #pragma omp parallel for default(none) \ shared(H_lambda, jac, mu, scalingFactor, \ trainableParamNumber, tp_it, \ num_observables) #endif + // clang-format on for (size_t obs_idx = 0; obs_idx < num_observables; obs_idx++) { From 972bf3454e36674ca09a2edeec0e0c3c52493de3 Mon Sep 17 00:00:00 2001 From: "Lee J. O'Riordan" Date: Fri, 15 Oct 2021 09:11:46 +0100 Subject: [PATCH 45/45] Avoid ARM mac wheels built during PRs --- .github/workflows/wheel_macos_arm64.yml | 1 - 1 file changed, 1 deletion(-) diff --git a/.github/workflows/wheel_macos_arm64.yml b/.github/workflows/wheel_macos_arm64.yml index de0bc0ca58..c0b83ab86c 100644 --- a/.github/workflows/wheel_macos_arm64.yml +++ b/.github/workflows/wheel_macos_arm64.yml @@ -3,7 +3,6 @@ on: push: branches: - master - pull_request: env: CIBW_BUILD: 'cp37-* cp38-* cp39-*'