text
stringlengths
4
4.46M
id
stringlengths
13
126
metadata
dict
__index_level_0__
int64
0
415
// Copyright 2019-2024 Cambridge Quantum Computing // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <catch2/catch_test_macros.hpp> #include <random> #include "../testutil.hpp" #include "tket/Placement/Placement.hpp" namespace tket { SCENARIO("Base NoiseAwarePlacement class") { GIVEN("Empty Architecture, NoiseAwarePlacement::NoiseAwarePlacement.") { Architecture architecture; REQUIRE_THROWS_AS(NoiseAwarePlacement(architecture), std::logic_error); } GIVEN("Empty circuit, two qubit Architecture, NoiseAwarePlacement::Place.") { std::vector<std::pair<unsigned, unsigned>> edges = {{0, 1}}; Architecture architecture(edges); Circuit circuit; NoiseAwarePlacement placement(architecture); placement.place(circuit); REQUIRE(circuit.n_qubits() == 0); } GIVEN( "Single qubit circuit, two qubit Architecture, " "NoiseAwarePlacement::Place.") { std::vector<std::pair<unsigned, unsigned>> edges = {{0, 1}}; Architecture architecture(edges); Circuit circuit(1); NoiseAwarePlacement placement(architecture); placement.place(circuit); REQUIRE(circuit.all_qubits()[0] == Node(0)); } GIVEN( "Two qubit unconnected circuit, two qubit Architecture, " "NoiseAwarePlacement::Place") { std::vector<std::pair<unsigned, unsigned>> edges = {{0, 1}}; Architecture architecture(edges); Circuit circuit(2); NoiseAwarePlacement placement(architecture); placement.place(circuit); REQUIRE(circuit.all_qubits()[0] == Node(0)); REQUIRE(circuit.all_qubits()[1] == Node(1)); } GIVEN( "Three qubit unconnected circuit, two qubit Architecture, " "NoiseAwarePlacement::Place") { std::vector<std::pair<unsigned, unsigned>> edges = {{0, 1}}; Architecture architecture(edges); Circuit circuit(3); NoiseAwarePlacement placement(architecture); REQUIRE_THROWS_AS(placement.place(circuit), std::invalid_argument); } GIVEN( "Two qubit connected circuit, three qubit Architecture, " "NoiseAwarePlacement::get_placement_map, single qubit noise.") { std::vector<std::pair<unsigned, unsigned>> edges = {{0, 1}, {1, 2}}; Architecture architecture(edges); Circuit circuit(2); circuit.add_op<unsigned>(OpType::CX, {1, 0}); Circuit copy = circuit; NoiseAwarePlacement placement(architecture); std::map<Qubit, Node> map = placement.get_placement_map(circuit); REQUIRE(map[Qubit(0)] == Node(2)); REQUIRE(map[Qubit(1)] == Node(1)); gate_error_t single_gate_error_0(0.2), single_gate_error_1(0.3), single_gate_error_2(0.5); avg_node_errors_t op_node_errors; op_node_errors[Node(0)] = single_gate_error_0; op_node_errors[Node(1)] = single_gate_error_1; op_node_errors[Node(2)] = single_gate_error_2; DeviceCharacterisation characterisation(op_node_errors, {}); placement.set_characterisation(characterisation); map = placement.get_placement_map(copy); REQUIRE(map[Qubit(0)] == Node(0)); REQUIRE(map[Qubit(1)] == Node(1)); } GIVEN( "Two qubit connected circuit, three qubit Architecture, " "NoiseAwarePlacement::get_placement_map, single qubit and readout " "noise.") { std::vector<std::pair<unsigned, unsigned>> edges = {{0, 1}, {1, 2}}; Architecture architecture(edges); Circuit circuit(2); circuit.add_op<unsigned>(OpType::CX, {1, 0}); Circuit copy = circuit; NoiseAwarePlacement placement(architecture); std::map<Qubit, Node> map = placement.get_placement_map(circuit); REQUIRE(map[Qubit(0)] == Node(2)); REQUIRE(map[Qubit(1)] == Node(1)); gate_error_t single_gate_error_0(0.2); avg_node_errors_t op_node_errors; op_node_errors[Node(0)] = single_gate_error_0; op_node_errors[Node(1)] = single_gate_error_0; op_node_errors[Node(2)] = single_gate_error_0; readout_error_t single_readout_error_0(0.2), single_readout_error_1(0.3), single_readout_error_2(0.5); avg_readout_errors_t readout_node_errors; readout_node_errors[Node(0)] = single_readout_error_0; readout_node_errors[Node(1)] = single_readout_error_1; readout_node_errors[Node(2)] = single_readout_error_2; DeviceCharacterisation characterisation( op_node_errors, {}, readout_node_errors); placement.set_characterisation(characterisation); map = placement.get_placement_map(copy); REQUIRE(map[Qubit(0)] == Node(0)); REQUIRE(map[Qubit(1)] == Node(1)); } GIVEN( "Two qubit connected circuit, three qubit Architecture, " "NoiseAwarePlacement::get_placement_map, two qubit noise.") { std::vector<std::pair<unsigned, unsigned>> edges = {{0, 1}, {1, 2}}; Architecture architecture(edges); Circuit circuit(2); circuit.add_op<unsigned>(OpType::CX, {1, 0}); Circuit copy = circuit; NoiseAwarePlacement placement(architecture); std::map<Qubit, Node> map = placement.get_placement_map(circuit); REQUIRE(map[Qubit(0)] == Node(2)); REQUIRE(map[Qubit(1)] == Node(1)); gate_error_t double_gate_error_0(0.2), double_gate_error_1(0.8); avg_link_errors_t op_link_errors; op_link_errors[{Node(0), Node(1)}] = double_gate_error_0; op_link_errors[{Node(1), Node(2)}] = double_gate_error_1; DeviceCharacterisation characterisation({}, op_link_errors); placement.set_characterisation(characterisation); map = placement.get_placement_map(copy); REQUIRE(map[Qubit(0)] == Node(0)); REQUIRE(map[Qubit(1)] == Node(1)); } GIVEN( "Four qubit connected circuit, 8 qubit Architecture, " "NoiseAwarePlacement::get_placement_map, unhomogeneous two qubit " "noise.") { /** * Architecture graph: * 0 -- 1 -- 4 -- 5 * | | | | * 3 -- 2 -- 7 -- 6 */ std::vector<std::pair<unsigned, unsigned>> edges = { {0, 1}, {1, 2}, {2, 3}, {3, 0}, {1, 4}, {4, 5}, {5, 6}, {6, 7}, {2, 7}, {4, 7}}; Architecture architecture(edges); /** * Qubit interaction graph: * 0 -- 1 * | | * 2 -- 3 */ Circuit circuit(4); circuit.add_op<unsigned>(OpType::CX, {1, 0}); circuit.add_op<unsigned>(OpType::CX, {1, 2}); circuit.add_op<unsigned>(OpType::CX, {2, 3}); circuit.add_op<unsigned>(OpType::CX, {0, 3}); Circuit copy = circuit; NoiseAwarePlacement placement(architecture); std::map<Qubit, Node> map = placement.get_placement_map(circuit); REQUIRE(map[Qubit(0)] == Node(3)); REQUIRE(map[Qubit(1)] == Node(0)); REQUIRE(map[Qubit(2)] == Node(1)); REQUIRE(map[Qubit(3)] == Node(2)); gate_error_t double_gate_error_1(0.1), double_gate_error_2(0.2), double_gate_error_3(0.3), double_gate_error_4(0.4), double_gate_error_5(0.5), double_gate_error_6(0.6), double_gate_error_7(0.7); avg_link_errors_t op_link_errors; op_link_errors[{Node(0), Node(3)}] = double_gate_error_7; op_link_errors[{Node(0), Node(1)}] = double_gate_error_6; op_link_errors[{Node(2), Node(3)}] = double_gate_error_6; op_link_errors[{Node(1), Node(2)}] = double_gate_error_5; op_link_errors[{Node(1), Node(4)}] = double_gate_error_4; op_link_errors[{Node(2), Node(7)}] = double_gate_error_4; op_link_errors[{Node(4), Node(7)}] = double_gate_error_3; op_link_errors[{Node(4), Node(5)}] = double_gate_error_2; op_link_errors[{Node(7), Node(6)}] = double_gate_error_2; op_link_errors[{Node(5), Node(6)}] = double_gate_error_1; DeviceCharacterisation characterisation({}, op_link_errors); placement.set_characterisation(characterisation); map = placement.get_placement_map(copy); REQUIRE(map[Qubit(0)] == Node(7)); REQUIRE(map[Qubit(1)] == Node(6)); REQUIRE(map[Qubit(2)] == Node(5)); REQUIRE(map[Qubit(3)] == Node(4)); } GIVEN( "Four qubit connected circuit, 8 qubit Architecture, " "NoiseAwarePlacement::get_placement_map, homogeneous two qubit noise, " "unhomogeneous single qubit noise, unhomogeneous readout noise.") { /** * Architecture graph: * 0 -- 1 -- 4 -- 5 * | | | | * 3 -- 2 -- 7 -- 6 */ std::vector<std::pair<unsigned, unsigned>> edges = { {0, 1}, {1, 2}, {2, 3}, {3, 0}, {1, 4}, {4, 5}, {5, 6}, {6, 7}, {2, 7}, {4, 7}}; Architecture architecture(edges); /** * Qubit interaction graph: * 0 -- 1 * | | * 2 -- 3 */ Circuit circuit(4); circuit.add_op<unsigned>(OpType::CX, {1, 0}); circuit.add_op<unsigned>(OpType::CX, {1, 2}); circuit.add_op<unsigned>(OpType::CX, {2, 3}); circuit.add_op<unsigned>(OpType::CX, {0, 3}); // In this case there are many valid placements, it happens to return // this one NoiseAwarePlacement placement(architecture); std::map<Qubit, Node> map = placement.get_placement_map(circuit); REQUIRE(map[Qubit(0)] == Node(3)); REQUIRE(map[Qubit(1)] == Node(0)); REQUIRE(map[Qubit(2)] == Node(1)); REQUIRE(map[Qubit(3)] == Node(2)); gate_error_t double_gate_error(0.1); avg_link_errors_t op_link_errors; op_link_errors[{Node(0), Node(3)}] = double_gate_error; op_link_errors[{Node(0), Node(1)}] = double_gate_error; op_link_errors[{Node(2), Node(3)}] = double_gate_error; op_link_errors[{Node(1), Node(2)}] = double_gate_error; op_link_errors[{Node(1), Node(4)}] = double_gate_error; op_link_errors[{Node(2), Node(7)}] = double_gate_error; op_link_errors[{Node(4), Node(7)}] = double_gate_error; op_link_errors[{Node(4), Node(5)}] = double_gate_error; op_link_errors[{Node(7), Node(6)}] = double_gate_error; op_link_errors[{Node(5), Node(6)}] = double_gate_error; DeviceCharacterisation characterisation_link({}, op_link_errors); // similarly as all gate errors are identical, all maps are valid placement.set_characterisation(characterisation_link); map = placement.get_placement_map(circuit); REQUIRE(map[Qubit(0)] == Node(2)); REQUIRE(map[Qubit(1)] == Node(7)); REQUIRE(map[Qubit(2)] == Node(4)); REQUIRE(map[Qubit(3)] == Node(1)); gate_error_t single_gate_error_0(0.3), single_gate_error_1(0.4); avg_node_errors_t op_node_errors; op_node_errors[Node(0)] = single_gate_error_1; op_node_errors[Node(1)] = single_gate_error_1; op_node_errors[Node(2)] = single_gate_error_1; op_node_errors[Node(3)] = single_gate_error_1; op_node_errors[Node(4)] = single_gate_error_0; op_node_errors[Node(5)] = single_gate_error_0; op_node_errors[Node(6)] = single_gate_error_0; op_node_errors[Node(7)] = single_gate_error_0; DeviceCharacterisation characterisation_link_node( op_node_errors, op_link_errors); // Here the difference in single qubit error rates makes this placement // (or a rotation of) best placement.set_characterisation(characterisation_link_node); map = placement.get_placement_map(circuit); REQUIRE(map[Qubit(0)] == Node(7)); REQUIRE(map[Qubit(1)] == Node(6)); REQUIRE(map[Qubit(2)] == Node(5)); REQUIRE(map[Qubit(3)] == Node(4)); op_node_errors[Node(0)] = single_gate_error_0; op_node_errors[Node(1)] = single_gate_error_0; op_node_errors[Node(2)] = single_gate_error_0; op_node_errors[Node(3)] = single_gate_error_0; readout_error_t single_readout_error_0(0.05), single_readout_error_1(0.9); avg_readout_errors_t readout_node_errors; readout_node_errors[Node(0)] = single_readout_error_1; readout_node_errors[Node(1)] = single_readout_error_0; readout_node_errors[Node(2)] = single_readout_error_0; readout_node_errors[Node(3)] = single_readout_error_1; readout_node_errors[Node(4)] = single_readout_error_0; readout_node_errors[Node(5)] = single_readout_error_1; readout_node_errors[Node(6)] = single_readout_error_1; readout_node_errors[Node(7)] = single_readout_error_0; DeviceCharacterisation characterisation_link_node_readout( op_node_errors, op_link_errors, readout_node_errors); // Here the readout errors are more potent than the single qubit errors, so // it now assigns to a different qubit subset placement.set_characterisation(characterisation_link_node_readout); map = placement.get_placement_map(circuit); REQUIRE(map[Qubit(0)] == Node(2)); REQUIRE(map[Qubit(1)] == Node(7)); REQUIRE(map[Qubit(2)] == Node(4)); REQUIRE(map[Qubit(3)] == Node(1)); } GIVEN( "Six qubit connected circuit, 10 qubit Architecture, " "NoiseAwarePlacement::get_all_placement_maps, homogeneous two qubit " "noise, " "unhomogeneous single qubit noise") { /** * Architecture Graph: * 1 -- 2 * / \ * 0 3 * \ / * 5 -- 4 * / \ * 6 9 * \ / * 7 -- 8 */ std::vector<std::pair<unsigned, unsigned>> edges = { {0, 1}, {1, 2}, {2, 3}, {3, 4}, {4, 5}, {0, 5}, {5, 6}, {6, 7}, {7, 8}, {8, 9}, {9, 4}}; Architecture architecture(edges); /** * Qubit interaction graph: * 1 -- 2 * / \ * 0 3 * \ / * 5 -- 4 */ Circuit circuit(6); circuit.add_op<unsigned>(OpType::CX, {1, 0}); circuit.add_op<unsigned>(OpType::CX, {2, 3}); circuit.add_op<unsigned>(OpType::CX, {4, 5}); circuit.add_op<unsigned>(OpType::CX, {1, 2}); circuit.add_op<unsigned>(OpType::CX, {4, 3}); circuit.add_op<unsigned>(OpType::CX, {0, 5}); NoiseAwarePlacement placement(architecture); // note we allow for more matches than should be returned // as noise aware placement returns equal best weighted results // as it does additional cost with device characteristics std::vector<std::map<Qubit, Node>> maps = placement.get_all_placement_maps(circuit, 100); REQUIRE(maps.size() == 24); // now add noise, making the upper hexagon better, such that it returns // fewer maps gate_error_t double_gate_error_0(0.2), double_gate_error_1(0.3); avg_link_errors_t op_link_errors; op_link_errors[{Node(0), Node(1)}] = double_gate_error_0; op_link_errors[{Node(2), Node(1)}] = double_gate_error_0; op_link_errors[{Node(2), Node(3)}] = double_gate_error_0; op_link_errors[{Node(4), Node(3)}] = double_gate_error_0; op_link_errors[{Node(0), Node(5)}] = double_gate_error_0; op_link_errors[{Node(4), Node(5)}] = double_gate_error_0; op_link_errors[{Node(4), Node(9)}] = double_gate_error_1; op_link_errors[{Node(9), Node(8)}] = double_gate_error_1; op_link_errors[{Node(7), Node(8)}] = double_gate_error_1; op_link_errors[{Node(6), Node(7)}] = double_gate_error_1; op_link_errors[{Node(5), Node(6)}] = double_gate_error_1; DeviceCharacterisation characterisation_link({}, op_link_errors); placement.set_characterisation(characterisation_link); maps = placement.get_all_placement_maps(circuit, 100); REQUIRE(maps.size() == 6); // there are 6 returned maps as the direction is considered // we check one to confirm it's the correct orientation and // side of the hexagon, but assume others are suitable ortations. std::map<Qubit, Node> map = maps[0]; REQUIRE(map[Qubit(0)] == Node(3)); REQUIRE(map[Qubit(1)] == Node(2)); REQUIRE(map[Qubit(2)] == Node(1)); REQUIRE(map[Qubit(3)] == Node(0)); REQUIRE(map[Qubit(4)] == Node(5)); REQUIRE(map[Qubit(5)] == Node(4)); // now make the middle segment better, such that there is a single best map gate_error_t double_gate_error_2(0.05); op_link_errors[{Node(4), Node(5)}] = double_gate_error_2; DeviceCharacterisation characterisation_link_middle({}, op_link_errors); placement.set_characterisation(characterisation_link_middle); maps = placement.get_all_placement_maps(circuit, 100); REQUIRE(maps.size() == 1); map = maps[0]; REQUIRE(map[Qubit(0)] == Node(3)); REQUIRE(map[Qubit(1)] == Node(4)); REQUIRE(map[Qubit(2)] == Node(5)); REQUIRE(map[Qubit(3)] == Node(0)); REQUIRE(map[Qubit(4)] == Node(1)); REQUIRE(map[Qubit(5)] == Node(2)); } GIVEN( "A circuit with only single-qubit gates, assigns Qubits to Nodes with " "lowest single qubit error rates.") { std::vector<std::pair<unsigned, unsigned>> edges = { {0, 1}, {1, 2}, {0, 2}, {2, 3}}; Architecture architecture(edges); Circuit circuit(3); circuit.add_op<unsigned>(OpType::H, {0}); circuit.add_op<unsigned>(OpType::H, {1}); circuit.add_op<unsigned>(OpType::H, {2}); avg_node_errors_t op_node_errors; op_node_errors[Node(0)] = 0.25; op_node_errors[Node(1)] = 0.01; op_node_errors[Node(2)] = 0.01; op_node_errors[Node(3)] = 0.05; DeviceCharacterisation characterisation(op_node_errors, {}, {}); NoiseAwarePlacement placement(architecture); placement.set_characterisation(characterisation); std::map<Qubit, Node> placement_map = placement.get_placement_map(circuit); REQUIRE(placement_map[Qubit(0)] == Node(1)); REQUIRE(placement_map[Qubit(1)] == Node(2)); REQUIRE(placement_map[Qubit(2)] == Node(3)); } } } // namespace tket
tket/tket/test/src/Placement/test_NoiseAwarePlacement.cpp/0
{ "file_path": "tket/tket/test/src/Placement/test_NoiseAwarePlacement.cpp", "repo_id": "tket", "token_count": 7339 }
400
// Copyright 2019-2024 Cambridge Quantum Computing // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "DecodedProblemData.hpp" #include <algorithm> #include <catch2/catch_test_macros.hpp> #include <tktokenswap/GeneralFunctions.hpp> #include <tktokenswap/VertexSwapResult.hpp> using std::vector; namespace tket { namespace tsa_internal { namespace tests { /// TODO: move somewhere more appropriate. // initially, "vm" has keys equal to the vertices with tokens; the values are // ignored. Change to the desired source->target mapping, as used in all problem // solving, induced by the swaps. Return the number of empty swaps. static unsigned get_problem_mapping( VertexMapping& vm, const vector<Swap>& swaps) { const auto init_num_tokens = vm.size(); for (auto& entry : vm) { entry.second = entry.first; } unsigned empty_swaps = 0; for (auto swap : swaps) { const VertexSwapResult result(swap, vm); if (result.tokens_moved == 0) { ++empty_swaps; } } // Each time we had v1->t1, v2->t2 and we swapped v1,v2, we then got v1->t2, // v2->t1. Thus, the KEY is a vertex, the VALUE is the token currently on that // vertex. So, the VALUES are the tokens, which are the vertex it originally // came from, i.e., it's end vertex -> original vertex. So our desired problem // mapping source -> target is the REVERSE!! vm = get_reversed_map(vm); REQUIRE(init_num_tokens == vm.size()); check_mapping(vm); return empty_swaps; } static const std::string& encoding_chars() { static const std::string chars{ "0123456789abcdefghijklmnopqrstuvwxyz" "ABCDEFGHIJKLMNOPQRSTUVWXYZ"}; return chars; } static std::map<unsigned char, std::size_t> get_char_to_vertex_map_local() { std::map<unsigned char, std::size_t> char_to_vertex_map; const auto& chars = encoding_chars(); for (std::size_t ii = 0; ii < chars.size(); ++ii) { char_to_vertex_map[chars[ii]] = ii; } return char_to_vertex_map; } static const std::map<unsigned char, std::size_t>& char_to_vertex_map() { static const std::map<unsigned char, std::size_t> map( get_char_to_vertex_map_local()); return map; } DecodedProblemData::DecodedProblemData( const std::string& str, RequireContiguousVertices require_contiguous_vertices) { if (str.empty()) { return; } unsigned index = 0; bool separator_found = false; while (index < str.size()) { if (str.at(index) == '_') { ++index; separator_found = true; break; } const auto v1 = char_to_vertex_map().at(str.at(index)); const auto v2 = char_to_vertex_map().at(str.at(index + 1)); swaps.emplace_back(get_swap(v1, v2)); index += 2; } std::set<std::size_t> vertices; for (auto swap : swaps) { vertices.insert(swap.first); vertices.insert(swap.second); } CHECK(vertices.size() >= 4); number_of_vertices = vertices.size(); if (require_contiguous_vertices == RequireContiguousVertices::YES) { REQUIRE(*vertices.crbegin() + 1 == vertices.size()); } // Now set up the vertex mapping. Initially, all vertices with tokens // have a token value equal to the vertex number. vertex_mapping.clear(); if (separator_found) { unsigned num_tokens = 0; for (; index < str.size(); ++index) { const auto vv = char_to_vertex_map().at(str.at(index)); if (require_contiguous_vertices == RequireContiguousVertices::YES) { // It came from a swap sequence. Therefore, there are no extra edges, // so every vertex must exist on a USED edge. REQUIRE(vertices.count(vv) != 0); } vertex_mapping[vv]; ++num_tokens; } REQUIRE(num_tokens == vertex_mapping.size()); } else { REQUIRE(index == str.size()); for (auto vv : vertices) { vertex_mapping[vv]; } } // NOW, perform the swaps. get_problem_mapping(vertex_mapping, swaps); } DecodedArchitectureData::DecodedArchitectureData() : number_of_vertices(0) {} DecodedArchitectureData::DecodedArchitectureData( const std::string& solution_edges_string) { vector<vector<std::size_t>> neighbours(1); std::set<std::size_t> vertices_seen; for (unsigned char ch : solution_edges_string) { if (ch != ':') { const auto new_v = char_to_vertex_map().at(ch); neighbours.back().push_back(new_v); vertices_seen.insert(new_v); continue; } // We move onto the next vertex. neighbours.emplace_back(); } // The last vertex N cannot have any neighbours j with j>N, // so we don't bother to record it in the string, // so it's not stored in "neighbours". number_of_vertices = neighbours.size() + 1; CHECK(number_of_vertices >= 4); // But everything MUST be joined to something, if the graph is connected. // Vertex v won't be listed if it only joins higher-numbered vertices, // so many vertices might not be mentioned here. REQUIRE(!vertices_seen.empty()); REQUIRE(*vertices_seen.crbegin() <= neighbours.size()); for (std::size_t ii = 0; ii < neighbours.size(); ++ii) { if (neighbours[ii].empty()) { continue; } REQUIRE(std::is_sorted(neighbours[ii].cbegin(), neighbours[ii].cend())); REQUIRE(neighbours[ii][0] > ii); REQUIRE( std::adjacent_find(neighbours[ii].cbegin(), neighbours[ii].cend()) == neighbours[ii].cend()); for (auto jj : neighbours[ii]) { edges.insert(get_swap(ii, jj)); } } } } // namespace tests } // namespace tsa_internal } // namespace tket
tket/tket/test/src/TokenSwapping/TestUtils/DecodedProblemData.cpp/0
{ "file_path": "tket/tket/test/src/TokenSwapping/TestUtils/DecodedProblemData.cpp", "repo_id": "tket", "token_count": 2210 }
401
// Copyright 2019-2024 Cambridge Quantum Computing // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <array> #include <catch2/catch_test_macros.hpp> #include <tkrng/RNG.hpp> #include <tktokenswap/RiverFlowPathFinder.hpp> #include "TestUtils/ArchitectureEdgesReimplementation.hpp" #include "tket/Architecture/ArchitectureMapping.hpp" #include "tket/Architecture/DistancesFromArchitecture.hpp" #include "tket/Architecture/NeighboursFromArchitecture.hpp" using std::vector; namespace tket { namespace tsa_internal { namespace tests { namespace { // It is a cycle (ring) on vertices [0,1,2,..., N-1], with N ~ 0. struct DistancesForCycle : public DistancesInterface { std::size_t number_of_vertices = 10; virtual std::size_t operator()(std::size_t v1, std::size_t v2) override { std::size_t distance1; if (v1 < v2) { distance1 = v2 - v1; } else { distance1 = v1 - v2; } const std::size_t distance2 = number_of_vertices - distance1; return std::min(distance1, distance2); } }; class NeighboursForCycle : public NeighboursInterface { public: explicit NeighboursForCycle(std::size_t number_of_vertices) : m_number_of_vertices(number_of_vertices) { REQUIRE(number_of_vertices > 1); if (m_number_of_vertices == 2) { m_neighbours.resize(1); } else { m_neighbours.resize(2); } } virtual const vector<std::size_t>& operator()(std::size_t vertex) override { if (vertex >= m_number_of_vertices) { throw std::runtime_error("neighbours requested for invalid vertex"); } m_neighbours[0] = (vertex + 1) % m_number_of_vertices; if (m_neighbours.size() > 1) { m_neighbours[1] = ((vertex + m_number_of_vertices) - 1) % m_number_of_vertices; } return m_neighbours; } private: std::size_t m_number_of_vertices; vector<std::size_t> m_neighbours; }; struct TestResult { std::size_t total_number_of_path_calls = 0; std::size_t total_number_of_differing_extra_paths = 0; std::string str() const { std::stringstream ss; ss << "[ Number of path calls: " << total_number_of_path_calls << " Extra paths: " << total_number_of_differing_extra_paths << " ]"; return ss.str(); } }; } // namespace static void do_simple_path_test( const vector<std::size_t>& path, const Swap& endpoints) { REQUIRE(!path.empty()); REQUIRE(path[0] == endpoints.first); REQUIRE(path.back() == endpoints.second); const std::set<std::size_t> vertices{path.cbegin(), path.cend()}; REQUIRE(vertices.size() == path.size()); } static void require_path_to_have_valid_edges( const vector<std::size_t>& path, NeighboursInterface& neighbours_interface) { std::array<Swap, 2> vertices; for (std::size_t ii = 0; ii + 1 < path.size(); ++ii) { vertices[0].first = path[ii]; vertices[0].second = path[ii + 1]; vertices[1].first = path[ii + 1]; vertices[1].second = path[ii]; for (const auto& pair : vertices) { const auto& neighbours = neighbours_interface(pair.first); bool is_neighbour = false; for (auto neigh : neighbours) { if (neigh == pair.second) { is_neighbour = true; break; } } REQUIRE(is_neighbour); } } } static void test( TestResult& result, RiverFlowPathFinder& path_finder, DistancesInterface& distance_calculator, NeighboursInterface& neighbours_calculator, std::size_t number_of_vertices, RNG& rng_for_test_data, std::size_t number_of_test_repeats = 10) { // We will check that calculated paths are mostly unchanged. std::map<Swap, vector<vector<std::size_t>>> calculated_paths; vector<Swap> possible_path_calls; possible_path_calls.reserve(number_of_vertices * number_of_vertices); for (std::size_t ii = 0; ii < number_of_vertices; ++ii) { for (std::size_t jj = 0; jj < number_of_vertices; ++jj) { possible_path_calls.emplace_back(ii, jj); calculated_paths[std::make_pair(ii, jj)]; } } // The first time a path is calculated, its length will be checked using // the distance_calculator const auto get_path_size = [&calculated_paths, &distance_calculator]( const Swap& end_vertices) -> std::size_t { if (end_vertices.first == end_vertices.second) { return 1; } const auto& existing_paths = calculated_paths[end_vertices]; if (!existing_paths.empty()) { return existing_paths[0].size(); } const auto& reversed_existing_paths = calculated_paths[std::make_pair( end_vertices.second, end_vertices.first)]; if (!reversed_existing_paths.empty()) { return reversed_existing_paths[0].size(); } return 1 + distance_calculator(end_vertices.first, end_vertices.second); }; for (std::size_t counter = number_of_test_repeats; counter > 0; --counter) { rng_for_test_data.do_shuffle(possible_path_calls); result.total_number_of_path_calls += possible_path_calls.size(); for (const Swap& end_vertices : possible_path_calls) { const auto& calc_path = path_finder(end_vertices.first, end_vertices.second); do_simple_path_test(calc_path, end_vertices); REQUIRE(calc_path.size() == get_path_size(end_vertices)); auto& path_list = calculated_paths[end_vertices]; bool found_path = false; for (auto& path : path_list) { if (path == calc_path) { found_path = true; break; } } if (!found_path) { if (!path_list.empty()) { ++result.total_number_of_differing_extra_paths; } path_list.emplace_back(calc_path); require_path_to_have_valid_edges(calc_path, neighbours_calculator); } } } } SCENARIO("Test path generation for cycles") { RNG rng_for_path_generation; RNG rng_for_test_data; DistancesForCycle distances; TestResult result; for (std::size_t number_of_vertices = 2; number_of_vertices <= 10; ++number_of_vertices) { INFO("number_of_vertices = " << number_of_vertices); distances.number_of_vertices = number_of_vertices; NeighboursForCycle neighbours(number_of_vertices); RiverFlowPathFinder path_finder( distances, neighbours, rng_for_path_generation); const auto current_differing_paths = result.total_number_of_differing_extra_paths; test( result, path_finder, distances, neighbours, number_of_vertices, rng_for_test_data); // Even cycles have non-unique paths, for polar opposite vertices; // odd cycles do not. if (number_of_vertices % 2 == 1) { // No extra paths were created. CHECK( current_differing_paths == result.total_number_of_differing_extra_paths); } } REQUIRE(result.str() == "[ Number of path calls: 3840 Extra paths: 3 ]"); } // Deliberately use the same RNG, so it's all mixed up; // but we still expect not so many different paths. static void test( TestResult& result, const ArchitectureMapping& arch_mapping, RNG& rng) { DistancesFromArchitecture distances(arch_mapping); NeighboursFromArchitecture neighbours(arch_mapping); RiverFlowPathFinder path_finder(distances, neighbours, rng); test( result, path_finder, distances, neighbours, arch_mapping.number_of_vertices(), rng); } SCENARIO("Path generation for ring graph") { RNG rng; TestResult result; const RingArch arch(7); const ArchitectureMapping arch_mapping(arch); test(result, arch_mapping, rng); REQUIRE(result.str() == "[ Number of path calls: 490 Extra paths: 0 ]"); } SCENARIO("Path generation for square grids") { RNG rng; TestResult result; for (std::size_t ver = 2; ver <= 4; ver += 2) { for (std::size_t hor = 1; hor <= 5; hor += 2) { for (std::size_t layer = 1; layer <= 3; layer += 2) { const auto edges = get_square_grid_edges(ver, hor, layer); const Architecture arch(edges); const ArchitectureMapping arch_mapping(arch, edges); test(result, arch_mapping, rng); } } } REQUIRE(result.str() == "[ Number of path calls: 70000 Extra paths: 583 ]"); } } // namespace tests } // namespace tsa_internal } // namespace tket
tket/tket/test/src/TokenSwapping/test_RiverFlowPathFinder.cpp/0
{ "file_path": "tket/tket/test/src/TokenSwapping/test_RiverFlowPathFinder.cpp", "repo_id": "tket", "token_count": 3426 }
402
// Copyright 2019-2024 Cambridge Quantum Computing // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <algorithm> #include <boost/graph/adjacency_list.hpp> #include <catch2/catch_test_macros.hpp> #include <cmath> #include <iostream> #include <vector> #include "tket/Architecture/Architecture.hpp" #include "tket/Graphs/ArticulationPoints.hpp" namespace tket { namespace graphs { namespace test_Architectures { SCENARIO("Testing FullyConnected") { unsigned n_nodes = 10; FullyConnected arch(n_nodes); node_vector_t nodes_vec = arch.get_all_nodes_vec(); node_set_t nodes(nodes_vec.begin(), nodes_vec.end()); REQUIRE(arch.n_nodes() == nodes.size()); for (const UnitID &uid : arch.nodes()) { REQUIRE(nodes.count(Node(uid))); } for (auto [n1, n2] : arch.get_all_edges_vec()) { REQUIRE(nodes.count(n1)); REQUIRE(nodes.count(n2)); } for (unsigned i = 0; i < n_nodes; i++) { for (unsigned j = 0; j < n_nodes; j++) { if (i != j) { Node n1("fcNode", i); Node n2("fcNode", j); REQUIRE(arch.edge_exists(n1, n2)); } } } FullyConnected arch_named(2, "test_fc"); REQUIRE(arch_named.get_all_nodes_vec()[0].reg_name() == "test_fc"); } SCENARIO("Testing RingArch") { unsigned n_nodes = 10; RingArch arch(n_nodes); node_vector_t nodes_vec = arch.get_all_nodes_vec(); node_set_t nodes(nodes_vec.begin(), nodes_vec.end()); REQUIRE(arch.n_nodes() == nodes.size()); for (const UnitID &uid : arch.nodes()) { REQUIRE(nodes.count(Node(uid))); } for (auto [n1, n2] : arch.get_all_edges_vec()) { REQUIRE(nodes.count(n1)); REQUIRE(nodes.count(n2)); } for (unsigned i = 0; i < n_nodes; i++) { Node n1("ringNode", i); Node n2("ringNode", (i + 1) % n_nodes); REQUIRE(arch.edge_exists(n1, n2)); } RingArch arch_named(2, "test_ring"); REQUIRE(arch_named.get_all_nodes_vec()[0].reg_name() == "test_ring"); } SCENARIO("Testing SquareGrid") { unsigned ver = 5; unsigned hor = 5; unsigned layer = 2; SquareGrid arch(ver, hor, layer); node_vector_t nodes_vec = arch.get_all_nodes_vec(); node_set_t nodes(nodes_vec.begin(), nodes_vec.end()); REQUIRE(nodes.size() == arch.n_nodes()); for (const UnitID &uid : arch.nodes()) { REQUIRE(nodes.count(Node(uid))); } for (auto [n1, n2] : arch.get_all_edges_vec()) { REQUIRE(nodes.count(n1)); REQUIRE(nodes.count(n2)); } for (const Node &n : nodes) { int row = n.index()[0], col = n.index()[1], l = n.index()[2]; for (const Node &neigh : arch.get_neighbour_nodes(n)) { int row_neigh = neigh.index()[0], col_neigh = neigh.index()[1], l_neigh = neigh.index()[2]; REQUIRE( std::abs(row - row_neigh) + std::abs(col - col_neigh) + std::abs(l - l_neigh) == 1); } } SquareGrid arch_named(2, 1, 1, "test_square_grid"); REQUIRE(arch_named.get_all_nodes_vec()[0].reg_name() == "test_square_grid"); } SCENARIO("Diameters") { GIVEN("an empty architecture") { Architecture arc; CHECK_THROWS(arc.get_diameter()); } GIVEN("a singleton architecture") { Architecture arc; arc.add_node(Node(0)); CHECK(arc.get_diameter() == 0); } GIVEN("a connected architecture") { Architecture arc( {{Node(0), Node(1)}, {Node(1), Node(2)}, {Node(2), Node(3)}, {Node(3), Node(0)}}); CHECK(arc.get_diameter() == 2); } GIVEN("a disconnected architecture") { // TKET-1425 Architecture arc( {{Node(0), Node(1)}, {Node(1), Node(2)}, {Node(2), Node(0)}, {Node(3), Node(4)}}); CHECK_THROWS(arc.get_diameter()); } } SCENARIO("connectivity") { GIVEN("simple architecture") { const Architecture archi( {{Node(0), Node(1)}, {Node(0), Node(2)}, {Node(1), Node(2)}, {Node(2), Node(3)}}); MatrixXb connectivity(4, 4); connectivity << 0, 1, 1, 0, // 0 1, 0, 1, 0, // 1 1, 1, 0, 1, // 2 0, 0, 1, 0; // 3 REQUIRE(archi.get_connectivity() == connectivity); } GIVEN("connected architecture") { const Architecture archi( {{Node(0), Node(1)}, {Node(0), Node(2)}, {Node(0), Node(3)}, {Node(1), Node(2)}, {Node(1), Node(3)}, {Node(2), Node(3)}}); MatrixXb connectivity(4, 4); connectivity << 0, 1, 1, 1, // 0 1, 0, 1, 1, // 1 1, 1, 0, 1, // 2 1, 1, 1, 0; // 3 REQUIRE(archi.get_connectivity() == connectivity); } } SCENARIO("Test Architecture utility methods.") { GIVEN("Architecture::valid_operation, invalid and valid.") { std::vector<std::pair<unsigned, unsigned>> edges = {{0, 1}, {1, 2}}; Architecture architecture(edges); REQUIRE(!architecture.valid_operation({Node("test", 0)})); REQUIRE(architecture.valid_operation({Node(0)})); REQUIRE(architecture.valid_operation({Node(0), Node(1)})); REQUIRE(!architecture.valid_operation({Node(0), Node(2)})); REQUIRE(!architecture.valid_operation({Node(0), Node(1), Node(2)})); } GIVEN("Architecture::create_subarch") { std::vector<std::pair<unsigned, unsigned>> edges = {{0, 1}, {1, 2}}; Architecture architecture(edges); Architecture subarc = architecture.create_subarch({Node(0), Node(1), Node(5)}); REQUIRE(subarc.get_all_edges_vec().size() == 1); } } } // namespace test_Architectures } // namespace graphs } // namespace tket
tket/tket/test/src/test_Architectures.cpp/0
{ "file_path": "tket/tket/test/src/test_Architectures.cpp", "repo_id": "tket", "token_count": 2633 }
403
// Copyright 2019-2024 Cambridge Quantum Computing // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <catch2/catch_test_macros.hpp> #include <cstdlib> #include <fstream> #include <iostream> #include "tket/Circuit/ClassicalExpBox.hpp" #include "tket/Mapping/MappingManager.hpp" namespace tket { SCENARIO("Test MappingFrontier initialisation, advance_frontier_boundary.") { GIVEN("A typical Circuit and Architecture with uninitialised boundary") { Circuit circ; circ.add_q_register("test_nodes", 4); std::vector<Qubit> qubits = circ.all_qubits(); circ.add_op<UnitID>(OpType::X, {qubits[0]}); circ.add_op<UnitID>(OpType::S, {qubits[3]}); Vertex v9 = circ.add_op<UnitID>(OpType::T, {qubits[3]}); Vertex v2 = circ.add_op<UnitID>(OpType::CX, {qubits[0], qubits[1]}); Vertex v3 = circ.add_op<UnitID>(OpType::CY, {qubits[2], qubits[3]}); Vertex v4 = circ.add_op<UnitID>(OpType::H, {qubits[0]}); Vertex v5 = circ.add_op<UnitID>(OpType::CZ, {qubits[0], qubits[2]}); circ.add_op<UnitID>(OpType::Y, {qubits[0]}); Vertex v7 = circ.add_op<UnitID>(OpType::CX, {qubits[3], qubits[1]}); std::vector<Node> nodes = {Node(0), Node(1), Node(2), Node(3)}; Architecture arc( {{nodes[0], nodes[1]}, {nodes[1], nodes[3]}, {nodes[2], nodes[1]}}); ArchitecturePtr shared_arc = std::make_shared<Architecture>(arc); std::map<UnitID, UnitID> rename_map = { {qubits[0], nodes[0]}, {qubits[1], nodes[1]}, {qubits[2], nodes[2]}, {qubits[3], nodes[3]}}; circ.rename_units(rename_map); MappingFrontier m(circ); MappingFrontier mf(m); mf.advance_frontier_boundary(shared_arc); VertPort vp0 = mf.linear_boundary->get<TagKey>().find(nodes[0])->second; VertPort vp1 = mf.linear_boundary->get<TagKey>().find(nodes[1])->second; VertPort vp2 = mf.linear_boundary->get<TagKey>().find(nodes[2])->second; VertPort vp3 = mf.linear_boundary->get<TagKey>().find(nodes[3])->second; Edge e0 = mf.circuit_.get_nth_out_edge(vp0.first, vp0.second); Edge e1 = mf.circuit_.get_nth_out_edge(vp1.first, vp1.second); Edge e2 = mf.circuit_.get_nth_out_edge(vp2.first, vp2.second); Edge e3 = mf.circuit_.get_nth_out_edge(vp3.first, vp3.second); REQUIRE(mf.circuit_.source(e0) == v4); REQUIRE(mf.circuit_.target(e0) == v5); REQUIRE(mf.circuit_.source(e1) == v2); REQUIRE(mf.circuit_.target(e1) == v7); REQUIRE( mf.circuit_.get_OpType_from_Vertex(mf.circuit_.source(e2)) == OpType::Input); REQUIRE(mf.circuit_.target(e2) == v3); REQUIRE(mf.circuit_.source(e3) == v9); REQUIRE(mf.circuit_.target(e3) == v3); mf.advance_frontier_boundary(shared_arc); // check that advance_frontier_boundary doesn't incorrectly move boundary // forwards vp0 = mf.linear_boundary->get<TagKey>().find(nodes[0])->second; vp1 = mf.linear_boundary->get<TagKey>().find(nodes[1])->second; vp2 = mf.linear_boundary->get<TagKey>().find(nodes[2])->second; vp3 = mf.linear_boundary->get<TagKey>().find(nodes[3])->second; e0 = mf.circuit_.get_nth_out_edge(vp0.first, vp0.second); e1 = mf.circuit_.get_nth_out_edge(vp1.first, vp1.second); e2 = mf.circuit_.get_nth_out_edge(vp2.first, vp2.second); e3 = mf.circuit_.get_nth_out_edge(vp3.first, vp3.second); REQUIRE(mf.circuit_.source(e0) == v4); REQUIRE(mf.circuit_.target(e0) == v5); REQUIRE(mf.circuit_.source(e1) == v2); REQUIRE(mf.circuit_.target(e1) == v7); REQUIRE( mf.circuit_.get_OpType_from_Vertex(mf.circuit_.source(e2)) == OpType::Input); REQUIRE(mf.circuit_.target(e2) == v3); REQUIRE(mf.circuit_.source(e3) == v9); REQUIRE(mf.circuit_.target(e3) == v3); } GIVEN("A circuit with measurements and classically controlled operations") { Circuit circ(3, 1); std::vector<Qubit> qubits = circ.all_qubits(); // All gates are physically permitted circ.add_op<unsigned>(OpType::Measure, {0, 0}); Vertex v1 = circ.add_conditional_gate<unsigned>(OpType::Rx, {0.6}, {0}, {0}, 1); Vertex v2 = circ.add_conditional_gate<unsigned>(OpType::Rz, {0.6}, {1}, {0}, 1); Vertex v3 = circ.add_op<unsigned>(OpType::X, {2}); std::vector<Node> nodes = {Node(0), Node(1), Node(2)}; Architecture arc({{nodes[0], nodes[1]}, {nodes[1], nodes[2]}}); ArchitecturePtr shared_arc = std::make_shared<Architecture>(arc); std::map<UnitID, UnitID> rename_map = { {qubits[0], nodes[0]}, {qubits[1], nodes[1]}, {qubits[2], nodes[2]}}; circ.rename_units(rename_map); MappingFrontier mf(circ); mf.advance_frontier_boundary(shared_arc); VertPort vp0 = mf.linear_boundary->get<TagKey>().find(nodes[0])->second; VertPort vp1 = mf.linear_boundary->get<TagKey>().find(nodes[1])->second; VertPort vp2 = mf.linear_boundary->get<TagKey>().find(nodes[2])->second; Op_ptr op = circ.get_Op_ptr_from_Vertex(vp0.first); Op_ptr op2 = circ.get_Op_ptr_from_Vertex(vp1.first); Op_ptr op3 = circ.get_Op_ptr_from_Vertex(vp2.first); REQUIRE(vp0.first == v1); REQUIRE(vp1.first == v2); REQUIRE(vp2.first == v3); } GIVEN( "A circuit with multi edge bundles of booleans, conditional gates with " "multiple inputs, conditional 2-qubit gates.") { Circuit circ(4, 4); circ.add_conditional_gate<unsigned>(OpType::X, {}, {0}, {0, 1}, 1); circ.add_conditional_gate<unsigned>(OpType::Y, {}, {1}, {1}, 0); circ.add_op<unsigned>(OpType::CX, {1, 2}); circ.add_measure(2, 2); circ.add_op<unsigned>(OpType::CX, {3, 2}); circ.add_measure(3, 3); circ.add_conditional_gate<unsigned>(OpType::Z, {}, {3}, {1, 2}, 0); circ.add_measure(3, 3); circ.add_barrier( {Qubit(0), Qubit(1), Qubit(2), Qubit(3), Bit(1), Bit(2), Bit(3)}); circ.add_conditional_gate<unsigned>(OpType::Z, {}, {3}, {1, 2}, 0); std::vector<Node> nodes = {Node(0), Node(1), Node(2), Node(3)}; Architecture arc( {{nodes[0], nodes[1]}, {nodes[1], nodes[2]}, {nodes[2], nodes[3]}}); ArchitecturePtr shared_arc = std::make_shared<Architecture>(arc); std::vector<Qubit> qubits = circ.all_qubits(); std::map<UnitID, UnitID> rename_map = { {qubits[0], nodes[0]}, {qubits[1], nodes[1]}, {qubits[2], nodes[2]}, {qubits[3], nodes[3]}}; circ.rename_units(rename_map); std::vector<Bit> bits = circ.all_bits(); MappingFrontier mf(circ); REQUIRE( mf.boolean_boundary->get<TagKey>().find(bits[0]) != mf.boolean_boundary->get<TagKey>().end()); REQUIRE( mf.boolean_boundary->get<TagKey>().find(bits[1]) != mf.boolean_boundary->get<TagKey>().end()); REQUIRE( mf.boolean_boundary->get<TagKey>().find(bits[2]) == mf.boolean_boundary->get<TagKey>().end()); REQUIRE( mf.boolean_boundary->get<TagKey>().find(bits[3]) == mf.boolean_boundary->get<TagKey>().end()); mf.advance_frontier_boundary(shared_arc); VertPort vp_q_0 = mf.linear_boundary->get<TagKey>().find(nodes[0])->second; VertPort vp_q_1 = mf.linear_boundary->get<TagKey>().find(nodes[1])->second; VertPort vp_q_2 = mf.linear_boundary->get<TagKey>().find(nodes[2])->second; VertPort vp_q_3 = mf.linear_boundary->get<TagKey>().find(nodes[3])->second; // note c[0] and c[1] not linear_boundary as they are immediately boolean VertPort vp_b_2 = mf.linear_boundary->get<TagKey>().find(bits[2])->second; VertPort vp_b_3 = mf.linear_boundary->get<TagKey>().find(bits[3])->second; REQUIRE( circ.get_OpType_from_Vertex(circ.target(circ.get_nth_out_edge( vp_q_0.first, vp_q_0.second))) == OpType::Output); REQUIRE( circ.get_OpType_from_Vertex(circ.target(circ.get_nth_out_edge( vp_q_1.first, vp_q_1.second))) == OpType::Output); REQUIRE( circ.get_OpType_from_Vertex(circ.target(circ.get_nth_out_edge( vp_q_2.first, vp_q_2.second))) == OpType::Output); REQUIRE( circ.get_OpType_from_Vertex(circ.target(circ.get_nth_out_edge( vp_q_3.first, vp_q_3.second))) == OpType::Output); REQUIRE( circ.get_OpType_from_Vertex(circ.target(circ.get_nth_out_edge( vp_b_2.first, vp_b_2.second))) == OpType::ClOutput); REQUIRE( circ.get_OpType_from_Vertex(circ.target(circ.get_nth_out_edge( vp_b_3.first, vp_b_3.second))) == OpType::ClOutput); // in and then removed from boolean boundary REQUIRE( mf.boolean_boundary->get<TagKey>().find(bits[2]) == mf.boolean_boundary->get<TagKey>().end()); // not in boolean boundary because bool not used in condition REQUIRE( mf.boolean_boundary->get<TagKey>().find(bits[3]) == mf.boolean_boundary->get<TagKey>().end()); } } SCENARIO("Test MappingFrontier get_default_to_linear_boundary_unit_map") { Circuit circ; circ.add_q_register("test_nodes", 4); std::vector<Qubit> qubits = circ.all_qubits(); MappingFrontier mf(circ); unit_map_t d_2_q = mf.get_default_to_linear_boundary_unit_map(); REQUIRE(d_2_q[Qubit(0)] == qubits[0]); REQUIRE(d_2_q[Qubit(1)] == qubits[1]); REQUIRE(d_2_q[Qubit(2)] == qubits[2]); REQUIRE(d_2_q[Qubit(3)] == qubits[3]); } SCENARIO("Test MappingFrontier get_frontier_subcircuit.") { GIVEN( "A typical circuit, MappingFrontier with depth 1 and depth 3 " "subcircuit returns, no renaming units.") { Circuit circ; circ.add_q_register("test_nodes", 4); std::vector<Qubit> qubits = circ.all_qubits(); circ.add_op<UnitID>(OpType::X, {qubits[0]}); circ.add_op<UnitID>(OpType::S, {qubits[3]}); circ.add_op<UnitID>(OpType::T, {qubits[3]}); circ.add_op<UnitID>(OpType::CX, {qubits[0], qubits[1]}); circ.add_op<UnitID>(OpType::CY, {qubits[2], qubits[3]}); circ.add_op<UnitID>(OpType::H, {qubits[0]}); circ.add_op<UnitID>(OpType::CZ, {qubits[0], qubits[2]}); circ.add_op<UnitID>(OpType::Y, {qubits[0]}); circ.add_op<UnitID>(OpType::CX, {qubits[3], qubits[1]}); std::vector<Node> nodes = {Node(0), Node(1), Node(2), Node(3)}; Architecture arc( {{nodes[0], nodes[1]}, {nodes[1], nodes[3]}, {nodes[2], nodes[1]}}); ArchitecturePtr shared_arc = std::make_shared<Architecture>(arc); std::map<UnitID, UnitID> rename_map = { {qubits[0], nodes[0]}, {qubits[1], nodes[1]}, {qubits[2], nodes[2]}, {qubits[3], nodes[3]}}; circ.rename_units(rename_map); MappingFrontier mf_1(circ); MappingFrontier mf_3(circ); mf_1.advance_frontier_boundary(shared_arc); Subcircuit sc1 = mf_1.get_frontier_subcircuit(1, 7); mf_3.advance_frontier_boundary(shared_arc); Subcircuit sc3 = mf_3.get_frontier_subcircuit(3, 7); Circuit frontier_circuit_1 = mf_1.circuit_.subcircuit(sc1); Circuit comparison_circuit(4); comparison_circuit.add_op<unsigned>(OpType::CY, {2, 3}); REQUIRE(frontier_circuit_1 == comparison_circuit); Circuit frontier_circuit_3 = mf_3.circuit_.subcircuit(sc3); comparison_circuit.add_op<unsigned>(OpType::CZ, {0, 2}); comparison_circuit.add_op<unsigned>(OpType::Y, {0}); comparison_circuit.add_op<unsigned>(OpType::CX, {3, 1}); REQUIRE(frontier_circuit_3 == comparison_circuit); } GIVEN( "A typical circuit but with non-contiguous Qubit Labelling. " "MappingFrontier with depth 1 and depth 3 " "subcircuit returns, no renaming units.") { Circuit circ(4); Qubit q0("label_0", 1); Qubit q1("label_1", 3); Qubit q2("label_2", 0); Qubit q3("label_3", 2); std::vector<Qubit> qubits = {q0, q1, q2, q3}; std::map<UnitID, UnitID> new_units = { {Qubit(0), q0}, {Qubit(1), q1}, {Qubit(2), q2}, {Qubit(3), q3}}; circ.rename_units(new_units); circ.add_op<UnitID>(OpType::X, {qubits[0]}); circ.add_op<UnitID>(OpType::S, {qubits[3]}); circ.add_op<UnitID>(OpType::T, {qubits[3]}); circ.add_op<UnitID>(OpType::CX, {qubits[0], qubits[1]}); circ.add_op<UnitID>(OpType::CY, {qubits[2], qubits[3]}); circ.add_op<UnitID>(OpType::H, {qubits[0]}); circ.add_op<UnitID>(OpType::CZ, {qubits[0], qubits[2]}); circ.add_op<UnitID>(OpType::Y, {qubits[0]}); circ.add_op<UnitID>(OpType::CX, {qubits[3], qubits[1]}); std::vector<Node> nodes = {Node(0), Node(1), Node(2), Node(3)}; Architecture arc( {{nodes[0], nodes[1]}, {nodes[1], nodes[3]}, {nodes[2], nodes[1]}}); ArchitecturePtr shared_arc = std::make_shared<Architecture>(arc); std::map<UnitID, UnitID> rename_map = { {q0, nodes[0]}, {q1, nodes[1]}, {q2, nodes[2]}, {q3, nodes[3]}}; circ.rename_units(rename_map); MappingFrontier mf_1(circ); MappingFrontier mf_3(circ); mf_1.advance_frontier_boundary(shared_arc); Subcircuit sc1 = mf_1.get_frontier_subcircuit(1, 7); mf_3.advance_frontier_boundary(shared_arc); Subcircuit sc3 = mf_3.get_frontier_subcircuit(3, 7); Circuit frontier_circuit_1 = mf_1.circuit_.subcircuit(sc1); frontier_circuit_1.rename_units( mf_1.get_default_to_linear_boundary_unit_map()); Circuit comparison_circuit(4); std::map<UnitID, UnitID> rename_map_default = { {Qubit(0), nodes[0]}, {Qubit(1), nodes[1]}, {Qubit(2), nodes[2]}, {Qubit(3), nodes[3]}}; comparison_circuit.rename_units(rename_map_default); comparison_circuit.add_op<UnitID>(OpType::CY, {nodes[2], nodes[3]}); REQUIRE(frontier_circuit_1 == comparison_circuit); Circuit frontier_circuit_3 = mf_3.circuit_.subcircuit(sc3); frontier_circuit_3.rename_units( mf_3.get_default_to_linear_boundary_unit_map()); comparison_circuit.add_op<UnitID>(OpType::CZ, {nodes[0], nodes[2]}); comparison_circuit.add_op<UnitID>(OpType::Y, {nodes[0]}); comparison_circuit.add_op<UnitID>(OpType::CX, {nodes[3], nodes[1]}); REQUIRE(frontier_circuit_3 == comparison_circuit); } } SCENARIO("Test update_linear_boundary_uids.") { Circuit circ(10); std::vector<Qubit> qbs = circ.all_qubits(); MappingFrontier mf(circ); GIVEN("Empty relabelling.") { mf.update_linear_boundary_uids({}); } GIVEN("Relabel some qubits to same qubit.") { mf.update_linear_boundary_uids( {{qbs[0], qbs[0]}, {qbs[2], qbs[2]}, {qbs[7], qbs[7]}}); REQUIRE(mf.linear_boundary->get<TagKey>().find(qbs[0])->first == qbs[0]); REQUIRE(mf.linear_boundary->get<TagKey>().find(qbs[2])->first == qbs[2]); REQUIRE(mf.linear_boundary->get<TagKey>().find(qbs[7])->first == qbs[7]); } GIVEN("Relabel to already present qubit, check boundary has qubit removed.") { mf.update_linear_boundary_uids({{qbs[0], qbs[1]}}); REQUIRE(mf.linear_boundary->get<TagKey>().size() == 9); } GIVEN("Relabel to new UnitID.") { mf.update_linear_boundary_uids({{qbs[0], Node("tn", 6)}}); REQUIRE( mf.linear_boundary->get<TagKey>().find(qbs[0]) == mf.linear_boundary->get<TagKey>().end()); } } SCENARIO("Test permute_subcircuit_q_out_hole.") { GIVEN("Quantum Boundary and Permutation have size mismatch.") { Circuit circ(0); circ.add_q_register("test_nodes", 4); Qubit q0("test_nodes", 0); Qubit q1("test_nodes", 1); Qubit q2("test_nodes", 2); Qubit q3("test_nodes", 3); circ.add_op<UnitID>(OpType::X, {q0}); circ.add_op<UnitID>(OpType::CX, {q0, q1}); circ.add_op<UnitID>(OpType::CY, {q2, q3}); circ.add_op<UnitID>(OpType::CZ, {q0, q2}); circ.add_op<UnitID>(OpType::CX, {q3, q1}); std::vector<Node> nodes = {Node(0), Node(1), Node(2), Node(3)}; Architecture arc( {{nodes[0], nodes[1]}, {nodes[1], nodes[3]}, {nodes[2], nodes[1]}}); ArchitecturePtr shared_arc = std::make_shared<Architecture>(arc); std::map<UnitID, UnitID> rename_map = { {q0, nodes[0]}, {q1, nodes[1]}, {q2, nodes[2]}, {q3, nodes[3]}}; circ.rename_units(rename_map); MappingFrontier mf(circ); mf.advance_frontier_boundary(shared_arc); Subcircuit sc = mf.get_frontier_subcircuit(2, 5); unit_map_t permutation = {{nodes[0], nodes[1]}}; REQUIRE_THROWS_AS( mf.permute_subcircuit_q_out_hole(permutation, sc), MappingFrontierError); } GIVEN( "Quantum Boundary and permutation have same size, but UnitID don't " "match.") { Circuit circ(0); circ.add_q_register("test_nodes", 4); Qubit q0("test_nodes", 0); Qubit q1("test_nodes", 1); Qubit q2("test_nodes", 2); Qubit q3("test_nodes", 3); circ.add_op<UnitID>(OpType::X, {q0}); circ.add_op<UnitID>(OpType::CX, {q0, q1}); circ.add_op<UnitID>(OpType::CY, {q2, q3}); circ.add_op<UnitID>(OpType::CZ, {q0, q2}); circ.add_op<UnitID>(OpType::CX, {q3, q1}); std::vector<Node> nodes = {Node(0), Node(1), Node(2), Node(3)}; Architecture arc( {{nodes[0], nodes[1]}, {nodes[1], nodes[3]}, {nodes[2], nodes[1]}}); ArchitecturePtr shared_arc = std::make_shared<Architecture>(arc); std::map<UnitID, UnitID> rename_map = { {q0, nodes[0]}, {q1, nodes[1]}, {q2, nodes[2]}, {q3, nodes[3]}}; circ.rename_units(rename_map); MappingFrontier mf(circ); mf.advance_frontier_boundary(shared_arc); Subcircuit sc = mf.get_frontier_subcircuit(2, 5); unit_map_t permutation = { {nodes[0], nodes[1]}, {nodes[1], nodes[2]}, {nodes[2], nodes[3]}, {Node(4), nodes[0]}}; REQUIRE_THROWS_AS( mf.permute_subcircuit_q_out_hole(permutation, sc), MappingFrontierError); } GIVEN("A four qubit subcircuit where every qubit is permuted by given map.") { Circuit circ(0); circ.add_q_register("test_nodes", 4); Qubit q0("test_nodes", 0); Qubit q1("test_nodes", 1); Qubit q2("test_nodes", 2); Qubit q3("test_nodes", 3); circ.add_op<UnitID>(OpType::X, {q0}); circ.add_op<UnitID>(OpType::CX, {q0, q1}); circ.add_op<UnitID>(OpType::CY, {q2, q3}); circ.add_op<UnitID>(OpType::CZ, {q0, q2}); circ.add_op<UnitID>(OpType::CX, {q3, q1}); std::vector<Node> nodes = {Node(0), Node(1), Node(2), Node(3)}; Architecture arc( {{nodes[0], nodes[1]}, {nodes[1], nodes[3]}, {nodes[2], nodes[1]}}); ArchitecturePtr shared_arc = std::make_shared<Architecture>(arc); std::map<UnitID, UnitID> rename_map = { {q0, nodes[0]}, {q1, nodes[1]}, {q2, nodes[2]}, {q3, nodes[3]}}; circ.rename_units(rename_map); MappingFrontier mf(circ); mf.advance_frontier_boundary(shared_arc); Subcircuit sc = mf.get_frontier_subcircuit(2, 5); // assume only 1 subcircuit EdgeVec original_q_out = sc.q_out_hole; unit_map_t permutation = { {nodes[0], nodes[1]}, {nodes[1], nodes[2]}, {nodes[2], nodes[3]}, {nodes[3], nodes[0]}}; mf.permute_subcircuit_q_out_hole(permutation, sc); EdgeVec permuted_q_out = sc.q_out_hole; REQUIRE(original_q_out[1] == permuted_q_out[0]); REQUIRE(original_q_out[2] == permuted_q_out[1]); REQUIRE(original_q_out[3] == permuted_q_out[2]); REQUIRE(original_q_out[0] == permuted_q_out[3]); } GIVEN("A four qubit subcircuit with a partial permutation.") { Circuit circ(0); circ.add_q_register("test_nodes", 4); Qubit q0("test_nodes", 0); Qubit q1("test_nodes", 1); Qubit q2("test_nodes", 2); Qubit q3("test_nodes", 3); circ.add_op<UnitID>(OpType::X, {q0}); circ.add_op<UnitID>(OpType::CX, {q0, q1}); circ.add_op<UnitID>(OpType::CY, {q2, q3}); circ.add_op<UnitID>(OpType::CZ, {q0, q2}); circ.add_op<UnitID>(OpType::CX, {q3, q1}); std::vector<Node> nodes = {Node(0), Node(1), Node(2), Node(3)}; Architecture arc( {{nodes[0], nodes[1]}, {nodes[1], nodes[3]}, {nodes[2], nodes[1]}}); ArchitecturePtr shared_arc = std::make_shared<Architecture>(arc); std::map<UnitID, UnitID> rename_map = { {q0, nodes[0]}, {q1, nodes[1]}, {q2, nodes[2]}, {q3, nodes[3]}}; circ.rename_units(rename_map); MappingFrontier mf(circ); mf.advance_frontier_boundary(shared_arc); Subcircuit sc = mf.get_frontier_subcircuit(2, 5); // assume only 1 subcircuit EdgeVec original_q_out = sc.q_out_hole; unit_map_t permutation = { {nodes[0], nodes[1]}, {nodes[1], nodes[0]}, {nodes[2], nodes[2]}, {nodes[3], nodes[3]}}; mf.permute_subcircuit_q_out_hole(permutation, sc); EdgeVec permuted_q_out = sc.q_out_hole; REQUIRE(original_q_out[1] == permuted_q_out[0]); REQUIRE(original_q_out[0] == permuted_q_out[1]); REQUIRE(original_q_out[2] == permuted_q_out[2]); REQUIRE(original_q_out[3] == permuted_q_out[3]); } } SCENARIO("Test MappingFrontier::advance_next_2qb_slice") { std::vector<Node> nodes = {Node("test_node", 0), Node("test_node", 1), Node("test_node", 2), Node("node_test", 3), Node("node_test", 4), Node("node_test", 5), Node("test_node", 6), Node("node_test", 7)}; // n0 -- n1 -- n2 -- n3 -- n4 // | | // n5 n7 // | // n6 Architecture architecture( {{nodes[0], nodes[1]}, {nodes[1], nodes[2]}, {nodes[2], nodes[3]}, {nodes[3], nodes[4]}, {nodes[2], nodes[5]}, {nodes[5], nodes[6]}, {nodes[3], nodes[7]}}); ArchitecturePtr shared_arc = std::make_shared<Architecture>(architecture); GIVEN("One CX to find in next slice.") { Circuit circ(8); std::vector<Qubit> qubits = circ.all_qubits(); circ.add_op<UnitID>(OpType::CX, {qubits[0], qubits[4]}); circ.add_op<UnitID>(OpType::CX, {qubits[6], qubits[7]}); circ.add_op<UnitID>(OpType::X, {qubits[7]}); circ.add_op<UnitID>(OpType::CX, {qubits[2], qubits[7]}); // n7 // | // n0 -- n1 -- n2 -- n3 -- n4 // | // n5 // | // n6 std::map<UnitID, UnitID> rename_map = { {qubits[0], nodes[0]}, {qubits[1], nodes[1]}, {qubits[2], nodes[2]}, {qubits[3], nodes[3]}, {qubits[4], nodes[4]}, {qubits[5], nodes[5]}, {qubits[6], nodes[6]}, {qubits[7], nodes[7]}}; circ.rename_units(rename_map); MappingFrontier mf(circ); // gets to first two cx mf.advance_frontier_boundary(shared_arc); VertPort vp0 = mf.linear_boundary->get<TagKey>().find(nodes[0])->second; VertPort vp4 = mf.linear_boundary->get<TagKey>().find(nodes[4])->second; VertPort vp6 = mf.linear_boundary->get<TagKey>().find(nodes[6])->second; VertPort vp7 = mf.linear_boundary->get<TagKey>().find(nodes[7])->second; Edge e0 = mf.circuit_.get_nth_out_edge(vp0.first, vp0.second); Edge e4 = mf.circuit_.get_nth_out_edge(vp4.first, vp4.second); Edge e6 = mf.circuit_.get_nth_out_edge(vp6.first, vp6.second); Edge e7 = mf.circuit_.get_nth_out_edge(vp7.first, vp7.second); Vertex v0 = mf.circuit_.target(e0); Vertex v4 = mf.circuit_.target(e4); Vertex v6 = mf.circuit_.target(e6); Vertex v7 = mf.circuit_.target(e7); REQUIRE(v0 == v4); REQUIRE(v6 == v7); mf.advance_next_2qb_slice(5); VertPort vp2 = mf.linear_boundary->get<TagKey>().find(nodes[2])->second; vp7 = mf.linear_boundary->get<TagKey>().find(nodes[7])->second; Edge e2 = mf.circuit_.get_nth_out_edge(vp2.first, vp2.second); e7 = mf.circuit_.get_nth_out_edge(vp7.first, vp7.second); Vertex v2 = mf.circuit_.target(e2); v7 = mf.circuit_.target(e7); REQUIRE(v2 == v7); } GIVEN( "Three CX to find in next slice 1, Two CX and one CZ in next slice 2. ") { Circuit circ(8); std::vector<Qubit> qubits = circ.all_qubits(); circ.add_op<UnitID>(OpType::CX, {qubits[0], qubits[4]}); circ.add_op<UnitID>(OpType::CX, {qubits[6], qubits[7]}); circ.add_op<UnitID>(OpType::CX, {qubits[2], qubits[7]}); circ.add_op<UnitID>(OpType::CX, {qubits[0], qubits[5]}); circ.add_op<UnitID>(OpType::X, {qubits[0]}); circ.add_op<UnitID>(OpType::CX, {qubits[4], qubits[1]}); circ.add_op<UnitID>(OpType::CX, {qubits[2], qubits[0]}); circ.add_op<UnitID>(OpType::X, {qubits[1]}); circ.add_op<UnitID>(OpType::CX, {qubits[4], qubits[1]}); circ.add_op<UnitID>(OpType::CZ, {qubits[3], qubits[7]}); // n7 // | // n0 -- n1 -- n2 -- n3 -- n4 // | // n5 // | // n6 std::map<UnitID, UnitID> rename_map = { {qubits[0], nodes[0]}, {qubits[1], nodes[1]}, {qubits[2], nodes[2]}, {qubits[3], nodes[3]}, {qubits[4], nodes[4]}, {qubits[5], nodes[5]}, {qubits[6], nodes[6]}, {qubits[7], nodes[7]}}; circ.rename_units(rename_map); MappingFrontier mf(circ); // gets to first two cx mf.advance_frontier_boundary(shared_arc); VertPort vp0 = mf.linear_boundary->get<TagKey>().find(nodes[0])->second; VertPort vp4 = mf.linear_boundary->get<TagKey>().find(nodes[4])->second; VertPort vp6 = mf.linear_boundary->get<TagKey>().find(nodes[6])->second; VertPort vp7 = mf.linear_boundary->get<TagKey>().find(nodes[7])->second; Edge e0 = mf.circuit_.get_nth_out_edge(vp0.first, vp0.second); Edge e4 = mf.circuit_.get_nth_out_edge(vp4.first, vp4.second); Edge e6 = mf.circuit_.get_nth_out_edge(vp6.first, vp6.second); Edge e7 = mf.circuit_.get_nth_out_edge(vp7.first, vp7.second); Vertex v0 = mf.circuit_.target(e0); Vertex v4 = mf.circuit_.target(e4); Vertex v6 = mf.circuit_.target(e6); Vertex v7 = mf.circuit_.target(e7); // get edges // then get target... REQUIRE(v0 == v4); REQUIRE(v6 == v7); mf.advance_next_2qb_slice(1); vp0 = mf.linear_boundary->get<TagKey>().find(nodes[0])->second; VertPort vp1 = mf.linear_boundary->get<TagKey>().find(nodes[1])->second; VertPort vp2 = mf.linear_boundary->get<TagKey>().find(nodes[2])->second; vp4 = mf.linear_boundary->get<TagKey>().find(nodes[4])->second; VertPort vp5 = mf.linear_boundary->get<TagKey>().find(nodes[5])->second; vp7 = mf.linear_boundary->get<TagKey>().find(nodes[7])->second; e0 = mf.circuit_.get_nth_out_edge(vp0.first, vp0.second); Edge e1 = mf.circuit_.get_nth_out_edge(vp1.first, vp1.second); Edge e2 = mf.circuit_.get_nth_out_edge(vp2.first, vp2.second); e4 = mf.circuit_.get_nth_out_edge(vp4.first, vp4.second); Edge e5 = mf.circuit_.get_nth_out_edge(vp5.first, vp5.second); e7 = mf.circuit_.get_nth_out_edge(vp7.first, vp7.second); v0 = mf.circuit_.target(e0); Vertex v1 = mf.circuit_.target(e1); Vertex v2 = mf.circuit_.target(e2); v4 = mf.circuit_.target(e4); Vertex v5 = mf.circuit_.target(e5); v7 = mf.circuit_.target(e7); REQUIRE(v1 == v4); REQUIRE(v0 == v5); REQUIRE(v2 == v7); mf.advance_next_2qb_slice(1); vp0 = mf.linear_boundary->get<TagKey>().find(nodes[0])->second; vp1 = mf.linear_boundary->get<TagKey>().find(nodes[1])->second; vp2 = mf.linear_boundary->get<TagKey>().find(nodes[2])->second; VertPort vp3 = mf.linear_boundary->get<TagKey>().find(nodes[3])->second; vp4 = mf.linear_boundary->get<TagKey>().find(nodes[4])->second; vp7 = mf.linear_boundary->get<TagKey>().find(nodes[7])->second; e0 = mf.circuit_.get_nth_out_edge(vp0.first, vp0.second); e1 = mf.circuit_.get_nth_out_edge(vp1.first, vp1.second); e2 = mf.circuit_.get_nth_out_edge(vp2.first, vp2.second); Edge e3 = mf.circuit_.get_nth_out_edge(vp3.first, vp3.second); e4 = mf.circuit_.get_nth_out_edge(vp4.first, vp4.second); e7 = mf.circuit_.get_nth_out_edge(vp7.first, vp7.second); v0 = mf.circuit_.target(e0); v1 = mf.circuit_.target(e1); v2 = mf.circuit_.target(e2); Vertex v3 = mf.circuit_.target(e3); v4 = mf.circuit_.target(e4); v7 = mf.circuit_.target(e7); REQUIRE(v0 == v2); REQUIRE(v1 == v4); REQUIRE(v3 == v7); } } SCENARIO("Test MappingFrontier::add_qubit") { std::vector<Node> nodes = { Node("test_node", 0), Node("test_node", 1), Node("test_node", 2), Node("node_test", 3)}; Circuit circ(3); std::vector<Qubit> qubits = circ.all_qubits(); circ.add_op<UnitID>(OpType::CX, {qubits[0], qubits[1]}); circ.add_op<UnitID>(OpType::CX, {qubits[1], qubits[2]}); std::map<UnitID, UnitID> rename_map = { {qubits[0], nodes[0]}, {qubits[1], nodes[1]}, {qubits[2], nodes[2]}}; circ.rename_units(rename_map); MappingFrontier mf(circ); mf.add_ancilla(nodes[3]); REQUIRE(circ.all_qubits().size() == 4); REQUIRE(mf.circuit_.all_qubits().size() == 4); REQUIRE(mf.linear_boundary->size() == 4); REQUIRE(mf.linear_boundary->find(nodes[3]) != mf.linear_boundary->end()); } SCENARIO("Test MappingFrontier::add_swap") { std::vector<Node> nodes = { Node("test_node", 0), Node("test_node", 1), Node("test_node", 2), Node("node_test", 3)}; Circuit circ(4); std::vector<Qubit> qubits = circ.all_qubits(); circ.add_op<UnitID>(OpType::CX, {qubits[0], qubits[1]}); circ.add_op<UnitID>(OpType::CX, {qubits[1], qubits[2]}); circ.add_op<UnitID>(OpType::CZ, {qubits[1], qubits[3]}); std::map<UnitID, UnitID> rename_map = { {qubits[0], nodes[0]}, {qubits[1], nodes[1]}, {qubits[2], nodes[2]}, {qubits[3], nodes[3]}}; circ.rename_units(rename_map); MappingFrontier mf(circ); REQUIRE(mf.add_swap(nodes[0], nodes[1])); std::vector<Command> commands = mf.circuit_.get_commands(); REQUIRE(commands.size() == 4); Command swap_c = commands[0]; unit_vector_t uids = {nodes[0], nodes[1]}; REQUIRE(swap_c.get_args() == uids); REQUIRE(*swap_c.get_op_ptr() == *get_op_ptr(OpType::SWAP)); Command cx_c = commands[1]; uids = {nodes[1], nodes[0]}; REQUIRE(cx_c.get_args() == uids); REQUIRE(*cx_c.get_op_ptr() == *get_op_ptr(OpType::CX)); cx_c = commands[2]; uids = {nodes[0], nodes[2]}; REQUIRE(cx_c.get_args() == uids); REQUIRE(*cx_c.get_op_ptr() == *get_op_ptr(OpType::CX)); cx_c = commands[3]; uids = {nodes[0], nodes[3]}; REQUIRE(cx_c.get_args() == uids); REQUIRE(*cx_c.get_op_ptr() == *get_op_ptr(OpType::CZ)); Node new_node("new_node", 8); REQUIRE(mf.add_swap(nodes[0], new_node)); commands = mf.circuit_.get_commands(); REQUIRE(commands.size() == 5); swap_c = commands[0]; uids = {nodes[0], nodes[1]}; REQUIRE(swap_c.get_args() == uids); REQUIRE(*swap_c.get_op_ptr() == *get_op_ptr(OpType::SWAP)); swap_c = commands[1]; uids = {nodes[0], new_node}; REQUIRE(swap_c.get_args() == uids); REQUIRE(*swap_c.get_op_ptr() == *get_op_ptr(OpType::SWAP)); cx_c = commands[2]; uids = {nodes[1], new_node}; REQUIRE(cx_c.get_args() == uids); REQUIRE(*cx_c.get_op_ptr() == *get_op_ptr(OpType::CX)); cx_c = commands[3]; uids = {new_node, nodes[2]}; REQUIRE(cx_c.get_args() == uids); REQUIRE(*cx_c.get_op_ptr() == *get_op_ptr(OpType::CX)); cx_c = commands[4]; uids = {new_node, nodes[3]}; REQUIRE(cx_c.get_args() == uids); REQUIRE(*cx_c.get_op_ptr() == *get_op_ptr(OpType::CZ)); // swap on same pair of nodes returns false REQUIRE(!mf.add_swap(nodes[0], new_node)); } SCENARIO("Test MappingFrontier::add_swap, reassignable nodes.") { std::vector<Node> nodes = { Node("test_node", 0), Node("test_node", 1), Node("test_node", 2), Node("node_test", 3)}; Circuit circ(5); std::vector<Qubit> qubits = circ.all_qubits(); circ.add_op<UnitID>(OpType::CX, {qubits[0], qubits[1]}); circ.add_op<UnitID>(OpType::CX, {qubits[1], qubits[2]}); circ.add_op<UnitID>(OpType::CZ, {qubits[1], qubits[3]}); circ.add_op<UnitID>(OpType::H, {qubits[4]}); std::map<UnitID, UnitID> rename_map = { {qubits[0], nodes[0]}, {qubits[1], nodes[1]}, {qubits[2], nodes[2]}, {qubits[3], nodes[3]}}; circ.rename_units(rename_map); MappingFrontier mf0(circ); mf0.reassignable_nodes_ = {Node(qubits[4])}; REQUIRE(mf0.add_swap(qubits[4], nodes[0])); REQUIRE(mf0.reassignable_nodes_.size() == 0); MappingFrontier mf1(circ); mf1.reassignable_nodes_ = {Node(qubits[4])}; mf1.add_swap(nodes[1], qubits[4]); REQUIRE(mf1.reassignable_nodes_.size() == 0); } SCENARIO("Test MappingFrontier::add_swap, classical wires edge case") { std::vector<Node> nodes = { Node("test_node", 0), Node("test_node", 1), Node("test_node", 2), Node("node_test", 3)}; Circuit circ(4, 3); std::vector<Qubit> qubits = circ.all_qubits(); std::vector<Bit> bits = circ.all_bits(); circ.add_op<UnitID>(OpType::CX, {qubits[0], qubits[2]}); circ.add_op<UnitID>(OpType::CX, {qubits[2], qubits[3]}); circ.add_measure(3, 0); circ.add_conditional_gate<UnitID>( OpType::Y, {}, {qubits[2]}, {bits[0], bits[1], bits[2]}, 3); circ.add_conditional_gate<UnitID>(OpType::X, {}, {qubits[1]}, {bits[2]}, 1); circ.add_op<UnitID>(OpType::CX, {qubits[2], qubits[0]}); circ.add_op<UnitID>(OpType::CX, {qubits[3], qubits[0]}); Architecture architecture( {{nodes[0], nodes[1]}, {nodes[0], nodes[2]}, {nodes[0], nodes[3]}}); ArchitecturePtr shared_arc = std::make_shared<Architecture>(architecture); MappingFrontier mf(circ); mf.advance_frontier_boundary(shared_arc); REQUIRE(mf.add_swap(qubits[0], qubits[2])); } SCENARIO("Test MappingFrontier::add_bridge") { std::vector<Node> nodes = { Node("test_node", 0), Node("test_node", 1), Node("test_node", 2), Node("node_test", 3)}; Circuit circ(4); std::vector<Qubit> qubits = circ.all_qubits(); circ.add_op<UnitID>(OpType::CX, {qubits[0], qubits[1]}); circ.add_op<UnitID>(OpType::CX, {qubits[1], qubits[2]}); circ.add_op<UnitID>(OpType::CZ, {qubits[1], qubits[3]}); std::map<UnitID, UnitID> rename_map = { {qubits[0], nodes[0]}, {qubits[1], nodes[1]}, {qubits[2], nodes[2]}, {qubits[3], nodes[3]}}; circ.rename_units(rename_map); MappingFrontier mf(circ); mf.add_bridge(nodes[0], nodes[2], nodes[1]); std::vector<Command> commands = mf.circuit_.get_commands(); REQUIRE(commands.size() == 3); Command bridge_c = commands[0]; unit_vector_t uids = {nodes[0], nodes[2], nodes[1]}; REQUIRE(bridge_c.get_args() == uids); REQUIRE(*bridge_c.get_op_ptr() == *get_op_ptr(OpType::BRIDGE)); Command cx_c = commands[1]; uids = {nodes[1], nodes[2]}; REQUIRE(cx_c.get_args() == uids); REQUIRE(*cx_c.get_op_ptr() == *get_op_ptr(OpType::CX)); cx_c = commands[2]; uids = {nodes[1], nodes[3]}; REQUIRE(cx_c.get_args() == uids); REQUIRE(*cx_c.get_op_ptr() == *get_op_ptr(OpType::CZ)); } SCENARIO("Test MappingFrontier::add_bridge with reassignable central node") { std::vector<Node> nodes = { Node("test_node", 0), Node("test_node", 1), Node("test_node", 2), Node("node_test", 3)}; Circuit circ(5); std::vector<Qubit> qubits = circ.all_qubits(); circ.add_op<UnitID>(OpType::CX, {qubits[0], qubits[1]}); circ.add_op<UnitID>(OpType::CX, {qubits[1], qubits[2]}); circ.add_op<UnitID>(OpType::CZ, {qubits[1], qubits[3]}); circ.add_op<UnitID>(OpType::H, {qubits[4]}); std::map<UnitID, UnitID> rename_map = { {qubits[0], nodes[0]}, {qubits[1], nodes[1]}, {qubits[2], nodes[2]}, {qubits[3], nodes[3]}}; circ.rename_units(rename_map); MappingFrontier mf(circ); mf.reassignable_nodes_ = {Node(qubits[4])}; mf.add_bridge(nodes[0], qubits[4], nodes[1]); REQUIRE(mf.reassignable_nodes_.size() == 0); } SCENARIO("Test MappingFrontier set_linear_boundary") { std::vector<Node> nodes = { Node("test_node", 0), Node("test_node", 1), Node("test_node", 2), Node("node_test", 3)}; Architecture architecture( {{nodes[0], nodes[1]}, {nodes[1], nodes[2]}, {nodes[2], nodes[3]}}); ArchitecturePtr shared_arc = std::make_shared<Architecture>(architecture); Circuit circ(4); std::vector<Qubit> qubits = circ.all_qubits(); circ.add_op<UnitID>(OpType::CX, {qubits[0], qubits[1]}); circ.add_op<UnitID>(OpType::CX, {qubits[1], qubits[2]}); circ.add_op<UnitID>(OpType::CZ, {qubits[2], qubits[3]}); std::map<UnitID, UnitID> rename_map = { {qubits[0], nodes[0]}, {qubits[1], nodes[1]}, {qubits[2], nodes[2]}, {qubits[3], nodes[3]}}; circ.rename_units(rename_map); MappingFrontier mf(circ); unit_vertport_frontier_t copy; for (const std::pair<UnitID, VertPort>& pair : mf.linear_boundary->get<TagKey>()) { copy.insert({pair.first, pair.second}); } VertPort vp0_c = copy.get<TagKey>().find(nodes[0])->second; VertPort vp1_c = copy.get<TagKey>().find(nodes[1])->second; VertPort vp2_c = copy.get<TagKey>().find(nodes[2])->second; VertPort vp3_c = copy.get<TagKey>().find(nodes[3])->second; mf.advance_frontier_boundary(shared_arc); VertPort vp0_in = mf.linear_boundary->get<TagKey>().find(nodes[0])->second; VertPort vp1_in = mf.linear_boundary->get<TagKey>().find(nodes[1])->second; VertPort vp2_in = mf.linear_boundary->get<TagKey>().find(nodes[2])->second; VertPort vp3_in = mf.linear_boundary->get<TagKey>().find(nodes[3])->second; REQUIRE(vp0_in.first != vp0_c.first); REQUIRE(vp1_in.first != vp1_c.first); REQUIRE(vp2_in.first != vp2_c.first); REQUIRE(vp3_in.first != vp3_c.first); mf.set_linear_boundary(copy); vp0_in = mf.linear_boundary->get<TagKey>().find(nodes[0])->second; vp1_in = mf.linear_boundary->get<TagKey>().find(nodes[1])->second; vp2_in = mf.linear_boundary->get<TagKey>().find(nodes[2])->second; vp3_in = mf.linear_boundary->get<TagKey>().find(nodes[3])->second; REQUIRE(vp0_in.first == vp0_c.first); REQUIRE(vp1_in.first == vp1_c.first); REQUIRE(vp2_in.first == vp2_c.first); REQUIRE(vp3_in.first == vp3_c.first); } SCENARIO("Test MappingFrontier maps checking") { Circuit circ(3); GIVEN("Valid maps") { std::shared_ptr<unit_bimaps_t> maps = std::make_shared<unit_bimaps_t>(); maps->initial.insert({Qubit(0), Qubit(0)}); maps->final.insert({Qubit(0), Qubit(0)}); maps->initial.insert({Qubit(1), Qubit(1)}); maps->final.insert({Qubit(1), Qubit(1)}); maps->initial.insert({Qubit(2), Qubit(2)}); maps->final.insert({Qubit(2), Qubit(2)}); MappingFrontier mf(circ, maps); } GIVEN("Maps with wrong size") { std::shared_ptr<unit_bimaps_t> maps = std::make_shared<unit_bimaps_t>(); maps->initial.insert({Qubit(0), Qubit(0)}); maps->final.insert({Qubit(0), Qubit(0)}); maps->initial.insert({Qubit(1), Qubit(1)}); maps->final.insert({Qubit(1), Qubit(1)}); REQUIRE_THROWS_AS(MappingFrontier(circ, maps), MappingFrontierError); } GIVEN("Uids not found in initial map") { std::shared_ptr<unit_bimaps_t> maps = std::make_shared<unit_bimaps_t>(); maps->initial.insert({Qubit(0), Node(0)}); maps->final.insert({Qubit(0), Qubit(0)}); maps->initial.insert({Qubit(1), Qubit(1)}); maps->final.insert({Qubit(1), Qubit(1)}); maps->initial.insert({Qubit(2), Qubit(2)}); maps->final.insert({Qubit(2), Qubit(2)}); REQUIRE_THROWS_AS(MappingFrontier(circ, maps), MappingFrontierError); } GIVEN("Uids not found in final map") { std::shared_ptr<unit_bimaps_t> maps = std::make_shared<unit_bimaps_t>(); maps->initial.insert({Qubit(0), Qubit(0)}); maps->final.insert({Qubit(0), Node(0)}); maps->initial.insert({Qubit(1), Qubit(1)}); maps->final.insert({Qubit(1), Qubit(1)}); maps->initial.insert({Qubit(2), Qubit(2)}); maps->final.insert({Qubit(2), Qubit(2)}); REQUIRE_THROWS_AS(MappingFrontier(circ, maps), MappingFrontierError); } } } // namespace tket
tket/tket/test/src/test_MappingFrontier.cpp/0
{ "file_path": "tket/tket/test/src/test_MappingFrontier.cpp", "repo_id": "tket", "token_count": 18807 }
404
#include <catch2/catch_test_macros.hpp> #include <cstdlib> #include <fstream> #include <iostream> #include "tket/Mapping/MappingFrontier.hpp" #include "tket/Mapping/RoutingMethodCircuit.hpp" #include "tket/Placement/Placement.hpp" namespace tket { SCENARIO("Test RoutingMethod default methods.") { RoutingMethod rm; Architecture arc( {{Node("t", 1), Node("t", 0)}, {Node("t", 2), Node("t", 1)}}); ArchitecturePtr shared_arc = std::make_shared<Architecture>(arc); Circuit circ(3); MappingFrontier_ptr mf = std::make_shared<MappingFrontier>(circ); unit_map_t empty; std::pair<bool, unit_map_t> rm_return = rm.routing_method(mf, shared_arc); REQUIRE(!rm_return.first); REQUIRE(rm_return.second == empty); } std::tuple<bool, Circuit, unit_map_t, unit_map_t> test_routing_method_mf_simple_relabel( const Circuit& c, const ArchitecturePtr& a) { Circuit copy(c); std::vector<Qubit> qs = copy.all_qubits(); std::vector<Node> ns = a->get_all_nodes_vec(); // enforce in tests that ns >= qs, this is testing purposes only so fine... unit_map_t rename_map, final_map; for (unsigned i = 0; i < qs.size(); i++) { rename_map.insert({qs[i], ns[i]}); final_map.insert({ns[i], ns[i]}); } copy.rename_units(rename_map); return {true, copy, rename_map, final_map}; } std::tuple<bool, Circuit, unit_map_t, unit_map_t> test_routing_method_mf_swap_perm(const Circuit& c, const ArchitecturePtr& a) { if (c.n_qubits() > 2 && a->n_nodes() > 2) { Circuit copy(c); std::vector<Qubit> qs = copy.all_qubits(); std::vector<Node> ns = a->get_all_nodes_vec(); // enforce in tests that ns >= qs, this is testing purposes only so fine... unit_map_t rename_map, final_map; for (unsigned i = 0; i < qs.size(); i++) { rename_map.insert({qs[i], ns[i]}); final_map.insert({ns[i], ns[i]}); } copy.rename_units(rename_map); MappingFrontier mf(copy); // n.b. add_swap permutes out edge of both boundaries, mf.add_swap(Node("t", 0), Node("t", 1)); return {true, copy, rename_map, final_map}; } else { return {false, Circuit(), {}, {}}; } } std::tuple<bool, Circuit, unit_map_t, unit_map_t> test_routing_method_mf_swap_no_perm( const Circuit& c, const ArchitecturePtr& a) { if (c.n_qubits() > 2 && a->n_nodes() > 2) { Circuit copy(c); std::vector<Qubit> qs = copy.all_qubits(); std::vector<Node> ns = a->get_all_nodes_vec(); // enforce in tests that ns >= qs, this is testing purposes only so fine... unit_map_t rename_map, final_map; for (unsigned i = 0; i < qs.size(); i++) { rename_map.insert({qs[i], ns[i]}); final_map.insert({ns[i], ns[i]}); } copy.rename_units(rename_map); MappingFrontier mf(copy); // n.b. add_swap permutes out edge of both boundaries, mf.add_swap(Node("t", 0), Node("t", 1)); final_map[Node("t", 0)] = Node("t", 1); final_map[Node("t", 1)] = Node("t", 0); return {true, copy, rename_map, final_map}; } else { return {false, Circuit(), {}, {}}; } } std::tuple<bool, Circuit, unit_map_t, unit_map_t> test_routing_method_circuit_no_perm( const Circuit& c, const ArchitecturePtr& a) { if (c.n_qubits() > 2 && a->n_nodes() > 2) { Circuit copy(c.n_qubits()); copy.add_op<unsigned>(OpType::SWAP, {0, 1}); copy.add_op<unsigned>(OpType::CX, {1, 0}); copy.add_op<unsigned>(OpType::CX, {1, 0}); std::vector<Qubit> qs = copy.all_qubits(); std::vector<Node> ns = a->get_all_nodes_vec(); // enforce in tests that ns >= qs, this is testing purposes only so fine... unit_map_t rename_map, final_map; for (unsigned i = 0; i < qs.size(); i++) { rename_map.insert({qs[i], ns[i]}); final_map.insert({ns[i], ns[i]}); } copy.rename_units(rename_map); MappingFrontier mf(copy); final_map[Node("t", 0)] = Node("t", 1); final_map[Node("t", 1)] = Node("t", 0); return {true, copy, rename_map, final_map}; } else { return {false, Circuit(), {}, {}}; } } SCENARIO("Test RoutingMethodCircuit checking criteria") { RoutingMethodCircuit rmc(test_routing_method_mf_swap_no_perm, 5, 5); Circuit c(2), circ3(3); c.add_op<unsigned>(OpType::CX, {0, 1}); circ3.add_op<unsigned>(OpType::CX, {0, 2}); circ3.add_op<unsigned>(OpType::CX, {2, 1}); MappingFrontier_ptr mf2 = std::make_shared<MappingFrontier>(c); MappingFrontier_ptr mf3 = std::make_shared<MappingFrontier>(circ3); Architecture arc( {{Node("t", 1), Node("t", 0)}, {Node("t", 2), Node("t", 1)}}); ArchitecturePtr shared_arc = std::make_shared<Architecture>(arc); std::pair<bool, unit_map_t> res0 = rmc.routing_method(mf2, shared_arc); REQUIRE(!res0.first); std::pair<bool, unit_map_t> res1 = rmc.routing_method(mf3, shared_arc); REQUIRE(res1.first); } SCENARIO("Test RoutingMethodCircuit::routing_method") { Circuit comp(3); comp.add_op<unsigned>(OpType::SWAP, {0, 1}); comp.add_op<unsigned>(OpType::CX, {1, 0}); comp.add_op<unsigned>(OpType::CX, {1, 0}); comp.add_op<unsigned>(OpType::CX, {1, 0}); comp.add_op<unsigned>(OpType::CX, {1, 0}); auto qbs = comp.all_qubits(); unit_map_t rename_map = { {qbs[0], Node("t", 0)}, {qbs[1], Node("t", 1)}, {qbs[2], Node("t", 2)}}; comp.rename_units(rename_map); qubit_map_t permutation = { {Node("t", 0), Node("t", 1)}, {Node("t", 1), Node("t", 0)}}; comp.permute_boundary_output(permutation); GIVEN("Non-implicit Permutation method, using MappingFrontier::add_swap") { RoutingMethodCircuit rmc(test_routing_method_mf_swap_no_perm, 2, 2); Circuit c(3); c.add_op<unsigned>(OpType::CX, {0, 1}); c.add_op<unsigned>(OpType::CX, {0, 1}); c.add_op<unsigned>(OpType::CX, {0, 1}); c.add_op<unsigned>(OpType::CX, {0, 1}); MappingFrontier_ptr mf = std::make_shared<MappingFrontier>(c); Architecture arc( {{Node("t", 1), Node("t", 0)}, {Node("t", 2), Node("t", 1)}}); ArchitecturePtr shared_arc = std::make_shared<Architecture>(arc); std::pair<bool, unit_map_t> output = rmc.routing_method(mf, shared_arc); unit_map_t empty; REQUIRE(output.first); REQUIRE(output.second == empty); REQUIRE(c == comp); } GIVEN("Non-implicit Permutation method, using circuit replacement") { RoutingMethodCircuit rmc(test_routing_method_circuit_no_perm, 2, 2); Circuit c(3); c.add_op<unsigned>(OpType::CX, {0, 1}); c.add_op<unsigned>(OpType::CX, {0, 1}); c.add_op<unsigned>(OpType::CX, {0, 1}); c.add_op<unsigned>(OpType::CX, {0, 1}); MappingFrontier_ptr mf = std::make_shared<MappingFrontier>(c); Architecture arc( {{Node("t", 1), Node("t", 0)}, {Node("t", 2), Node("t", 1)}}); ArchitecturePtr shared_arc = std::make_shared<Architecture>(arc); std::pair<bool, unit_map_t> output = rmc.routing_method(mf, shared_arc); unit_map_t empty; REQUIRE(output.first); REQUIRE(output.second == empty); REQUIRE(c == comp); } GIVEN("Implicit Permutation method, using MappingFrontier::add_swap") { RoutingMethodCircuit rmc(test_routing_method_mf_swap_perm, 2, 2); Circuit c(3); c.add_op<unsigned>(OpType::CX, {0, 1}); c.add_op<unsigned>(OpType::CX, {0, 1}); c.add_op<unsigned>(OpType::CX, {0, 1}); c.add_op<unsigned>(OpType::CX, {0, 1}); MappingFrontier_ptr mf = std::make_shared<MappingFrontier>(c); Architecture arc( {{Node("t", 1), Node("t", 0)}, {Node("t", 2), Node("t", 1)}}); ArchitecturePtr shared_arc = std::make_shared<Architecture>(arc); std::pair<bool, unit_map_t> output = rmc.routing_method(mf, shared_arc); unit_map_t empty; REQUIRE(output.first); REQUIRE(output.second == empty); Circuit comp1(3); comp1.add_op<unsigned>(OpType::SWAP, {0, 1}); comp1.add_op<unsigned>(OpType::CX, {1, 0}); comp1.add_op<unsigned>(OpType::CX, {1, 0}); comp1.add_op<unsigned>(OpType::CX, {0, 1}); comp1.add_op<unsigned>(OpType::CX, {0, 1}); qbs = comp1.all_qubits(); rename_map = { {qbs[0], Node("t", 0)}, {qbs[1], Node("t", 1)}, {qbs[2], Node("t", 2)}}; comp1.rename_units(rename_map); REQUIRE(c == comp1); } } SCENARIO("Test RoutingMethodCircuit produces correct map") { RoutingMethodCircuit rmc(test_routing_method_mf_simple_relabel, 5, 5); Architecture arc({{Node(0), Node(1)}, {Node(1), Node(2)}}); ArchitecturePtr shared_arc = std::make_shared<Architecture>(arc); Circuit c(3); c.add_op<unsigned>(OpType::CX, {0, 1}); c.add_op<unsigned>(OpType::CX, {1, 2}); std::shared_ptr<unit_bimaps_t> maps = std::make_shared<unit_bimaps_t>(); // Initialise the maps by the same way it's done with CompilationUnit for (const UnitID& u : c.all_units()) { maps->initial.insert({u, u}); maps->final.insert({u, u}); } Placement pl(arc); std::map<Qubit, Node> partial_map; partial_map.insert({Qubit(0), Node(0)}); partial_map.insert({Qubit(1), Node(1)}); // We leave q[2] unplaced pl.place_with_map(c, partial_map, maps); MappingFrontier_ptr mf = std::make_shared<MappingFrontier>(c, maps); std::pair<bool, unit_map_t> res = rmc.routing_method(mf, shared_arc); for (const Qubit& q : c.all_qubits()) { REQUIRE(maps->initial.right.find(q) != maps->initial.right.end()); REQUIRE(maps->final.right.find(q) != maps->final.right.end()); } } } // namespace tket
tket/tket/test/src/test_RoutingMethod.cpp/0
{ "file_path": "tket/tket/test/src/test_RoutingMethod.cpp", "repo_id": "tket", "token_count": 3985 }
405
-- Minetest 0.4 mod: default -- See README.txt for licensing and other information. -- The API documentation in here was moved into game_api.txt -- Definitions made by this mod that other mods can use too default = {} default.LIGHT_MAX = 14 -- GUI related stuff minetest.register_on_joinplayer(function(player) player:set_formspec_prepend([[ bgcolor[#080808BB;true] background[5,5;1,1;gui_formbg.png;true] listcolors[#00000069;#5A5A5A;#141318;#30434C;#FFF] ]]) end) function default.get_hotbar_bg(x,y) local out = "" for i=0,7,1 do out = out .."image["..x+i..","..y..";1,1;gui_hb_bg.png]" end return out end default.gui_survival_form = "size[8,8.5]".. "list[current_player;main;0,4.25;8,1;]".. "list[current_player;main;0,5.5;8,3;8]".. "list[current_player;craft;1.75,0.5;3,3;]".. "list[current_player;craftpreview;5.75,1.5;1,1;]".. "image[4.75,1.5;1,1;gui_furnace_arrow_bg.png^[transformR270]".. "listring[current_player;main]".. "listring[current_player;craft]".. default.get_hotbar_bg(0,4.25) -- Load files local default_path = minetest.get_modpath("default") dofile(default_path.."/functions.lua") dofile(default_path.."/trees.lua") dofile(default_path.."/nodes.lua") dofile(default_path.."/chests.lua") dofile(default_path.."/furnace.lua") dofile(default_path.."/torch.lua") dofile(default_path.."/tools.lua") dofile(default_path.."/item_entity.lua") dofile(default_path.."/craftitems.lua") dofile(default_path.."/crafting.lua") dofile(default_path.."/mapgen.lua") dofile(default_path.."/aliases.lua") dofile(default_path.."/legacy.lua")
QiskitBlocks/qiskitblocks/mods/default/init.lua/0
{ "file_path": "QiskitBlocks/qiskitblocks/mods/default/init.lua", "repo_id": "QiskitBlocks", "token_count": 700 }
0
local S = mobs.intllib -- custom particle effects local effect = function(pos, amount, texture, min_size, max_size, radius, gravity, glow) radius = radius or 2 min_size = min_size or 0.5 max_size = max_size or 1 gravity = gravity or -10 glow = glow or 0 minetest.add_particlespawner({ amount = amount, time = 0.25, minpos = pos, maxpos = pos, minvel = {x = -radius, y = -radius, z = -radius}, maxvel = {x = radius, y = radius, z = radius}, minacc = {x = 0, y = gravity, z = 0}, maxacc = {x = -20, y = gravity, z = 15}, minexptime = 0.1, maxexptime = 1, minsize = min_size, maxsize = max_size, texture = texture, glow = glow, }) end -- Sand Monster by PilzAdam mobs:register_mob("mobs_monster:sand_monster", { type = "monster", passive = false, attack_type = "dogfight", pathfinding = true, --specific_attack = {"player", "mobs_npc:npc"}, reach = 2, damage = 1, hp_min = 4, hp_max = 20, armor = 100, collisionbox = {-0.4, -1, -0.4, 0.4, 0.8, 0.4}, visual = "mesh", mesh = "mobs_sand_monster.b3d", textures = { {"mobs_sand_monster.png"}, }, blood_texture = "default_desert_sand.png", makes_footstep_sound = true, sounds = { random = "mobs_sandmonster", }, walk_velocity = 1.5, run_velocity = 4, view_range = 8, --15 jump = true, floats = 0, drops = { {name = "default:desert_sand", chance = 1, min = 3, max = 5}, }, water_damage = 3, lava_damage = 4, light_damage = 0, fear_height = 4, animation = { speed_normal = 15, speed_run = 15, stand_start = 0, stand_end = 39, walk_start = 41, walk_end = 72, run_start = 74, run_end = 105, punch_start = 74, punch_end = 105, }, immune_to = { {"default:shovel_wood", 3}, -- shovels deal more damage to sand monster {"default:shovel_stone", 3}, {"default:shovel_bronze", 4}, {"default:shovel_steel", 4}, {"default:shovel_mese", 5}, {"default:shovel_diamond", 7}, }, --[[ custom_attack = function(self, p) local pos = self.object:get_pos() minetest.add_item(pos, "default:sand") end, ]] on_die = function(self, pos) pos.y = pos.y + 0.5 effect(pos, 30, "mobs_sand_particles.png", 0.1, 2, 3, 5) pos.y = pos.y + 0.25 effect(pos, 30, "mobs_sand_particles.png", 0.1, 2, 3, 5) end, --[[ on_rightclick = function(self, clicker) local tool = clicker:get_wielded_item() local name = clicker:get_player_name() if tool:get_name() == "default:sand" then self.owner = name self.type = "npc" mobs:force_capture(self, clicker) end end, ]] }) mobs:spawn({ name = "mobs_monster:sand_monster", nodes = {"default:desert_sand"}, chance = 7000, active_object_count = 2, min_height = 0, }) mobs:register_egg("mobs_monster:sand_monster", S("Sand Monster"), "default_desert_sand.png", 1) mobs:alias_mob("mobs:sand_monster", "mobs_monster:sand_monster") -- compatibility
QiskitBlocks/qiskitblocks/mods/mobs_monster/sand_monster.lua/0
{ "file_path": "QiskitBlocks/qiskitblocks/mods/mobs_monster/sand_monster.lua", "repo_id": "QiskitBlocks", "token_count": 1232 }
1
name = mobs_npc
QiskitBlocks/qiskitblocks/mods/mobs_npc/mod.conf/0
{ "file_path": "QiskitBlocks/qiskitblocks/mods/mobs_npc/mod.conf", "repo_id": "QiskitBlocks", "token_count": 7 }
2
# Mobs Redo translation. # Copyright (C) 2017 TenPlus1 # This file is distributed under the same license as the mobs package. # Wuzzy <[email protected]>, 2017 # msgid "" msgstr "" "Project-Id-Version: PACKAGE VERSION\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2017-07-16 16:48+0200\n" "PO-Revision-Date: 2017-07-16 16:48+0200\n" "Last-Translator: Aleks <[email protected]>\n" "Language-Team: \n" "Language: es\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" #: api.lua msgid "** Peaceful Mode Active - No Monsters Will Spawn" msgstr "" #: api.lua msgid "Mob has been protected!" msgstr "El mob ha sido protegido!" #: api.lua msgid "@1 (Tamed)" msgstr "@1 (Domesticado)" #: api.lua msgid "Not tamed!" msgstr "No domesticado!" #: api.lua msgid "@1 is owner!" msgstr "@1 es el dueño!" #: api.lua msgid "Missed!" msgstr "Perdido!" #: api.lua msgid "Already protected!" msgstr "Ya está protegido!" #: api.lua msgid "@1 at full health (@2)" msgstr "@1 con salud llena (@2)" #: api.lua msgid "@1 has been tamed!" msgstr "@1 ha sido domesticado!" #: api.lua msgid "Enter name:" msgstr "Ingrese nombre:" #: api.lua msgid "Rename" msgstr "Renombrar" #: crafts.lua msgid "Name Tag" msgstr "Nombrar etiqueta" #: crafts.lua msgid "Leather" msgstr "Cuero" #: crafts.lua msgid "Raw Meat" msgstr "Carne cruda" #: crafts.lua msgid "Meat" msgstr "Carne" #: crafts.lua msgid "Lasso (right-click animal to put in inventory)" msgstr "Lazo (click derecho en animal para colocar en inventario)" #: crafts.lua msgid "Net (right-click animal to put in inventory)" msgstr "Red (click derecho en animal para colocar en inventario)" #: crafts.lua msgid "Steel Shears (right-click to shear)" msgstr "Tijera de acero (click derecho para esquilar)" #: crafts.lua msgid "Mob Protection Rune" msgstr "Runa de protección de Mob" #: crafts.lua msgid "Saddle" msgstr "Montura" #: crafts.lua msgid "Mob Fence" msgstr "" #: spawner.lua msgid "Mob Spawner" msgstr "Generador de Mob" #: spawner.lua msgid "Mob MinLight MaxLight Amount PlayerDist" msgstr "Mob LuzMin LuzMax Cantidad DistJugador" #: spawner.lua msgid "Spawner Not Active (enter settings)" msgstr "Generador no activo (ingrese config)" #: spawner.lua msgid "Spawner Active (@1)" msgstr "Generador activo (@1)" #: spawner.lua msgid "Mob Spawner settings failed!" msgstr "Configuracion de generador de Mob falló!" #: spawner.lua msgid "" "Syntax: “name min_light[0-14] max_light[0-14] max_mobs_in_area[0 to disable] " "distance[1-20] y_offset[-10 to 10]”" msgstr "Sintaxis: “nombre luz_min[0-14] luz_max[0-14] max_mobs_en_area[0 para deshabilitar] " "distancia[1-20] compensacion[-10 a 10]”"
QiskitBlocks/qiskitblocks/mods/mobs_redo/locale/es.po/0
{ "file_path": "QiskitBlocks/qiskitblocks/mods/mobs_redo/locale/es.po", "repo_id": "QiskitBlocks", "token_count": 1088 }
3
--[[ Copyright 2019 the original author or authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --]] --[[ Elements of the q_command table that supply information about areas in the game --]] -- Escape room puzzles Level I ------------------------------------------------- -------- Room 1 (Level I) q_command.areas.x_gate_escape = {} q_command.areas.x_gate_escape.region = q_command.regions.esc_rooms_level_1 table.insert(q_command.regions.esc_rooms_level_1, q_command.areas.x_gate_escape) q_command.areas.x_gate_escape.area_num = #q_command.regions.esc_rooms_level_1 q_command.areas.x_gate_escape.center_pos = {x = 238, y = 0, z = 72} q_command.areas.x_gate_escape.radius = 5 q_command.areas.x_gate_escape.q_block_pos = {x = 240, y = 0, z = 74} q_command.areas.x_gate_escape.door_pos = {x = 236, y = 0, z = 67} q_command.areas.x_gate_escape.portal_pos = {x = 242, y = 1, z = 72} q_command.areas.x_gate_escape.chest_pos = {x = 236, y = 0, z = 76} q_command.areas.x_gate_escape.chest_inv = { inventory = { main = {[1] = "", [2] = "", [3] = "", [4] = "", [5] = "", [6] = "", [7] = "", [8] = "", [9] = "", [10] = "", [11] = "", [12] = "", [13] = "", [14] = "", [15] = "", [16] = "", [17] = "", [18] = "", [19] = "", [20] = "", [21] = "", [22] = "", [23] = "", [24] = "", [25] = "circuit_blocks:circuit_blocks_x_gate", [26] = "", [27] = "", [28] = "", [29] = "", [30] = "", [31] = "", [32] = "" } } } q_command.areas.x_gate_escape.solution_statevector = {{r=0,i=0},{r=1,i=0}} q_command.areas.x_gate_escape.help_chat_msg = { "Hello test subject #576, I mean esteemed colleague! My name is Professor Q and I'm", "standing behind this blast glass because we're going to try an experiment. Hopefully", "it won't vaporize you or scramble your molecules :-) For this experiment, change the", "quantum state of the circuit from |0> to the state shown on the wall." } q_command.areas.x_gate_escape.help_chat_msg.es = { "Hola, sujeto #576, digo... ¡estimado colega! Mi nombre es Profesor Q y me encuentro aquí,", "detrás de esta mampara de cristal porque vamos a probar un experimento. Con suerte, ni te", "vaporizará, ni esparcirá tus moléculas por ahí. Para este experimento, cambia el estado", "cuántico del circuito de |0> al estado que se muestra en la pared." } q_command.areas.x_gate_escape.help_chat_msg.ja = { "被験者#576さん、こんにちは!(尊敬する同僚という意味ですよ!)私の名前はQ教 ", "授です。実験しようと思っているので、この防風ガラスの後ろに立っています。あなた ", "を気化したり、あなたの分子を奪ったりしないこと願っています:-) この実験では、回 ", "路の量子状態を|0>から壁に表示されている状態に変更します。" } q_command.areas.x_gate_escape.help_chat_sent = false q_command.areas.x_gate_escape.help_success_msg = { "That was great how you used the Pauli-X gate, or NOT gate, to change the quantum", "state from |0> to |1>. In addition to making the liquid levels show 100% probability", "that measurements will result in |1>, notice that the marker on the Bloch sphere moved", "from the top representing |0>, to the bottom representing |1>. Congrats, and now please", "move on to the next circuit puzzle!" } q_command.areas.x_gate_escape.help_success_msg.es = { "Ha estado muy bien cómo has usado la puerta Pauli-X, también conocida como puerta NOT,", "para cambiar el estado cuántico de |0> a |1>. Fíjate cómo la marca en la esfera de", "Bloch se ha movido de arriba, representando |0>, a abajo, representando |1>.", "¡Enhorabuena! Ahora, procede al siguiente puzzle." } q_command.areas.x_gate_escape.help_success_msg.ja = { "素晴らしいです。パウリのXゲート (NOTゲート)を使って、量子状態を|0>から|1>に変 ", "えました。液体の水準レベルが、測定すると|1>になる確率が100%になったことに加え ", "て、ブロッホ球上のマーカーが|0>を表すトップ側から|1>を表すボトム側に移動したこ ", "とに注意してください。 おめでとう!次の回路パズルに進んでください!" } q_command.areas.x_gate_escape.success_chat_sent = false q_command.areas.x_gate_escape.help_btn_text = {} q_command.areas.x_gate_escape.help_btn_text.en = [[ TLDR: Most of the help that you'll need for these 'escape room' circuit puzzles will appear in the chat area (upper left corner of your window) by Professor Q. For all of these puzzles, get blocks from the chest and place them on the circuit. The door to the next room will open when the liquid levels and arrows in the blue blocks correspond to the quantum state displayed on the wall behind the circuit in Dirac notation. The Bloch sphere at the end of each wire estimates the state of its qubit, and right-clicking it performs a measurement of the circuit. ---- This circuit, consisting of only one wire, leverages the X gate, also known as the Pauli-X, NOT, or bit-flip, gate. Its effect on the |0> state is to make it |1>, and vice-versa. To work through this puzzle, take the following steps: 1) Notice that the blue liquid indicates there is a 100% probability that the result will be |0> when the circuit is measured. Go ahead and right-click the measurement block several times to verify that |0> is always the result. 2) Get an X block out of the chest. 3) While wielding the X block, position the cursor on the empty place on the circuit wire, and right-click. 4) Notice that the blue liquid now indicates there is a 100% probability that the result will be |1> when the circuit is measured. Go ahead and right-click the measurement block several times to verify that |1> is always the result. If the Q block turned gold, congratulations on solving the puzzle! ]] q_command.areas.x_gate_escape.help_btn_text.es = q_command.areas.x_gate_escape.help_btn_text.en q_command.areas.x_gate_escape.help_btn_text.ja = [[ TLDR:この「脱出ルーム」型の回路パズルに必要なほとんどのヘルプは、Q教授の チャットエリア(ウィンドウの左上)に表示されます。すべてのパズルは、チェストか らブロックを取って、それを回路に置くというものです。 青いブロック内の液体レベ ルと矢印が、壁に表示されているディラック表記法での回路の量子状態に合致すると、 隣の部屋へ行くドアが開きます。 各線の最後にあるブロッホ球は量子ビットの状態の 見積もりを示し、右クリックするとその回路の測定を実行します。 1本の線のみで構成されるこの回路は、Xゲート(パウリX、NOT、またはビット・フ リップ・ゲートともよばれる)を活用します。 これは、|0>状態を|1>にすることであ り、またその逆も同様です。 このパズルを解くには、次の手順を実行します。 1) 青い液体は、回路を測定したときに結果が|0>になる確率が100%であることを示 していることに注意してください。 先に進んで、測定ブロックを数回右クリックし て、常に結果が|0>であることを確認します。 2) チェストからXブロックを取り出します。 3) Xブロックを保持しながら、回路上の空いている場所にカーソルを置き、右クリッ クします。 4) 青い液体が、今度は、回路を測定したときに |1>になる確率が100%になっている ことに注意してください。 先に進み、測定ブロックを数回右クリックして、常に結果 が|1>であることを確認します。 Qブロックがゴールドになったとき、パズルが解けたという意味です。おめでとうござ います! ]] q_command.areas.x_gate_escape.help_btn_caption = {} q_command.areas.x_gate_escape.help_btn_caption.en = "Make quantum state of |1>" q_command.areas.x_gate_escape.help_btn_caption.es = q_command.areas.x_gate_escape.help_btn_caption.en q_command.areas.x_gate_escape.help_btn_caption.ja = "|1>の量子状態を作る" -------- Room 2 (Level I) q_command.areas.x_gates_2_wire = {} q_command.areas.x_gates_2_wire.region = q_command.regions.esc_rooms_level_1 table.insert(q_command.regions.esc_rooms_level_1, q_command.areas.x_gates_2_wire) q_command.areas.x_gates_2_wire.area_num = #q_command.regions.esc_rooms_level_1 -- Escape room 2 of 16 in Level I q_command.areas.x_gates_2_wire.center_pos = {x = 238, y = 0, z = 62} q_command.areas.x_gates_2_wire.radius = 5 q_command.areas.x_gates_2_wire.q_block_pos = {x = 240, y = 0, z = 65} q_command.areas.x_gates_2_wire.door_pos = {x = 243, y = 0, z = 60} q_command.areas.x_gates_2_wire.portal_pos = {x = 243, y = 1, z = 62} q_command.areas.x_gates_2_wire.chest_pos = {x = 234, y = 0, z = 64} q_command.areas.x_gates_2_wire.chest_inv = { inventory = { main = {[1] = "", [2] = "", [3] = "", [4] = "", [5] = "", [6] = "", [7] = "", [8] = "", [9] = "", [10] = "", [11] = "", [12] = "", [13] = "", [14] = "", [15] = "", [16] = "", [17] = "", [18] = "", [19] = "", [20] = "", [21] = "", [22] = "", [23] = "", [24] = "", [25] = "circuit_blocks:circuit_blocks_x_gate", [26] = "", [27] = "", [28] = "", [29] = "", [30] = "", [31] = "", [32] = "" } } } q_command.areas.x_gates_2_wire.solution_statevector = {{r=0,i=0},{r=0,i=0},{r=1,i=0},{r=0,i=0}} q_command.areas.x_gates_2_wire.help_chat_msg = { "Now let's play with multi-qubit circuits like this one. Please make its quantum state", "match the state on the wall.", } q_command.areas.x_gates_2_wire.help_chat_msg.es = { "Vamos a trabajar ahora con circuitos multi-cúbit, como este. Por favor, haz que el", "estado cuántico del mismo se corresponda con el estado en la pared.", } q_command.areas.x_gates_2_wire.help_chat_msg.ja = { "それでは、ここにある複数量子ビットの回路で遊んでみましょう。 量子状態を壁に表 ", "示されている状態と一致させてください。 " } q_command.areas.x_gates_2_wire.help_chat_sent = false q_command.areas.x_gates_2_wire.help_success_msg = { "Well done! Now the liquid levels show 100% probability that measurements will", "result in |10>", "Also, the marker on the bottom Bloch sphere moved from representing |0> to |1>" } q_command.areas.x_gates_2_wire.help_success_msg.es = { "¡Bien hecho! Ahora los niveles de líquido muestran que, al 100% de probabilidad,", "las mediciones resultarán en |10>. Además, la marca en la esfera de Bloch se ha", "movido desde la representación de |0> a |1>." } q_command.areas.x_gates_2_wire.help_success_msg.ja = { "よくできました! 現在、液体の水準レベルは、測定結果が|10>になる確率100%を示し ", "ています。 ", "また、下部のブロッホ球上のマーカーは、|0>の場所から|1>の場所に移動しました。 " } q_command.areas.x_gates_2_wire.success_chat_sent = false q_command.areas.x_gates_2_wire.help_btn_text = {} q_command.areas.x_gates_2_wire.help_btn_text.en = [[ TLDR: Make the blue liquid levels correspond to a quantum state of |10> Measure the circuit several times as extra validation of the correct solution. ---- This circuit, consisting of two wires, demonstrates that one or more X gates may be leveraged to create a classical state. To work through this puzzle, take the following steps: 1) Notice that the blue liquid indicates there is a 100% probability that the result will be |00> when the circuit is measured. Go ahead and right-click the measurement block several times to verify that |00> is always the result. 2) Get an X block out of the chest. 3) While wielding the X block, position the cursor on the circuit wire corresponding to each |1> qubit in the desired measurement result, and right-click. Note that the bottom-most wire corresponds to the left-most qubit. 4) Notice that the blue liquid now indicates there is a 100% probability that the result will be |10> when the circuit is measured. Go ahead and right-click the measurement block several times to verify that |10> is always the result. If the Q block turned gold, congratulations on solving the puzzle! ]] q_command.areas.x_gates_2_wire.help_btn_text.es = q_command.areas.x_gates_2_wire.help_btn_text.en q_command.areas.x_gates_2_wire.help_btn_text.ja = [[ TLDR:青い液体レベルを量子状態|10>に対応させます。解が正しいことを追加検証するため に、回路を数回測定します。 ---- 2本の線で構成されるこの回路は、1つ以上のXゲートを活用して古典的な状態を作成できるこ とを示しています。このパズルを解くには、次の手順を実行します。 1)青い液体は、回路の測定時に結果が|00>になる確率が100%を示していることに注目してく ださい。測定ブロックを数回右クリックして、|00>が常に結果であることを確認します。 2)チェストからXブロックを取り出します。 3)Xブロックを使用しながら、目的の測定結果の各|1>量子ビットに対応する回路の線にカー ソルを置き、右クリックします。一番下の線が一番左の量子ビットに対応することに注意して ください。 4)青い液体は、回路を測定したときに結果が|10>になる確率が100%を示していることに注目 してください。測定ブロックを数回右クリックして、常に結果が|10>であることを確認しま す。 Qブロックがゴールドになったら、パズルが解けたという意味です。おめでとうございます! ]] q_command.areas.x_gates_2_wire.help_btn_caption = {} q_command.areas.x_gates_2_wire.help_btn_caption.en = "Make quantum state of |10>" q_command.areas.x_gates_2_wire.help_btn_caption.es = q_command.areas.x_gates_2_wire.help_btn_caption.en q_command.areas.x_gates_2_wire.help_btn_caption.ja = "|10>の量子状態を作る" -------- Room 3 (Level I) q_command.areas.x_gates_3_wire = {} q_command.areas.x_gates_3_wire.region = q_command.regions.esc_rooms_level_1 table.insert(q_command.regions.esc_rooms_level_1, q_command.areas.x_gates_3_wire) q_command.areas.x_gates_3_wire.area_num = #q_command.regions.esc_rooms_level_1 q_command.areas.x_gates_3_wire.center_pos = {x = 248, y = 0, z = 62} q_command.areas.x_gates_3_wire.radius = 5 q_command.areas.x_gates_3_wire.q_block_pos = {x = 244, y = -1, z = 64} q_command.areas.x_gates_3_wire.door_pos = {x = 250, y = 0, z = 67} q_command.areas.x_gates_3_wire.portal_pos = {x = 253, y = 0, z = 61} q_command.areas.x_gates_3_wire.chest_pos = {x = 252, y = 0, z = 60} q_command.areas.x_gates_3_wire.chest_inv = { inventory = { main = {[1] = "", [2] = "", [3] = "", [4] = "", [5] = "", [6] = "", [7] = "", [8] = "", [9] = "", [10] = "", [11] = "", [12] = "", [13] = "", [14] = "", [15] = "", [16] = "", [17] = "", [18] = "", [19] = "", [20] = "", [21] = "", [22] = "", [23] = "", [24] = "", [25] = "circuit_blocks:circuit_blocks_x_gate", [26] = "", [27] = "", [28] = "", [29] = "", [30] = "", [31] = "", [32] = "" } } } q_command.areas.x_gates_3_wire.solution_statevector = {{r=0,i=0},{r=0,i=0},{r=0,i=0},{r=1,i=0},{r=0,i=0},{r=0,i=0},{r=0,i=0},{r=0,i=0}} q_command.areas.x_gates_3_wire.help_chat_msg = { "Here you'll do more of the same, but with one additional wire and twice the", "number of basis states." } q_command.areas.x_gates_3_wire.help_chat_msg.es = { "Aquí vas a hacer lo mismo, pero con una línea adicional y el doble de estados base." } q_command.areas.x_gates_3_wire.help_chat_msg.ja = { "ここでは、同じことを行いますが、線を1本追加し、基底状態の数を2倍にします。 " } q_command.areas.x_gates_3_wire.help_chat_sent = false q_command.areas.x_gates_3_wire.help_success_msg = { "You're catching on quickly! You're also noticing that there are 2 to the n power of", "basis states, where n is the number of wires. Here, there are 3 wires, so 8 basis", "states, |000> through |111>" } q_command.areas.x_gates_3_wire.help_success_msg.es = { "¡Lo pillas rápido! También te habrás dado cuenta de que el número de estados bae es 2", "elevado a la n potencia, donde n es el número de líneas. En este caso hay 3 líneas,", "luego 8 estados base, del |000> al |111>" } q_command.areas.x_gates_3_wire.help_success_msg.ja = { "すぐにできましたね! また、2のn乗個の基底状態があることに気づきましたね(nは線 ", "の数です)。 ここでは、3つの線があるため、|000>から|111> の8つの基底状態があり ", "ます。 " } q_command.areas.x_gates_3_wire.success_chat_sent = false q_command.areas.x_gates_3_wire.help_btn_text = {} q_command.areas.x_gates_3_wire.help_btn_text.en = [[ TLDR: Make the blue liquid levels correspond to a quantum state of |011> The exit door is behind the circuit, so use the ladder. ---- This circuit, consisting of three wires, demonstrates that one or more X gates may be leveraged to create a classical state. To work through this puzzle, take the following steps: 1) Notice that the blue liquid indicates there is a 100% probability that the result will be |000> when the circuit is measured. Go ahead and right-click the measurement block several times to verify that |000> is always the result. 2) Get an X block out of the chest. 3) While wielding the X block, position the cursor on the circuit wire corresponding to each |1> qubit in the desired measurement result, and right-click. Note that the bottom-most wire corresponds to the left-most qubit. 4) Notice that the blue liquid now indicates there is a 100% probability that the result will be |011> when the circuit is measured. Go ahead and right-click the measurement block several times to verify that |011> is always the result. If the Q block turned gold, congratulations on solving the puzzle! ]] q_command.areas.x_gates_3_wire.help_btn_text.es = q_command.areas.x_gates_3_wire.help_btn_text.en q_command.areas.x_gates_3_wire.help_btn_text.ja = [[ TLDR:青い液体レベルを量子状態|011>に対応させます。出口のドアは回路の後ろにあるの で、はしごを使用します。 ---- 3本のワイヤで構成されるこの回路は、1つ以上のXゲートを活用して古典的な状態を作成でき ることを示しています。このパズルを解くには、次の手順を実行します。 1)青い液体は、回路を測定したときに結果が|000>になる確率が100%であることを示してい ることに注意してください。測定ブロックを数回右クリックして、​​常に結果が|000>であること を確認します。 2)チェストからXブロックを取り出します。 3)Xブロックを使用しながら、目的の測定結果の各|1>の量子ビットに対応する回路の線に カーソルを置き、右クリックします。一番下の線が一番左の量子ビットに対応することに注意 してください。 4)青い液体が、回路の測定時に結果が|011>になる確率が100%であることを示していること に注意してください。測定ブロックを数回右クリックして、|011>が常に結果であることを確認 します。 Qブロックがゴールドになったら、パズルが解けたという意味です。おめでとうございます! ]] q_command.areas.x_gates_3_wire.help_btn_caption = {} q_command.areas.x_gates_3_wire.help_btn_caption.en = "Make quantum state of |011>" q_command.areas.x_gates_3_wire.help_btn_caption.es = q_command.areas.x_gates_3_wire.help_btn_caption.en q_command.areas.x_gates_3_wire.help_btn_caption.ja = "|011>の量子状態を作る" -------- Room 4 (Level I) q_command.areas.h_gate_escape = {} q_command.areas.h_gate_escape.region = q_command.regions.esc_rooms_level_1 table.insert(q_command.regions.esc_rooms_level_1, q_command.areas.h_gate_escape) q_command.areas.h_gate_escape.area_num = #q_command.regions.esc_rooms_level_1 q_command.areas.h_gate_escape.center_pos = {x = 248, y = 0, z = 72} q_command.areas.h_gate_escape.radius = 5 q_command.areas.h_gate_escape.q_block_pos = {x = 247, y = 0, z = 74} q_command.areas.h_gate_escape.door_pos = {x = 253, y = 0, z = 70} q_command.areas.h_gate_escape.portal_pos = {x = 253, y = 1, z = 72} q_command.areas.h_gate_escape.chest_pos = {x = 244, y = 0, z = 70} q_command.areas.h_gate_escape.chest_inv = { inventory = { main = {[1] = "", [2] = "", [3] = "", [4] = "", [5] = "", [6] = "", [7] = "", [8] = "", [9] = "", [10] = "", [11] = "", [12] = "", [13] = "", [14] = "", [15] = "", [16] = "", [17] = "", [18] = "", [19] = "", [20] = "", [21] = "", [22] = "", [23] = "", [24] = "", [25] = "", [26] = "", [27] = "", [28] = "", [29] = "", [30] = "circuit_blocks:circuit_blocks_h_gate", [31] = "", [32] = "" } } } q_command.areas.h_gate_escape.solution_statevector = {{r=0.707,i=0},{r=0.707,i=0}} q_command.areas.h_gate_escape.help_chat_msg = { "This room is where Schroedinger's cat starts getting nervous. Put the qubit in an equal", "superposition of dead and alive, I mean |0> and |1>" } q_command.areas.h_gate_escape.help_chat_msg.es = { "Esta es la habitación donde el gato de Schrodinger comienza a ponerse nervioso. Pon", "el cúbit en igual superposición de vivo y muerto. Quiero decir, de |0> y |1>" } q_command.areas.h_gate_escape.help_chat_msg.ja = { "この部屋はシュレーディンガーの猫が緊張しはじめる場所です。 量子ビットを死んで ", "いるか生きているかの、つまり|0>と|1>の均等な重ね合わせ状態に置きます。 " } q_command.areas.h_gate_escape.help_chat_sent = false q_command.areas.h_gate_escape.help_success_msg = { "You've put the qubit in the |+> (pronounced 'plus') state where it has an equal probability", "that measurements will result in |0> or |1>. You also made the marker on the Bloch sphere", "move to its equator, where the distances to the north pole |0> and the south pole |1>", "are equal. Fun fact: The probability of a |0> measurement result is proportional to", "the vertical (Z axis) distance of the qubit's state to the south pole on the Bloch sphere!" } q_command.areas.h_gate_escape.help_success_msg.es = { "Acabas de poner el cúbit en el estado |+> (pronunciado, “más”). También has hecho que la", "marca de la esfera de Bloch se mueva hacia el ecuador, donde las distancias al polo norte,", "|0>, y al polo sur, |1>, son iguales. Dato interesante: la probabilidad de medir |0> es", "proporcional a la distancia vertical (eje Z) del estado del cúbit al polo sur, en la", "esfera de Bloch." } q_command.areas.h_gate_escape.help_success_msg.ja = { "量子ビットを|+>(「プラス」と発音)状態、つまり、|0>または|1>が測定される確率が ", "等しい状態にしました。 また、ブロッホ球上のマーカーが赤道上に移動しました。赤 ", "道は、北極|0>と南極|1>までの距離が等しくなっています。 おもしろい事実:|0>が測 ", "定される確率は、ブロッホ球上の南極までの量子ビットの状態の垂直(Z軸上)の距離 ", "に比例します!" } q_command.areas.h_gate_escape.success_chat_sent = false q_command.areas.h_gate_escape.help_btn_text = {} q_command.areas.h_gate_escape.help_btn_text.en = [[ TLDR: Make the blue liquid levels correspond to a quantum state of sqrt(1/2) |0> + sqrt(1/2) |1>, which is commonly referred to as |+> ---- This circuit, consisting of only one wire, leverages the H gate, also known as the the Hadamard gate. Its effect on the |0> state is to put it into an equal superposition of |0> and |1>. Therefore, when the qubit is measured, there is a 50% probability that the result will be |0>, and a 50% probability that the result will be |1>. To work through this puzzle, take the following steps: 1) Notice that the blue liquid indicates there is a 100% probability that the result will be |0> when the circuit is measured. Go ahead and right-click the measurement block several times to verify that |0> is always the result. 2) Get an H block out of the chest. 3) While wielding the H block, position the cursor on the empty place on the circuit wire, and right-click. 4) Notice that the blue liquid now indicates there is a 50% probability that the result will be |0> when the circuit is measured, and a 50% probability that the result will be |1> when the circuit is measured. Go ahead and right-click the measurement block several times to verify that the results are fairly evenly distributed between |0> and |1>. If the Q block turned gold, congratulations on solving the puzzle! ]] q_command.areas.h_gate_escape.help_btn_text.es = q_command.areas.h_gate_escape.help_btn_text.en q_command.areas.h_gate_escape.help_btn_text.ja = [[ TLDR:青い液体レベルをsqrt(1/2)|0> + sqrt(1/2)|1>の量子状態に対応させます。これは 一般に|+>と呼ばれます ---- 1本の線のみで構成されるこの回路は、アダマールゲートとも呼ばれるHゲートを活用します。 Hは、|0>状態を|0>と|1>の等しい重ね合わせします。したがって、量子ビットを測定すると 50%の確率で結果が|0>になり、50%の確率で結果が|1>になります。このパズルを解くには、 次の手順を実行します。 1)青い液体は、回路を測定したときに結果が|0>になる確率が100%であることを示している ことに注意してください。測定ブロックを数回右クリックして、結果が常に|0>であることを確 認します。 2)チェストからHブロックを取り出します。 3)Hブロックを保持しながら、回路の線の空いている場所にカーソルを置き、右クリックしま す。 4)青色の液体は、回路の測定結果が|0>になる確率が50%であり、|1>となる確率が50%であ ることに注意してください。次に、測定ブロックを数回右クリックして、結果が|0>と|1>の間 でほぼ均等に分布していることを確認します。 Qブロックがゴールドになったら、パズルが解けたという意味です。おめでとうございます! ]] q_command.areas.h_gate_escape.help_btn_caption = {} q_command.areas.h_gate_escape.help_btn_caption.en = "Make a quantum state of |+>" q_command.areas.h_gate_escape.help_btn_caption.es = q_command.areas.h_gate_escape.help_btn_caption.en q_command.areas.h_gate_escape.help_btn_caption.ja = "|+>の量子状態を作る" -------- Room 5 (Level I) q_command.areas.h_x_gate = {} q_command.areas.h_x_gate.region = q_command.regions.esc_rooms_level_1 table.insert(q_command.regions.esc_rooms_level_1, q_command.areas.h_x_gate) q_command.areas.h_x_gate.area_num = #q_command.regions.esc_rooms_level_1 q_command.areas.h_x_gate.center_pos = {x = 258, y = 0, z = 72} q_command.areas.h_x_gate.radius = 5 q_command.areas.h_x_gate.q_block_pos = {x = 260, y = 0, z = 73} q_command.areas.h_x_gate.door_pos = {x = 256, y = 0, z = 67} q_command.areas.h_x_gate.portal_pos = {x = 263, y = 1, z = 72} q_command.areas.h_x_gate.chest_pos = {x = 256, y = 0, z = 76} q_command.areas.h_x_gate.chest_inv = { inventory = { main = {[1] = "", [2] = "", [3] = "", [4] = "", [5] = "", [6] = "", [7] = "", [8] = "", [9] = "", [10] = "", [11] = "", [12] = "", [13] = "", [14] = "", [15] = "", [16] = "", [17] = "", [18] = "", [19] = "", [20] = "", [21] = "", [22] = "", [23] = "", [24] = "", [25] = "circuit_blocks:circuit_blocks_x_gate", [26] = "", [27] = "", [28] = "", [29] = "", [30] = "circuit_blocks:circuit_blocks_h_gate", [31] = "", [32] = "" } } } q_command.areas.h_x_gate.solution_statevector = {{r=0.707,i=0},{r=-0.707,i=0}} q_command.areas.h_x_gate.help_chat_msg = { "Now let's visit the back side of the Bloch sphere, in a state commonly known as |->", "(pronounced 'minus'), where measurements resulting in |0> or |1> are also equally likely" } q_command.areas.h_x_gate.help_chat_msg.es = { "Visitemos ahora el otro lado de la esfera de Bloch, un estado conocido como |-> (pronunciado", "“menos”), donde las mediciones que resultan en |0> o |1> son igualmente probables." } q_command.areas.h_x_gate.help_chat_msg.ja = { "ここで、ブロッホ球の裏側を見てみましょう。一般に |->(「マイナス」と発音)と呼 ", "ばれる状態で、測定結果が同じように|0>または|1>になる可能性が等しい状態です。" } q_command.areas.h_x_gate.help_chat_sent = false q_command.areas.h_x_gate.help_success_msg = { "Nice navigation! You're noticing how the quantum computing gates such as X and Hadamard", "may be represented as rotations on the Bloch sphere. The X gate rotates 180 degrees, also", "known as pi (3.14...) radians, around the X axis (which is the axis coming toward you)", "but a bit down and to the left). You also may have noticed that the H gate rotates pi", "radians around an axis that is halfway in-between the X and Z axes." } q_command.areas.h_x_gate.help_success_msg.es = { "¡Bien dirigido! Te estarás percatando de cómo las puertas X y Hadamard se pueden", "representar como rotaciones en la esfera de Bloch. La puerta X rota 180 grados, o PI (3.14…) ", "radianes, la marca, alrededor del eje X (que es el eje que apunta hacia ti, aunque un", "poco más hacia abajo y a la izquierda). También habrás notado que la puerta H rota PI", "radianes la marca, alrededor de un eje que se encuentra a medio camino entre los ejes X y Z." } q_command.areas.h_x_gate.help_success_msg.ja = { "素晴らしいナビゲーションです! Xやアダマールなどの量子コンピューティングゲート ", "が、ブロッホ球上でどのような回転となるか分かっているようですね。XゲートはX軸 ", "(あなた側に向かっている軸・図では少し左下向きですが)を中心に180度(π(3.14 ...)", "ラジアン)回転とします。また、HゲートがX軸とZ軸の中間の軸を中心にπ回転す ", "ることも分かりましたね。" } q_command.areas.h_x_gate.success_chat_sent = false q_command.areas.h_x_gate.help_btn_text = {} q_command.areas.h_x_gate.help_btn_text.en = [[ TLDR: Make the blue liquid levels correspond to a quantum state of sqrt(1/2) |0> - sqrt(1/2) |1>, which is commonly referred to as |-> ---- This circuit, consisting of only one wire, demonstrates that the order of gates on a wire often matters. It also show that the basis states in a quantum state may have different phases. To work through this puzzle, take the following steps: 1) Notice that the blue liquid indicates there is a 100% probability that the result will be |0> when the circuit is measured. Go ahead and right-click the measurement block several times to verify that |0> is always the result. 2) Get an H block and an X block out of the chest, placing both on the circuit. 3) The solution will have probabilities indicating that measurement results |0> and |1> are equally likely, as well has having opposite phases. The notation for a phase on these block-world circuits is an arrow that points in a direction signifying its counterclockwise rotation, from 0 radians pointing rightward. As an example, a leftward pointing arrow signifies a phase of pi radians. 4) The blue liquid should indicate there is a 50% probability that the result will be |0> when the circuit is measured, and a 50% probability that the result will be |1> when the circuit is measured. Go ahead and right-click the measurement block several times to verify that the results are fairly evenly distributed between |0> and |1>. If the Q block turned gold, congratulations on solving the puzzle! ]] q_command.areas.h_x_gate.help_btn_text.es = q_command.areas.h_x_gate.help_btn_text.en q_command.areas.h_x_gate.help_btn_text.ja = [[ TLDR:青い液体レベルをsqrt(1/2)|0>-sqrt(1/2)|1>の量子状態に対応させます。これは一 般的に|->と呼ばれます ---- 1本の線のみで構成されるこの回路は、線上のゲートの順序が重要であることを示します。ま た、量子状態の基底状態は異なる位相を持つ可能性があることも示しています。このパズルを 解くには、次の手順を実行します。 1)青い液体は、回路を測定したときに結果が|0>になる確率が100%であることを示している ことに注意してください。測定ブロックを数回右クリックして、常に測定結果が |0>であるこ とを確認します。 2)チェストからHブロックとXブロックを取り出し、両方を回路に置きます。 3)解は、測定結果が|0>と|1>が等しく存在し、位相が逆である確率をもちます。ここのブロッ クワールドの回路上の位相の表記は、右向き矢印が0ラジアンで、そこから反時計回りの回転 です。例として、左向きの矢印は、πラジアンの位相を示します。 4)青い液体は、回路が測定されると結果が|0>になる確率が50%、|1>となる確率が50%であ ることを示している必要があります。測定ブロックを数回右クリックして、結果が|0>と|1>の 間でほぼ均等に分布していることを確認します。 Qブロックがゴールドになったら、パズルが解けたという意味です。おめでとうございます! ]] q_command.areas.h_x_gate.help_btn_caption = {} q_command.areas.h_x_gate.help_btn_caption.en = "Make a quantum state of |->" q_command.areas.h_x_gate.help_btn_caption.es = q_command.areas.h_x_gate.help_btn_caption.en q_command.areas.h_x_gate.help_btn_caption.ja = "|->の量子状態を作る" -------- Room 6 (Level I) q_command.areas.h_z_gate = {} q_command.areas.h_z_gate.region = q_command.regions.esc_rooms_level_1 table.insert(q_command.regions.esc_rooms_level_1, q_command.areas.h_z_gate) q_command.areas.h_z_gate.area_num = #q_command.regions.esc_rooms_level_1 q_command.areas.h_z_gate.center_pos = {x = 258, y = 0, z = 62} q_command.areas.h_z_gate.radius = 5 q_command.areas.h_z_gate.q_block_pos = {x = 259, y = 0, z = 60} q_command.areas.h_z_gate.door_pos = {x = 263, y = 0, z = 60} q_command.areas.h_z_gate.portal_pos = {x = 263, y = 1, z = 62} q_command.areas.h_z_gate.chest_pos = {x = 254, y = 0, z = 64} q_command.areas.h_z_gate.chest_inv = { inventory = { main = {[1] = "", [2] = "", [3] = "", [4] = "", [5] = "", [6] = "", [7] = "", [8] = "", [9] = "", [10] = "", [11] = "", [12] = "", [13] = "", [14] = "", [15] = "", [16] = "", [17] = "", [18] = "", [19] = "", [20] = "", [21] = "", [22] = "", [23] = "", [24] = "", [25] = "", [26] = "", [27] = "circuit_blocks:circuit_blocks_z_gate", [28] = "", [29] = "", [30] = "circuit_blocks:circuit_blocks_h_gate", [31] = "", [32] = "" } } } q_command.areas.h_z_gate.solution_statevector = {{r=0.707,i=0},{r=-0.707,i=0}} q_command.areas.h_z_gate.help_chat_msg = { "Let's take another trip to the |-> state, but this time via a different route. I've taken", "the liberty of replacing your X gate with a Z gate, so you'll need to experiment. Good luck!" } q_command.areas.h_z_gate.help_chat_msg.es = { "Vamos a alcanzar de nuevo el estado |->, esta vez siguiendo otra ruta. Me he tomado", "la libertad de reemplazar tu puerta X con una puerta Z, así que tendrás que experimentar", "un poco. ¡Buena suerte!" } q_command.areas.h_z_gate.help_chat_msg.ja = { "また別の|->状態に旅してみましょう。今回は別のルートを通ります。 私が、Xゲート ", "をZゲートに置き換えてみたので、あなたは実験する必要があります。 幸運を祈ってい ", "ます!" } q_command.areas.h_z_gate.help_chat_sent = false q_command.areas.h_z_gate.help_success_msg = { "Fascinating! You've demonstrated that there are several different ways (an infinite amount)", "for a quantum state to evolve to a different quantum state. This time, you used the H gate to", "move to the |+> state, and then you changed the phase of the quantum state by pi radians, using", "the Z gate to rotate around the Z axis. Did you notice that the arrows in the liquid blocks point", "in opposite directions (pi radians out of phase) when this one-qubit circuit is in the |-> state?" } q_command.areas.h_z_gate.help_success_msg.es = { "¡Fascinante! Acabas de demostrar que existen distintas formas (infinitas, de hecho) para que un estado", "cuántico evolucione hacia otro distinto. Esta vez, has usado una puerta H para alcanzar el estado |+>,", "y después has cambiado la fase del estado cuántico en PI radianes, usando la puerta Z para rotar alrededor", "del eje Z. ¿Te has dado cuenta de que las flechas de los bloques líquidos apuntan en direcciones", "opuestas (desfasadas PI radianes), cuando este circuito de un cúbit se encuentra en el estado |->?" } q_command.areas.h_z_gate.help_success_msg.ja = { "すばらしいです! あなたは、量子状態が異なる量子状態に進化するのに、いくつかの ", "異なる方法(無限の量)があることを実証しました。 今回は、Hゲートを使用して|+> ", "状態に移動し、Zゲートを使用してZ軸を中心に回転して、量子状態の位相をπ単位で変 ", "化させました。 この1量子ビットの回路が|->状態にあるとき、液体ブロックの矢印が ", "反対方向を指している(位相がπずれている)ことに気付きましたか?" } q_command.areas.h_z_gate.success_chat_sent = false q_command.areas.h_z_gate.help_btn_text = {} q_command.areas.h_z_gate.help_btn_text.en = [[ TLDR: Using a Z gate and one other gate, make the blue liquid levels correspond to a quantum state of sqrt(1/2) |0> - sqrt(1/2) |1>, which is commonly referred to as |-> ---- This circuit, consisting of only one wire, demonstrates how a block sphere models the state of a qubit. To work through this puzzle, take the following steps: 1) Notice that instead of the usual measurement block, this circuit has a (very pixelated) Bloch sphere. You can read more about this Bloch sphere in the building you started in when first playing this game. 2) Get an H block and a Z block out of the chest, placing them on the circuit. As you place each one, notice how the Bloch sphere changes, reflecting the updated state of the qubit. Try placing them in a different order, noticing the effects on the Bloch sphere and liquid blocks. 3) The solution will have probabilities indicating that measurement results |0> and |1> are equally likely, as well has having opposite phases. Note that both the Bloch sphere, and the blue liquid blocks, reflect these probabilities and phases. If the Q block turned gold, congratulations on solving the puzzle! ]] q_command.areas.h_z_gate.help_btn_text.es = q_command.areas.h_z_gate.help_btn_text.en q_command.areas.h_z_gate.help_btn_text.ja = [[ TLDR:Zゲートと他の1つのゲートを使用して、青い液体レベルをsqrt(1/2)|0>-sqrt(1/2)|1> の量子状態に対応させます。これは一般に|->と呼ばれます ---- 1本の線のみで構成されるこの回路は、ブロッホ球が量子ビットの状態をモデル化する方法を 示しています。このパズルを解くには、次の手順を実行します。 1)通常の測定ブロックの代わりに、この回路には(ピクセル化された)ブロッホ球がありま す。このゲームを初めてプレイしたときにいた建物で、このブロッホ球体について詳しく読む ことができます。 2)チェストからHブロックとZブロックを取り出し、回路に配置します。それぞれを配置する ときに、更新された量子ビットの状態を反映して、ブロッホ球がどのように変化するかに注目 してください。ブロッホ球と液体ブロックにどのように影響するか注目しながら、それらを異 なる順序で配置してみてください。 3)解は、測定結果|0>と|1>が等しい確率で存在し、逆の位相を持つことを示しています。ブ ロッホ球と青い液体ブロックの両方がこれらの確率と位相を反映していることに注目してくだ さい。 Qブロックがゴールドになったら、パズルが解けたという意味です。おめでとうございます! ]] q_command.areas.h_z_gate.help_btn_caption = {} q_command.areas.h_z_gate.help_btn_caption.en = "Make a quantum state of |-> using gates including Z" q_command.areas.h_z_gate.help_btn_caption.es = q_command.areas.h_z_gate.help_btn_caption.en q_command.areas.h_z_gate.help_btn_caption.ja = "Zを含むゲートを使用して|->の量子状態を作る" -------- Room 7 (Level I) q_command.areas.hxx_gates_escape = {} q_command.areas.hxx_gates_escape.region = q_command.regions.esc_rooms_level_1 table.insert(q_command.regions.esc_rooms_level_1, q_command.areas.hxx_gates_escape) q_command.areas.hxx_gates_escape.area_num = #q_command.regions.esc_rooms_level_1 q_command.areas.hxx_gates_escape.center_pos = {x = 268, y = 0, z = 62} q_command.areas.hxx_gates_escape.radius = 5 q_command.areas.hxx_gates_escape.q_block_pos = {x = 271, y = -1, z = 66} q_command.areas.hxx_gates_escape.door_pos = {x = 266, y = 0, z = 67} q_command.areas.hxx_gates_escape.portal_pos = {x = 268, y = 1, z = 67} q_command.areas.hxx_gates_escape.chest_pos = {x = 266, y = 0, z = 58} q_command.areas.hxx_gates_escape.chest_inv = { inventory = { main = {[1] = "", [2] = "", [3] = "", [4] = "", [5] = "", [6] = "", [7] = "", [8] = "", [9] = "", [10] = "", [11] = "", [12] = "", [13] = "", [14] = "", [15] = "", [16] = "", [17] = "", [18] = "", [19] = "", [20] = "", [21] = "", [22] = "", [23] = "", [24] = "", [25] = "circuit_blocks:circuit_blocks_x_gate", [26] = "", [27] = "", [28] = "", [29] = "", [30] = "circuit_blocks:circuit_blocks_h_gate", [31] = "", [32] = "" } } } q_command.areas.hxx_gates_escape.solution_statevector = {{r=0,i=0},{r=0.707,i=0},{r=0,i=0},{r=0,i=0},{r=0,i=0},{r=0.707,i=0},{r=0,i=0},{r=0,i=0}} q_command.areas.hxx_gates_escape.help_chat_msg = { "Go ahead and solve this puzzle by thinking about one wire at a time" } q_command.areas.hxx_gates_escape.help_chat_msg.es = { "Continua y resuelve este puzzle línea por línea." } q_command.areas.hxx_gates_escape.help_chat_msg.ja = { "一度に1本の線について考えることで、このパズルを解いてください。" } q_command.areas.hxx_gates_escape.help_chat_sent = false q_command.areas.hxx_gates_escape.help_success_msg = { "You're really getting the hang of this! By thinking about the effects of various gates on", "individual wires, you've successfully crafted the desired composite quantum state." } q_command.areas.hxx_gates_escape.help_success_msg.es = { "¡Le vas cogiendo el truco! Pensando en el efecto de múltiples puertas en líneas individuales,", "has conseguido crear el estado cuántico deseado." } q_command.areas.hxx_gates_escape.help_success_msg.ja = { "あなたは本当にコツが分かっていますね! 個々の線に対するさまざまなゲートの影響 ", "を考えることで、目的の複合量子状態を作成できました。" } q_command.areas.hxx_gates_escape.success_chat_sent = false q_command.areas.hxx_gates_escape.help_btn_text = {} q_command.areas.hxx_gates_escape.help_btn_text.en = [[ TLDR: Make the blue liquid levels correspond to a quantum state of sqrt(1/2) |001> + sqrt(1/2) |101> ---- This circuit leverages Hadamard and X gates to create a quantum state in which the measurement results |001> and |101> are equally likely, and no other measurement results are possible. This quantum state could be expressed as |001> + |101> To solve this circuit puzzle, place an H gate and an X gate on the appropriate wires. Hint: Use what you already have learned about the behaviors of H and X gates on single-wire circuits. If the Q block turned gold, congratulations on solving the puzzle! ]] q_command.areas.hxx_gates_escape.help_btn_text.es = q_command.areas.hxx_gates_escape.help_btn_text.en q_command.areas.hxx_gates_escape.help_btn_text.ja = [[ TLDR:HおよびXゲートのみを使用して、青い液体レベルをsqrt(1/2)|001> + sqrt(1/2)|101>の量子状態に対応させます。 ---- この回路は、アダマールゲートとXゲートを活用して、測定結果が|001>または|101>に なる可能性が等しく、その他の測定結果が得られない量子状態を作成します。 この量 子状態は、|001> + |101>と表現できます。 この回路パズルを解決するには、適切な線にHゲートとXゲートを配置します。 ヒント:単線回路でのHゲートおよびXゲートの動作について既に学んだことを使用し てください。 Qブロックがゴールドになったら、パズルが解けたという意味です。おめでとうござい ます! ]] q_command.areas.hxx_gates_escape.help_btn_caption = {} q_command.areas.hxx_gates_escape.help_btn_caption.en = "Make |001> + |101> quantum state" q_command.areas.hxx_gates_escape.help_btn_caption.es = q_command.areas.hxx_gates_escape.help_btn_caption.en q_command.areas.hxx_gates_escape.help_btn_caption.ja = "|001> + |101> の量子状態を作る" -------- Room 8 (Level I) q_command.areas.equal_super_2wire_escape = {} q_command.areas.equal_super_2wire_escape.region = q_command.regions.esc_rooms_level_1 table.insert(q_command.regions.esc_rooms_level_1, q_command.areas.equal_super_2wire_escape) q_command.areas.equal_super_2wire_escape.area_num = #q_command.regions.esc_rooms_level_1 q_command.areas.equal_super_2wire_escape.center_pos = {x = 268, y = 0, z = 72} q_command.areas.equal_super_2wire_escape.radius = 5 q_command.areas.equal_super_2wire_escape.q_block_pos = {x = 266, y = 0, z = 75} q_command.areas.equal_super_2wire_escape.door_pos = {x = 270, y = 0, z = 77} q_command.areas.equal_super_2wire_escape.portal_pos = {x = 273, y = 1, z = 72} q_command.areas.equal_super_2wire_escape.chest_pos = {x = 264, y = 0, z = 70} q_command.areas.equal_super_2wire_escape.chest_inv = { inventory = { main = {[1] = "", [2] = "", [3] = "", [4] = "", [5] = "", [6] = "", [7] = "", [8] = "", [9] = "", [10] = "", [11] = "", [12] = "", [13] = "", [14] = "", [15] = "", [16] = "", [17] = "", [18] = "", [19] = "", [20] = "", [21] = "", [22] = "", [23] = "", [24] = "", [25] = "", [26] = "", [27] = "", [28] = "", [29] = "", [30] = "circuit_blocks:circuit_blocks_h_gate", [31] = "", [32] = "" } } } q_command.areas.equal_super_2wire_escape.solution_statevector = {{r=0.5,i=0},{r=0.5,i=0},{r=0.5,i=0},{r=0.5,i=0}} q_command.areas.equal_super_2wire_escape.help_chat_msg = { "Now put four basis states into equal superpositions" } q_command.areas.equal_super_2wire_escape.help_chat_msg.es = { "Ahora pon los cuatro estados base en igual superposición." } q_command.areas.equal_super_2wire_escape.help_chat_msg.ja = { "今度は、4つの基底状態を均等な重ね合わせ状態にします。" } q_command.areas.equal_super_2wire_escape.help_chat_sent = false q_command.areas.equal_super_2wire_escape.help_success_msg = { "Incredible! By putting each wire into a superposition, you've caused all four of the", "basis states in this quantum state to be in equal superpositions. As indicated by the", "formula on the wall, each state has a 1/4 probability of being the result when measured.", "Note that the measurement probability of a given basis state is the square of its", "coefficient (referred to by physicists as its amplitude)" } q_command.areas.equal_super_2wire_escape.help_success_msg.es = { "¡Increíble! Poniendo cada línea en superposición, has hecho que los cuatro estados base de", "este estado cuántico estén en igual superposición. Como indica la fórmula en la pared, cada", "estado tiene una probabilidad de ¼ de ser el resultado, tras una medición. Fíjate que la", "probabilidad de medición de un estado base cualquiera es el cuadrado de su coeficiente", "(llamado “amplitud”, por los físicos)." } q_command.areas.equal_super_2wire_escape.help_success_msg.ja = { "信じられません! 各線をそれぞれ重ね合わせにすることで、この量子状態の4つの基底 ", "状態が均等な重ね合わせ状態になります。 壁の式に示されているように、各状態は、 ", "測定される確率が1/4ずつあります。 与えられた基底状態の測定される確率は、その係 ", "数(物理学者は振幅と呼びます)の2乗であることに注意してください。" } q_command.areas.equal_super_2wire_escape.success_chat_sent = false q_command.areas.equal_super_2wire_escape.help_btn_text = {} q_command.areas.equal_super_2wire_escape.help_btn_text.en = [[ TLDR: Make the blue liquid levels correspond to the following quantum state, commonly referred to as an equal superposition: sqrt(1/4) |00> + sqrt(1/4) |01> + sqrt(1/4) |10> + sqrt(1/4) |11> ---- This circuit leverages two Hadamard gates to create an equal superposition of |00>, |01>, |10>, and |11>. To solve this circuit puzzle, place an H block on each wire. Notice how the outcome probabilities and measurement results change as these gates are removed and added. This pattern of placing an H gate on each wire of a circuit is commonly used to create a superposition consisting of 2^numQubits states. If the Q block turned gold, congratulations on solving the puzzle! ]] q_command.areas.equal_super_2wire_escape.help_btn_text.es = q_command.areas.equal_super_2wire_escape.help_btn_text.en q_command.areas.equal_super_2wire_escape.help_btn_text.ja = [[ TLDR:青色の液体レベルを一般に、均等な重ね合わせと呼ばれる次の量子状態に対応させま す:sqrt(1/4)|00> + sqrt(1/4)|01> + sqrt(1/4)|10>+ SQRT(1/4)|11> ---- この回路は、2つのアダマールゲートを活用して、|00>、|01>、|10>、および|11>の均等な重ね 合わせを作成します。 この回路パズルを解くには、各線上にHブロックを配置します。 これら のHゲートが削除または追加されたとき、結果の確率と測定結果がどのように変化するかに注 目してみてください。 回路の各ワイヤにHゲートを配置するこのパターンは、2 ^ 量子ビット 数 の状態の重ね合わせを作るために一般に使用されます。 Qブロックがゴールドになったら、パズルが解けたという意味です。おめでとうござい ます! ]] q_command.areas.equal_super_2wire_escape.help_btn_caption = {} q_command.areas.equal_super_2wire_escape.help_btn_caption.en = "Equal superposition with two qubits" q_command.areas.equal_super_2wire_escape.help_btn_caption.es = q_command.areas.equal_super_2wire_escape.help_btn_caption.en q_command.areas.equal_super_2wire_escape.help_btn_caption.ja = "2量子ビットの均等な重ね合わせ" -------- Room 9 (Level I) q_command.areas.equal_super_3wire_escape = {} q_command.areas.equal_super_3wire_escape.region = q_command.regions.esc_rooms_level_1 table.insert(q_command.regions.esc_rooms_level_1, q_command.areas.equal_super_3wire_escape) q_command.areas.equal_super_3wire_escape.area_num = #q_command.regions.esc_rooms_level_1 q_command.areas.equal_super_3wire_escape.center_pos = {x = 268, y = 0, z = 82} q_command.areas.equal_super_3wire_escape.radius = 5 q_command.areas.equal_super_3wire_escape.q_block_pos = {x = 264, y = -1, z = 78} q_command.areas.equal_super_3wire_escape.door_pos = {x = 270, y = 0, z = 87} q_command.areas.equal_super_3wire_escape.portal_pos = {x = 273, y = 1, z = 82} q_command.areas.equal_super_3wire_escape.chest_pos = {x = 272, y = 0, z = 80} q_command.areas.equal_super_3wire_escape.chest_inv = { inventory = { main = {[1] = "", [2] = "", [3] = "", [4] = "", [5] = "", [6] = "", [7] = "", [8] = "", [9] = "", [10] = "", [11] = "", [12] = "", [13] = "", [14] = "", [15] = "", [16] = "", [17] = "", [18] = "", [19] = "", [20] = "", [21] = "", [22] = "", [23] = "", [24] = "", [25] = "", [26] = "", [27] = "", [28] = "", [29] = "", [30] = "circuit_blocks:circuit_blocks_h_gate", [31] = "", [32] = "" } } } q_command.areas.equal_super_3wire_escape.solution_statevector = {{r=0.354,i=0},{r=0.354,i=0},{r=0.354,i=0},{r=0.354,i=0},{r=0.354,i=0},{r=0.354,i=0},{r=0.354,i=0},{r=0.354,i=0}} q_command.areas.equal_super_3wire_escape.help_chat_msg = { "This time, put eight basis states into equal superpositions" } q_command.areas.equal_super_3wire_escape.help_chat_msg.es = { "Esta vez, pon ocho estados base en igual superposición." } q_command.areas.equal_super_3wire_escape.help_chat_msg.ja = { "今度は、8つの基底状態を均等な重ね合わせ状態にします。" } q_command.areas.equal_super_3wire_escape.help_chat_sent = false q_command.areas.equal_super_3wire_escape.help_success_msg = { "You've got this! You may be familiar with the 'sum' notation on the wall, which", "provides a succinct way to express this state in which all of the basis states have", "the same amplitude." } q_command.areas.equal_super_3wire_escape.help_success_msg.es = { "¡Ya lo has pillado! Puede que te suene la notación “sumatorio” de la pared, que proporciona", "una forma breve de expresar este estado en el que todos los estados base tienen la misma", "amplitud." } q_command.areas.equal_super_3wire_escape.help_success_msg.ja = { "やりましたね! 壁の「和」の表記をよく知っているかもしれません。これは、すべて ", "の基底状態が同じ振幅を持つ、この状態を簡単に表現する方法です。" } q_command.areas.equal_super_3wire_escape.success_chat_sent = false q_command.areas.equal_super_3wire_escape.help_btn_text = {} q_command.areas.equal_super_3wire_escape.help_btn_text.en = [[ TLDR: Make the blue liquid levels correspond to an equal superposition of its eight basis states. ---- This circuit leverages two Hadamard gates to create an equal superposition of |000>, |001>, |010>, |011>, |100>, |101>, |110> and |111>. A convenient way to express this state is to use the math sum symbol as shown on the wall. To solve this circuit puzzle, place an H block on each wire. Notice how the outcome probabilities and measurement results change as these gates are removed and added. This pattern of placing an H gate on each wire of a circuit is commonly used to create a superposition consisting of 2^numQubits states. If the Q block turned gold, congratulations on solving the puzzle! ]] q_command.areas.equal_super_3wire_escape.help_btn_text.es = q_command.areas.equal_super_3wire_escape.help_btn_text.en q_command.areas.equal_super_3wire_escape.help_btn_text.ja = [[ この回路は、2つのアダマールゲートを活用して、|000>、|001>、|010>、|011>、|100>、 |101>、|110>および|111>の等しい重ね合わせを作成します。 この状態を表現する便利な方法 は、壁に示されているように数学和記号を使用することです。 この回路パズルを解決するに は、各ワイヤにHブロックを配置します。 これらのゲートが削除および追加されると、結果の 確率と測定結果がどのように変化するかに注目してください。 回路の各線にHゲートを配置す るこのパターンは、2 ^ (量子ビット数)個の状態で構成される重ね合わせを作成するために 一般的に使用されます。 Qブロックがゴールドになったら、パズルが解けたという意味です。おめでとうございます! ]] q_command.areas.equal_super_3wire_escape.help_btn_caption = {} q_command.areas.equal_super_3wire_escape.help_btn_caption.en = "Equal superposition with three qubits" q_command.areas.equal_super_3wire_escape.help_btn_caption.es = q_command.areas.equal_super_3wire_escape.help_btn_caption.en q_command.areas.equal_super_3wire_escape.help_btn_caption.ja = "3量子ビットの均等な重ね合わせ" -------- Room 10 (Level I) q_command.areas.bell_phi_plus_escape = {} q_command.areas.bell_phi_plus_escape.region = q_command.regions.esc_rooms_level_1 table.insert(q_command.regions.esc_rooms_level_1, q_command.areas.bell_phi_plus_escape) q_command.areas.bell_phi_plus_escape.area_num = #q_command.regions.esc_rooms_level_1 q_command.areas.bell_phi_plus_escape.center_pos = {x = 268, y = 0, z = 92} q_command.areas.bell_phi_plus_escape.radius = 5 q_command.areas.bell_phi_plus_escape.q_block_pos = {x = 266, y = 0, z = 94} q_command.areas.bell_phi_plus_escape.door_pos = {x = 263, y = 0, z = 94} q_command.areas.bell_phi_plus_escape.portal_pos = {x = 273, y = 1, z = 92} q_command.areas.bell_phi_plus_escape.chest_pos = {x = 272, y = 0, z = 90} q_command.areas.bell_phi_plus_escape.chest_inv = { inventory = { main = {[1] = "", [2] = "", [3] = "", [4] = "", [5] = "", [6] = "", [7] = "", [8] = "", [9] = "", [10] = "", [11] = "", [12] = "", [13] = "", [14] = "", [15] = "", [16] = "", [17] = "", [18] = "", [19] = "", [20] = "", [21] = "", [22] = "", [23] = "", [24] = "", [25] = "circuit_blocks:circuit_blocks_x_gate", [26] = "", [27] = "", [28] = "", [29] = "", [30] = "circuit_blocks:circuit_blocks_h_gate", [31] = "circuit_blocks:control_tool", [32] = "" } } } q_command.areas.bell_phi_plus_escape.solution_statevector = {{r=0.707,i=0},{r=0,i=0},{r=0,i=0},{r=0.707,i=0}} q_command.areas.bell_phi_plus_escape.help_chat_msg = { "Now we'll experiment with a phenomenon known as 'quantum entanglement' that Einstein", "referred to as 'spooky actions at a distance'. Your challenge is to entangle two", "qubits so that each one will have the same measurement result. Hint: You'll click the", "X gate while wielding the Control Tool to turn in into a CNOT gate." } q_command.areas.bell_phi_plus_escape.help_chat_msg.es = { "Ahora vamos a experimentar con un fenómeno llamado “entrelazamiento cuántico”, y al que", "Einstein se refería como “acciones espeluznantes a distancia”. El reto consiste en entrelazar", "dos cubits de tal forma que se obtenga la misma medida para ambos. Pista: sostén la", "Herramienta Control y haz clic en la puerta X para convertirla en una puerta CNOT." } q_command.areas.bell_phi_plus_escape.help_chat_msg.ja = { "次に、アインシュタインが「不気味な遠隔作用」とよんだ「量子もつれ」の現象を実験 ", "します。 あなたの課題は、それぞれが同じ測定結果を持つように、2つの量子ビットを ", "エンタングルすることです。 ヒント:コントロールツールを使用してXゲートをクリッ ", "クすると、CNOTゲートに変わります。" } q_command.areas.bell_phi_plus_escape.help_chat_sent = false q_command.areas.bell_phi_plus_escape.help_success_msg = { "Amazing! You've just entangled two qubits in one of the four Bell states. This one is", "known as the 'phi +' state. Did you notice that the Bloch spheres have question marks", "in them? That's because an entangled state can't be expressed in terms of the states of", "its qubits." } q_command.areas.bell_phi_plus_escape.help_success_msg.es = { "¡Impresionante! Acabas de entrelazar dos cubits en uno de los cuatro estados de Bell. Este se", "conoce con el nombre de estado “phi +”. ¿Te has dado cuenta de que la esfera de Bloch", "muestra símbolos de interrogación en ella? Esto se debe a que un estado entrelazado no", "puede exprese en términos de los estados de sus cúbits." } q_command.areas.bell_phi_plus_escape.help_success_msg.ja = { "すごいです! 4つのベル状態のうちの1つである、2つの量子ビットがもつれた状態になりまし ", "た。 これは「Φ+」状態として知られています。 ブロッホ球に?マークがついていることに気 ", "づきましたか? エンタングルメント状態は、一つの量子ビットの状態で表せないからです。" } q_command.areas.bell_phi_plus_escape.success_chat_sent = false q_command.areas.bell_phi_plus_escape.help_btn_text = {} q_command.areas.bell_phi_plus_escape.help_btn_text.en = [[ TLDR: Make the blue liquid levels correspond to a quantum state of sqrt(1/2) |00> + sqrt(1/2) |11> which is referred to as the phi+ Bell state. ---- The four simplest examples of quantum entanglement are the Bell states. The most well-known Bell state, symbolized by phi+, may be realized with a Hadamard gate and a CNOT gate. The CNOT gate is a two-wire gate that has the appearance of cross-hairs and a vertical line with a dot. The cross-hairs symbol has the functionality of the X gate, with the difference being that it is conditional on the state of the other wire, performing the NOT operation whenever the other wire is |1>. Measuring one of the qubits results in the measured state of the other qubit to be determined. A correct phi+ Bell state solution will have probabilities indicating that measurement results |00> and |11> are equally likely, as well has having identical phases. The notation for a phase on these block-world circuits is an arrow that points in a direction signifying its counterclockwise rotation, from 0 radians pointing rightward. One way to realize this state is to place a Hadamard gate on the top wire, and an X gate on the second wire in a column to the right of the Hadamard gate. Then select the control tool from the hotbar (after having retrieved it from the chest). While positioning the cursor on the X gate in the circuit, left-click until the control qubit is on the same wire as the Hadamard gate. If the Q block turned gold, congratulations on solving the puzzle! ]] q_command.areas.bell_phi_plus_escape.help_btn_text.es = q_command.areas.bell_phi_plus_escape.help_btn_text.en q_command.areas.bell_phi_plus_escape.help_btn_text.ja = [[ TLDR:青い液体レベルを、phi +ベル状態と呼ばれるsqrt(1/2)|00> + sqrt(1/2)|11>の量子 状態に対応させます。 ---- 量子エンタングルメントの最もシンプルな4つの例は、ベル状態です。Φ+に象徴される最も有 名なベル状態は、アダマールゲートとCNOTゲートで実現できます。 CNOTゲートは、十字線 と点のある垂直線の外観を持つ2線式のゲートです。十字記号にはXゲートの機能があります が、違いはもう一方の線の状態を条件とし、その線が|1>である場合は常にNOT演算を実行する ことです。 片方の量子ビットを測定すると、もう一方の量子ビットの測定状態が決定されます。正しいΦ+ のベル状態の解には、|00>と|11>の測定される確率が等しく、同じ位相になります。ここのブ ロックワールドの回路上の位相の表記は、右向き矢印が 0ラジアンで、そこから反時計回りの 回転です。 この状態を実現する1つの方法は、上の線にアダマールゲートを配置し、アダマールゲートの 右の列の上から2番目の線にXゲートを配置し、ホットバーからコントロールツールを選択 (チェストから取得した後)します。 回路内のXゲートにカーソルを置きながら、制御量子ビッ トがアダマールゲートと同じ線上にくるまで左クリックします。 Qブロックがゴールドになったら、パズルが解けたという意味です。おめでとうございます! ]] q_command.areas.bell_phi_plus_escape.help_btn_caption = {} q_command.areas.bell_phi_plus_escape.help_btn_caption.en = "Make the phi+ Bell state" q_command.areas.bell_phi_plus_escape.help_btn_caption.es = q_command.areas.bell_phi_plus_escape.help_btn_caption.en q_command.areas.bell_phi_plus_escape.help_btn_caption.ja = "Φ+ のベル状態を作る" -------- Room 11 (Level I) q_command.areas.bell_phi_minus_escape = {} q_command.areas.bell_phi_minus_escape.region = q_command.regions.esc_rooms_level_1 table.insert(q_command.regions.esc_rooms_level_1, q_command.areas.bell_phi_minus_escape) q_command.areas.bell_phi_minus_escape.area_num = #q_command.regions.esc_rooms_level_1 q_command.areas.bell_phi_minus_escape.center_pos = {x = 258, y = 0, z = 92} q_command.areas.bell_phi_minus_escape.radius = 5 q_command.areas.bell_phi_minus_escape.q_block_pos = {x = 256, y = 0, z = 90} q_command.areas.bell_phi_minus_escape.door_pos = {x = 256, y = 0, z = 87} q_command.areas.bell_phi_minus_escape.portal_pos = {x = 263, y = 1, z = 92} q_command.areas.bell_phi_minus_escape.chest_pos = {x = 260, y = 0, z = 96} q_command.areas.bell_phi_minus_escape.chest_inv = { inventory = { main = {[1] = "", [2] = "", [3] = "", [4] = "", [5] = "", [6] = "", [7] = "", [8] = "", [9] = "", [10] = "", [11] = "", [12] = "", [13] = "", [14] = "", [15] = "", [16] = "", [17] = "", [18] = "", [19] = "", [20] = "", [21] = "", [22] = "", [23] = "", [24] = "", [25] = "circuit_blocks:circuit_blocks_x_gate", [26] = "", [27] = "", [28] = "", [29] = "", [30] = "circuit_blocks:circuit_blocks_h_gate", [31] = "circuit_blocks:control_tool", [32] = "" } } } q_command.areas.bell_phi_minus_escape.solution_statevector = {{r=0.707,i=0},{r=0,i=0},{r=0,i=0},{r=-0.707,i=0}} q_command.areas.bell_phi_minus_escape.help_chat_msg = { "Now entangle two qubits in another way, known as the 'phi -' Bell state." } q_command.areas.bell_phi_minus_escape.help_chat_msg.es = { "Ahora entrelaza dos cúbits de otra manera, conocida como el estado de Bell “phi -“." } q_command.areas.bell_phi_minus_escape.help_chat_msg.ja = { "さあ、「Φ-」のベル状態として知られる、別の方法で2つの量子ビットをエンタングル ", "さえましょう。" } q_command.areas.bell_phi_minus_escape.help_chat_sent = false q_command.areas.bell_phi_minus_escape.help_success_msg = { "Congratulations! You entangled those qubits in such a way that the measurement results", "are the same as the previous, 'phi +', Bell state. But did you notice that the phases", "in the relevant basis states are pi radians out of phase?" } q_command.areas.bell_phi_minus_escape.help_success_msg.es = { "¡Enhorabuena! Has entrelazado esos cúbits de forma que los resultados medidos son los", "mismos que en el estado anterior, “phi +”. ¿Pero te has dado cuenta de que las fases de los", "estados se encuentran desfasadas PI radianes?" } q_command.areas.bell_phi_minus_escape.help_success_msg.ja = { "おめでとうございます! 前の「Φ+」のベル状態と同じ測定結果になるように、量子 ", "ビットをエンタングルさせることができました。 ただし、基底状態の位相がπずれてい ", "ることに気づきましたか?" } q_command.areas.bell_phi_minus_escape.success_chat_sent = false q_command.areas.bell_phi_minus_escape.help_btn_text = {} q_command.areas.bell_phi_minus_escape.help_btn_text.en = [[ TLDR: Make the blue liquid levels correspond to a quantum state of sqrt(1/2) |00> - sqrt(1/2) |11> which is referred to as the phi- Bell state. ---- The four simplest examples of quantum entanglement are the Bell states. One of these Bell states, symbolized by phi- (phi minus), may be realized by placing an X gate on the top wire, and adding the phi+ Bell state circuit (as instructed in another puzzle) to the right of the X gate. Measuring one of the qubits results in the measured state of the other qubit to be determined. A correct phi- Bell state solution will have probabilities indicating that measurement results |00> and |11> are equally likely, as well has having opposite phases. The notation for a phase on these block-world circuits is an arrow that points in a direction signifying its counterclockwise rotation, from 0 radians pointing rightward. As an example, a leftward pointing arrow signifies a phase of pi radians. If the Q block turned gold, congratulations on solving the puzzle! ]] q_command.areas.bell_phi_minus_escape.help_btn_text.es = q_command.areas.bell_phi_minus_escape.help_btn_text.en q_command.areas.bell_phi_minus_escape.help_btn_text.ja = [[ TLDR:青い液体レベルを、sqrt(1/2)|00>-sqrt(1/2)|11>の量子状態に対応させます。これ は、Φ-のベル状態と呼ばれます。 ---- 量子エンタングルメントの最もシンプルな4つの例は、ベル状態です。これらのベル状態の1つ は、Φ-(phi -)と呼ばれXゲートを上の線に配置し、Xゲートの右側にΦ+ のベル状態回路(別 のパズルで示しました)を追加することで実現できます。 片方の量子ビットを測定すると、もう一方の量子ビットの測定状態が決定されます。正しいΦ- のベル状態の解は、|00>と|11>の測定される確率が等しく、位相が逆です。ここのブロック ワールドの回路上の位相の表記は、右向き矢印が 0ラジアンで、そこから反時計回りの回転で す。例として、左向きの矢印は、πラジアンの位相を示します。 Qブロックがゴールドになったら、パズルが解けたという意味です。おめでとうございます! ]] q_command.areas.bell_phi_minus_escape.help_btn_caption = {} q_command.areas.bell_phi_minus_escape.help_btn_caption.en = "Make the phi- Bell state" q_command.areas.bell_phi_minus_escape.help_btn_caption.es = q_command.areas.bell_phi_minus_escape.help_btn_caption.en q_command.areas.bell_phi_minus_escape.help_btn_caption.ja = "Φ- のベル状態を作る" -------- Room 12 (Level I) q_command.areas.bell_psi_plus_escape = {} q_command.areas.bell_psi_plus_escape.region = q_command.regions.esc_rooms_level_1 table.insert(q_command.regions.esc_rooms_level_1, q_command.areas.bell_psi_plus_escape) q_command.areas.bell_psi_plus_escape.area_num = #q_command.regions.esc_rooms_level_1 q_command.areas.bell_psi_plus_escape.center_pos = {x = 258, y = 0, z = 82} q_command.areas.bell_psi_plus_escape.radius = 5 q_command.areas.bell_psi_plus_escape.q_block_pos = {x = 260, y = 0, z = 80} q_command.areas.bell_psi_plus_escape.door_pos = {x = 253, y = 0, z = 80} q_command.areas.bell_psi_plus_escape.portal_pos = {x = 263, y = 1, z = 82} q_command.areas.bell_psi_plus_escape.chest_pos = {x = 254, y = 0, z = 84} q_command.areas.bell_psi_plus_escape.chest_inv = { inventory = { main = {[1] = "", [2] = "", [3] = "", [4] = "", [5] = "", [6] = "", [7] = "", [8] = "", [9] = "", [10] = "", [11] = "", [12] = "", [13] = "", [14] = "", [15] = "", [16] = "", [17] = "", [18] = "", [19] = "", [20] = "", [21] = "", [22] = "", [23] = "", [24] = "", [25] = "circuit_blocks:circuit_blocks_x_gate", [26] = "", [27] = "", [28] = "", [29] = "", [30] = "circuit_blocks:circuit_blocks_h_gate", [31] = "circuit_blocks:control_tool", [32] = "" } } } q_command.areas.bell_psi_plus_escape.solution_statevector = {{r=0,i=0},{r=0.707,i=0},{r=0.707,i=0},{r=0,i=0}} q_command.areas.bell_psi_plus_escape.help_chat_msg = { "Go ahead and entangle the two qubits in yet another way, this time in which the", "measurement result of one qubit is the opposite result of measuring the other qubit." } q_command.areas.bell_psi_plus_escape.help_chat_msg.es = { "Continua y entrelaza ambos cúbits de otra forma más, esta vez en una en la que el resultado", "de un cúbit sea siempre opuesto al resultado del otro." } q_command.areas.bell_psi_plus_escape.help_chat_msg.ja = { "先に進み、2つの量子ビットをさらに別の方法でエンタングルさせます。今回は、一つ ", "の量子ビットの測定結果が、もう一つの量子ビットの測定結果の逆になります。" } q_command.areas.bell_psi_plus_escape.help_chat_sent = false q_command.areas.bell_psi_plus_escape.help_success_msg = { "Well done! The state you made is known as the 'psi +', Bell state." } q_command.areas.bell_psi_plus_escape.help_success_msg.es = { "¡Bien hecho! Este estado se conoce como el estado de Bell “psi +”." } q_command.areas.bell_psi_plus_escape.help_success_msg.ja = { "よくできました! あなたが作った状態は、「Ψ+」のベル状態として知られています。" } q_command.areas.bell_psi_plus_escape.success_chat_sent = false q_command.areas.bell_psi_plus_escape.help_btn_text = {} q_command.areas.bell_psi_plus_escape.help_btn_text.en = [[ TLDR: Make the blue liquid levels correspond to a quantum state of sqrt(1/2) |01> + sqrt(1/2) |10> which is referred to as the psi+ Bell state. ---- The four simplest examples of quantum entanglement are the Bell states. One of these Bell states, symbolized by psi+ (psi plus), may be realized by placing an X gate on the second wire, and adding the phi+ Bell state circuit (as instructed in another puzzle) to the right of the X gate, Measuring one of the qubits results in the measured state of the other qubit to be determined. A correct psi+ Bell state solution will have probabilities indicating that measurement results |01> and |10> are equally likely, as well has having identical phases. The notation for a phase on these block-world circuits is an arrow that points in a direction signifying its counterclockwise rotation, from 0 radians pointing rightward. The psi+ Bell state is known as one of the singlet states, where measuring one of the qubits determines that the other qubit will be measured as the opposite state. If the Q block turned gold, congratulations on solving the puzzle! ]] q_command.areas.bell_psi_plus_escape.help_btn_text.es = q_command.areas.bell_psi_plus_escape.help_btn_text.en q_command.areas.bell_psi_plus_escape.help_btn_text.ja = [[ TLDR:青い液体レベルをΨ+ のベル状態と呼ばれるsqrt(1/2)|01> + sqrt(1/2)|10>の量子状 態に対応させます。 ---- 量子エンタングルメントの最もシンプルな4つの例は、ベル状態です。これらのベル状態の1つ は、Ψ+(psi +)で表され、2番目の線にXゲートを配置し、Xゲートの右側にΦ+のベル状態回 路(別のパズルで指示されています)を追加することで実現できます。 片方の量子ビットを測定すると、もう一方の量子ビットの測定状態が決定されます。正しいΨ+ のベル状態の解は、 |01>と|10>が測定される可能性が等しく、位相が等しくなります。ここの ブロックワールドの回路上の位相の表記は、右向き矢印が 0ラジアンで、そこから反時計回り の回転です。Ψ+のベル状態は一重項状態の1つとして知られており、量子ビットの1つを測定 すると、もう一方の量子ビットが反対の状態となることが決まります。 Qブロックがゴールドになったら、パズルが解けたという意味です。おめでとうございます! ]] q_command.areas.bell_psi_plus_escape.help_btn_caption = {} q_command.areas.bell_psi_plus_escape.help_btn_caption.en = "Make the psi+ Bell state" q_command.areas.bell_psi_plus_escape.help_btn_caption.es = q_command.areas.bell_psi_plus_escape.help_btn_caption.en q_command.areas.bell_psi_plus_escape.help_btn_caption.ja = "Ψ+ のベル状態を作る" -------- Room 13 (Level I) q_command.areas.bell_psi_minus_escape = {} q_command.areas.bell_psi_minus_escape.region = q_command.regions.esc_rooms_level_1 table.insert(q_command.regions.esc_rooms_level_1, q_command.areas.bell_psi_minus_escape) q_command.areas.bell_psi_minus_escape.area_num = #q_command.regions.esc_rooms_level_1 q_command.areas.bell_psi_minus_escape.center_pos = {x = 248, y = 0, z = 82} q_command.areas.bell_psi_minus_escape.radius = 5 q_command.areas.bell_psi_minus_escape.q_block_pos = {x = 245, y = 0, z = 80} q_command.areas.bell_psi_minus_escape.door_pos = {x = 250, y = 0, z = 87} q_command.areas.bell_psi_minus_escape.portal_pos = {x = 253, y = 1, z = 82} q_command.areas.bell_psi_minus_escape.chest_pos = {x = 250, y = 0, z = 78} q_command.areas.bell_psi_minus_escape.chest_inv = { inventory = { main = {[1] = "", [2] = "", [3] = "", [4] = "", [5] = "", [6] = "", [7] = "", [8] = "", [9] = "", [10] = "", [11] = "", [12] = "", [13] = "", [14] = "", [15] = "", [16] = "", [17] = "", [18] = "", [19] = "", [20] = "", [21] = "", [22] = "", [23] = "", [24] = "", [25] = "circuit_blocks:circuit_blocks_x_gate", [26] = "", [27] = "circuit_blocks:circuit_blocks_z_gate", [28] = "", [29] = "", [30] = "circuit_blocks:circuit_blocks_h_gate", [31] = "circuit_blocks:control_tool", [32] = "" } } } q_command.areas.bell_psi_minus_escape.solution_statevector = {{r=0,i=0},{r=0.707,i=0},{r=-0.707,i=0},{r=0,i=0}} q_command.areas.bell_psi_minus_escape.help_chat_msg = { "Let's tackle the fourth and final Bell state, this time also using a Z gate." } q_command.areas.bell_psi_minus_escape.help_chat_msg.es = { "Vamos a por el cuarto estado de Bell, esta vez usando una puerta Z." } q_command.areas.bell_psi_minus_escape.help_chat_msg.ja = { "4番目のそして最後のベル状態に取り組みましょう。今度はZゲートを使います。" } q_command.areas.bell_psi_minus_escape.help_chat_sent = false q_command.areas.bell_psi_minus_escape.help_success_msg = { "Awesome! This one is called the 'psi -', Bell state." } q_command.areas.bell_psi_minus_escape.help_success_msg.es = { "¡Alucinante! Este es el estado de Bell “psi -“." } q_command.areas.bell_psi_minus_escape.help_success_msg.ja = { "お見事です! これは「Ψ-」のベル状態と呼ばれます。" } q_command.areas.bell_psi_minus_escape.success_chat_sent = false q_command.areas.bell_psi_minus_escape.help_btn_text = {} q_command.areas.bell_psi_minus_escape.help_btn_text.en = [[ TLDR: Make the blue liquid levels correspond to a quantum state of sqrt(1/2) |01> - sqrt(1/2) |10> which is referred to as the psi- Bell state. ---- The four simplest examples of quantum entanglement are the Bell states. One of these Bell states, symbolized by psi- (psi minus), may be realized by placing an X gate on the second wire, adding the phi+ Bell state circuit (as instructed in another puzzle) to the right of the X gate, and adding a Z gate to the second wire after the phi+ Bell state circuit. Measuring one of the qubits results in the measured state of the other qubit to be determined. A correct psi- Bell state solution will have probabilities indicating that measurement results |01> and |10> are equally likely, as well has having opposite phases. The notation for a phase on these block-world circuits is an arrow that points in a direction signifying its counterclockwise rotation, from 0 radians pointing rightward. As an example, a leftward pointing arrow signifies a phase of pi radians. The psi- Bell state is known as one of the singlet states, where measuring one of the qubits determines that the other qubit will be measured as the opposite state. If the Q block turned gold, congratulations on solving the puzzle! ]] q_command.areas.bell_psi_minus_escape.help_btn_text.es = q_command.areas.bell_psi_minus_escape.help_btn_text.en q_command.areas.bell_psi_minus_escape.help_btn_text.ja = [[ TLDR:青い液体レベルをsqrt(1/2)|01>-sqrt(1/2)|10>の量子状態に対応させます。これ は、Ψ-のベル状態と呼ばれます。 ---- 量子エンタングルメントの最もシンプルな4つの例は、ベル状態です。これらのベル状態の1つ は、Ψ-(psi -)と呼ばれ、Xゲートを2番目の線に配置し、Xゲートの右側にΦ +のベル状態の 回路(別のパズルで示されました)を追加し、その後に2番目の線にZゲートを追加することで 実現できます。 片方の量子ビットを測定すると、もう片方の量子ビットの測定状態が決定されます。正確なΨ- のベル状態の解は、|01>と|10>が測定される確率が等しく、逆の位相を持ちます。ここのブ ロックワールドの回路上の位相の表記は、右向き矢印が 0ラジアンで、そこから反時計回りの 回転です。例として、左向きの矢印は、πラジアンの位相を示します。 Ψ-のベル状態は一重項 状態の1つとして知られており、片方の量子ビットを測定すると、もう片方の量子ビットが反 対の状態となることが決まります。 Qブロックがゴールドになったら、パズルが解けたという意味です。おめでとうございます! ]] q_command.areas.bell_psi_minus_escape.help_btn_caption = {} q_command.areas.bell_psi_minus_escape.help_btn_caption.en = "Make the psi- Bell state" q_command.areas.bell_psi_minus_escape.help_btn_caption.es = q_command.areas.bell_psi_minus_escape.help_btn_caption.en q_command.areas.bell_psi_minus_escape.help_btn_caption.ja = "Ψ- のベル状態を作る" -------- Room 14 (Level I) q_command.areas.ghz_state_escape = {} q_command.areas.ghz_state_escape.region = q_command.regions.esc_rooms_level_1 table.insert(q_command.regions.esc_rooms_level_1, q_command.areas.ghz_state_escape) q_command.areas.ghz_state_escape.area_num = #q_command.regions.esc_rooms_level_1 q_command.areas.ghz_state_escape.center_pos = {x = 248, y = 0, z = 92} q_command.areas.ghz_state_escape.radius = 5 q_command.areas.ghz_state_escape.q_block_pos = {x = 244, y = 0, z = 96} q_command.areas.ghz_state_escape.door_pos = {x = 243, y = 0, z = 94} q_command.areas.ghz_state_escape.portal_pos = {x = 253, y = 1, z = 92} q_command.areas.ghz_state_escape.chest_pos = {x = 252, y = 0, z = 90} q_command.areas.ghz_state_escape.chest_inv = { inventory = { main = {[1] = "", [2] = "", [3] = "", [4] = "", [5] = "", [6] = "", [7] = "", [8] = "", [9] = "", [10] = "", [11] = "", [12] = "", [13] = "", [14] = "", [15] = "", [16] = "", [17] = "", [18] = "", [19] = "", [20] = "", [21] = "", [22] = "", [23] = "", [24] = "", [25] = "circuit_blocks:circuit_blocks_x_gate", [26] = "", [27] = "", [28] = "", [29] = "", [30] = "circuit_blocks:circuit_blocks_h_gate", [31] = "circuit_blocks:control_tool", [32] = "" } } } q_command.areas.ghz_state_escape.solution_statevector = {{r=0.707,i=0},{r=0,i=0},{r=0,i=0},{r=0,i=0},{r=0,i=0},{r=0,i=0},{r=0,i=0},{r=0.707,i=0}} q_command.areas.ghz_state_escape.help_chat_msg = { "Next you'll entangle three qubits so that they all either measure 0s or 1s" } q_command.areas.ghz_state_escape.help_chat_msg.es = { "Ahora entrelazarás tres cúbits de forma que todos midan o 0, o 1." } q_command.areas.ghz_state_escape.help_chat_msg.ja = { "次は、3つの量子ビットをエンタングルして、すべてが0またはすべてが1に測定される ", "状態を作ります。" } q_command.areas.ghz_state_escape.help_chat_sent = false q_command.areas.ghz_state_escape.help_success_msg = { "Congratulations! You've successfully created a state known as GHZ." } q_command.areas.ghz_state_escape.help_success_msg.es = { "¡Enhorabuena! Has creado el estado conocido como “GHZ”." } q_command.areas.ghz_state_escape.help_success_msg.ja = { "おめでとうございます! GHZとよばれる状態を正しく作成しました。" } q_command.areas.ghz_state_escape.success_chat_sent = false q_command.areas.ghz_state_escape.help_btn_text = {} q_command.areas.ghz_state_escape.help_btn_text.en = [[ TLDR: Make the blue liquid levels correspond to a quantum state of sqrt(1/2) |000> - sqrt(1/2) |111> which is referred to as the GHZ state. ---- GHZ (Greenberger–Horne–Zeilinger) states are entangled states involving three or more qubits, where the basis states involved contain all zeros or all ones. For example, the entangled state in this three-wire circuit puzzle has equal probabilities of being measured as |000> and |111>. Please refer to the Bell state circuit puzzles for more information on entanglement. One way to realize this state is to place a Hadamard gate on the top wire, and an X gate on the second wire in a column to the right of the Hadamard gate. Then select the control tool from the hotbar (after having retrieved it from the chest). While positioning the cursor on the X gate in the circuit, convert it to a CNOT gate by left-clicking, until the control qubit is on the same wire as the Hadamard gate. Repeat this process to place another CNOT gate whose X gate is on the third wire and control qubit is on the top wire. Note that measuring the circuit (by right-clicking the measurement blocks) results in either |000> or |111> each time. If the Q block turned gold, congratulations on solving the puzzle! ]] q_command.areas.ghz_state_escape.help_btn_text.es = q_command.areas.ghz_state_escape.help_btn_text.en q_command.areas.ghz_state_escape.help_btn_text.ja = [[ TLDR:青い液体レベルをGHZ状態と呼ばれるsqrt(1/2)|000>-sqrt(1/2)|111>の量子状態に 対応させます。 ---- GHZ(グリーンバーガー=ホーン=ツァイリンガー)状態は、3つ以上の量子ビットが関与す るもつれ状態であり、基底状態はすべて0またはすべて1です。たとえば、この3線式回路パズ ルのもつれ状態は、|000>と|111>の測定される確率が等しくなります。エンタングルメントの 詳細については、ベル状態の回路パズルを参照してください。 この状態を実現する1つの方法は、上の線にアダマールゲートを配置し、アダマールゲートの 右側の列の2番目の線にXゲートを配置し、次に、ホットバーからコントロールツールを選択 (チェストから取得した後)します。回路内のXゲートにカーソルを置きながら、制御量子 ビットがアダマールゲートと同じ線上に来るまで左クリックして、カーソルをCNOTゲートに 変換します。同じようにして、Xゲートを3番目に、制御量子ビットが最上部の線にあるように 別のCNOTゲートを配置します。 (測定ブロックを右クリックして)回路を測定すると、毎回|000>または|111>になります。 Qブロックがゴールドになったら、パズルが解けたという意味です。おめでとうござい ます! ]] q_command.areas.ghz_state_escape.help_btn_caption = {} q_command.areas.ghz_state_escape.help_btn_caption.en = "Make the GHZ state" q_command.areas.ghz_state_escape.help_btn_caption.es = q_command.areas.ghz_state_escape.help_btn_caption.en q_command.areas.ghz_state_escape.help_btn_caption.ja = "GHZ状態を作る" -------- Room 15 (Level I) q_command.areas.y_z_rot_1wire_escape = {} q_command.areas.y_z_rot_1wire_escape.region = q_command.regions.esc_rooms_level_1 table.insert(q_command.regions.esc_rooms_level_1, q_command.areas.y_z_rot_1wire_escape) q_command.areas.y_z_rot_1wire_escape.area_num = #q_command.regions.esc_rooms_level_1 q_command.areas.y_z_rot_1wire_escape.center_pos = {x = 238, y = 0, z = 92} q_command.areas.y_z_rot_1wire_escape.radius = 5 q_command.areas.y_z_rot_1wire_escape.q_block_pos = {x = 236, y = 0, z = 90} q_command.areas.y_z_rot_1wire_escape.door_pos = {x = 236, y = 0, z = 87} q_command.areas.y_z_rot_1wire_escape.portal_pos = {x = 243, y = 1, z = 92} q_command.areas.y_z_rot_1wire_escape.chest_pos = {x = 240, y = 0, z = 96} q_command.areas.y_z_rot_1wire_escape.chest_inv = { inventory = { main = {[1] = "", [2] = "", [3] = "", [4] = "", [5] = "", [6] = "", [7] = "", [8] = "", [9] = "", [10] = "", [11] = "", [12] = "", [13] = "", [14] = "", [15] = "", [16] = "", [17] = "", [18] = "circuit_blocks:circuit_blocks_ry_gate_0p16", [19] = "circuit_blocks:circuit_blocks_rz_gate_0p16", [20] = "", [21] = "", [22] = "", [23] = "circuit_blocks:rotate_tool", [24] = "", [25] = "", [26] = "", [27] = "", [28] = "", [29] = "", [30] = "", [31] = "", [32] = "" } } } q_command.areas.y_z_rot_1wire_escape.solution_statevector = {{r=0.924,i=0},{r=-0,i=0.383}} q_command.areas.y_z_rot_1wire_escape.help_chat_msg = { "In this puzzle you'll experiment with the effects of rotating the state of a", "qubit in the Y and Z axes. Hint: You'll click the Ry and Rz blocks while wielding", "the Rotate Tool." } q_command.areas.y_z_rot_1wire_escape.help_chat_msg.es = { "En este puzzle experimentarás con los efectos de rotar el estado de un cúbit alrededor de los", "ejes Y y Z. Pista: sostén la Herramienta Rotación y haz clic en los bloques Ry y Rz." } q_command.areas.y_z_rot_1wire_escape.help_chat_msg.ja = { "このパズルでは、Y軸とZ軸で量子ビットの状態を回転させる効果を実験します。 ヒン ", "ト:回転ツールを使用しながら、RyブロックとRzブロックをクリックします。" } q_command.areas.y_z_rot_1wire_escape.help_chat_sent = false q_command.areas.y_z_rot_1wire_escape.help_success_msg = { "Nice work! Did you notice that rotating the qubit on the Y axis changed the", "measurement probabilities, but rotating on the Z axis didn't?" } q_command.areas.y_z_rot_1wire_escape.help_success_msg.es = { "¡Bien hecho! ¿Te has dado cuenta de que, rotando el cúbit alrededor del eje Y, cambian las", "probabilidades de la medida, pero rotándolo alrededor de Z, no cambian?" } q_command.areas.y_z_rot_1wire_escape.help_success_msg.ja = { "よくできました! Y軸で量子ビットを回転させると測定される確率は変わりますが、Z ", "軸で回転させても変わらないということに気づきましたか?" } q_command.areas.y_z_rot_1wire_escape.success_chat_sent = false q_command.areas.y_z_rot_1wire_escape.help_btn_text = {} q_command.areas.y_z_rot_1wire_escape.help_btn_text.en = [[ TLDR: Make the blue liquid levels correspond to the following quantum state: sqrt(0.85) |0> + sqrt(0.15) e^i pi/2 |1> ---- This circuit leverages Ry and Rz gates to create a state that has approx 85% probability of measuring |0> and approx 15% probability of measuring |1>. The latter basis states has a phase of pi/2. To solve this circuit puzzle, place Ry and Rz gates on the wire, and change their rotation angles by left and right-clicking the rotate tool until the desired state is achieved. If the Q block turned gold, congratulations on solving the puzzle! ]] q_command.areas.y_z_rot_1wire_escape.help_btn_text.es = q_command.areas.y_z_rot_1wire_escape.help_btn_text.en q_command.areas.y_z_rot_1wire_escape.help_btn_text.ja = [[ TLDR:青い液体レベルを次の量子状態に対応させます: sqrt(0.85)|0> + sqrt(0.15)e ^ i pi/2 |1> ---- この回路は、RyおよびRzゲートを使って、|0>を測定する確率が約85%、|1>を測定する確率が 約15%になる状態を作成します。 後者の基底状態の位相はpi/2です。 この回路パズルを解くに は、線上にRyおよびRzゲートを配置し、回転ツールを左および右クリックして、目的の状態に なるまで回転角度を調整します。 Qブロックがゴールドになったら、パズルが解けたという意味です。おめでとうござい ます! ]] q_command.areas.y_z_rot_1wire_escape.help_btn_caption = {} q_command.areas.y_z_rot_1wire_escape.help_btn_caption.en = "Rotate a qubit into a desired state" q_command.areas.y_z_rot_1wire_escape.help_btn_caption.es = q_command.areas.y_z_rot_1wire_escape.help_btn_caption.en q_command.areas.y_z_rot_1wire_escape.help_btn_caption.ja = "量子ビットを求める状態に回転する" -------- Room 16 (Level I) q_command.areas.phase_rot_2wire_escape = {} q_command.areas.phase_rot_2wire_escape.region = q_command.regions.esc_rooms_level_1 table.insert(q_command.regions.esc_rooms_level_1, q_command.areas.phase_rot_2wire_escape) q_command.areas.phase_rot_2wire_escape.area_num = #q_command.regions.esc_rooms_level_1 q_command.areas.phase_rot_2wire_escape.center_pos = {x = 238, y = 0, z = 82} q_command.areas.phase_rot_2wire_escape.radius = 5 q_command.areas.phase_rot_2wire_escape.q_block_pos = {x = 240, y = -1, z = 80} q_command.areas.phase_rot_2wire_escape.door_pos = {x = 233, y = 0, z = 80} q_command.areas.phase_rot_2wire_escape.portal_pos = {x = 243, y = 1, z = 82} q_command.areas.phase_rot_2wire_escape.chest_pos = {x = 234, y = 0, z = 84} q_command.areas.phase_rot_2wire_escape.chest_inv = { inventory = { main = {[1] = "", [2] = "", [3] = "", [4] = "", [5] = "", [6] = "", [7] = "", [8] = "", [9] = "", [10] = "", [11] = "", [12] = "", [13] = "", [14] = "", [15] = "", [16] = "", [17] = "", [18] = "", [19] = "circuit_blocks:circuit_blocks_rz_gate_0p16", [20] = "", [21] = "", [22] = "", [23] = "circuit_blocks:rotate_tool", [24] = "", [25] = "", [26] = "", [27] = "", [28] = "", [29] = "", [30] = "circuit_blocks:circuit_blocks_h_gate", [31] = "", [32] = "" } } } q_command.areas.phase_rot_2wire_escape.solution_statevector = {{r=0.5,i=0},{r=-0,i=0.5},{r=0,i=-0.5},{r=0.5,i=0}} q_command.areas.phase_rot_2wire_escape.help_chat_msg = { "Now you'll experiment with a pattern commonly used in quantum computing algorithms,", "in which Z axis rotations are sandwiched between pairs of H gates." } q_command.areas.phase_rot_2wire_escape.help_chat_msg.es = { "Ahora experimentarás con un patrón comúnmente utilizado en algoritmos cuánticos, donde", "rotaciones alrededor del eje Z se encuentran en medio de pares de puertas H, como si fueran", "el relleno de un sándwich." } q_command.areas.phase_rot_2wire_escape.help_chat_msg.ja = { "次に、量子計算アルゴリズムで一般的に使用されるパターンを実験します。このパター ", "ンでは、Z軸の回転がHゲートのペアの間に挟まれています。" } q_command.areas.phase_rot_2wire_escape.help_chat_sent = false q_command.areas.phase_rot_2wire_escape.help_success_msg = { "Well done! The H gates transformed changes in phase to changes in measurement", "probabilities.", "Congratulations on solving these circuit puzzles! Feel free to revisit any of them,", "and then explore other areas after climbing the ladder back to the main room." } q_command.areas.phase_rot_2wire_escape.help_success_msg.es = { "¡Muy bien! Las puertas H transforman cambios en la fase en cambios en la probabilidad.", "¡Mi más sentida enhorabuena por haber resuelto estos puzzles de circuitos! Vuelve a", "cualquiera de ellos si quieres y explora otras áreas tras subir las escaleras de vuelta", "a la habitación principal." } q_command.areas.phase_rot_2wire_escape.help_success_msg.ja = { "よくできました! Hゲートによって、位相の変化を測定される確率の変化に変換しま ", "した。おめでとうございます! ここのすべての回路パズルを解きました。ここへは、 ", "いつでも自由に戻ってこられます。次は、はしごを登ってメインルームに戻り、他のエ ", "リアも探索してみてください。" } q_command.areas.phase_rot_2wire_escape.success_chat_sent = false q_command.areas.phase_rot_2wire_escape.help_btn_text = {} q_command.areas.phase_rot_2wire_escape.help_btn_text.en = [[ TLDR: Make the blue liquid levels correspond to the following quantum state: sqrt(1/4) |00> + sqrt(1/4) e^i pi/2 |01> + sqrt(1/4) e^i 3pi/2 |10> + sqrt(1/4) |11> ---- This circuit leverages Hadamard gates and Rz gates to create a state that has equal probabilities of measuring |00>, |01>, |10> and |11>, with these basis states having various phase rotations. To solve this circuit puzzle, place an Rz between two H blocks on each wire. Then rotate the Rx gated by left and right-clicking them until the desired state is achieved. Notice that phase (Z axis) rotations that you apply become rotations on the X axis when sandwiched in-between Hadamard gates, converting changes in phase to changes in measurement probabilities. If the Q block turned gold, congratulations on solving the puzzle! ]] q_command.areas.phase_rot_2wire_escape.help_btn_text.es = q_command.areas.phase_rot_2wire_escape.help_btn_text.en q_command.areas.phase_rot_2wire_escape.help_btn_text.ja = [[ TLDR:青い液体レベルを次の量子状態に対応させます: sqrt(1/4)|00> + sqrt(1/4)e ^ i pi/2 |01> + sqrt(1/4)e ^ i 3pi/2 |10> + sqrt(1/4)|11> ---- この回路は、アダマールゲートとRzゲートを使って、|00>、|01>、|10>、および|11>が等しい 確率で測定される状態を作ります。これらの基底状態はさまざまに回転された位相を持ちま す。 この回路パズルを解くには、各線の2つのHブロックの間にRzを配置し、 目的の状態にな るまで、Rzを左および右クリックして回転させます。 適用する位相(Z軸)回転は、アダマー ルゲートの間に挟まれるとX軸の回転になり、位相の変化を測定確率の変化に変換することに 注意してください。 Qブロックがゴールドになったら、パズルが解けたという意味です。おめでとうございます! ]] q_command.areas.phase_rot_2wire_escape.help_btn_caption = {} q_command.areas.phase_rot_2wire_escape.help_btn_caption.en = "Convert phase rotations into measurement probabilities" q_command.areas.phase_rot_2wire_escape.help_btn_caption.es = q_command.areas.phase_rot_2wire_escape.help_btn_caption.en q_command.areas.phase_rot_2wire_escape.help_btn_caption.ja = "位相回転を測定確率に変換する" -- END Escape room puzzles Level I ---------------------------------------------
QiskitBlocks/qiskitblocks/mods/q_command/q_esc_rooms_level_1.lua/0
{ "file_path": "QiskitBlocks/qiskitblocks/mods/q_command/q_esc_rooms_level_1.lua", "repo_id": "QiskitBlocks", "token_count": 42912 }
4
--[[ Copyright 2019 the original author or authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --]] --[[ Make wall blocks for areas in the game --]] function q_command:register_wall_block(texture_name) minetest.register_node("q_command:dr_" .. texture_name, { description = "Wall block " .. texture_name, tiles = {"q_command_silver_sandstone_wall_tile.png", "q_command_silver_sandstone_wall_tile.png", "q_command_silver_sandstone_wall_tile.png", "q_command_silver_sandstone_wall_tile.png", "q_command_silver_sandstone_wall_tile.png", texture_name .. ".png",}, groups = {oddly_breakable_by_hand=2}, paramtype2 = "facedir" }) end q_command:register_wall_block("q_command_dirac_blank") q_command:register_wall_block("q_command_dirac_vert") q_command:register_wall_block("q_command_dirac_rangle") q_command:register_wall_block("q_command_dirac_plus") q_command:register_wall_block("q_command_dirac_minus") q_command:register_wall_block("q_command_dirac_rangle_plus") q_command:register_wall_block("q_command_dirac_rangle_minus") q_command:register_wall_block("q_command_dirac_rangle_space_vert") q_command:register_wall_block("q_command_dirac_rangle_plus_vert") q_command:register_wall_block("q_command_dirac_rangle_minus_vert") --q_command:register_wall_tile("sqrt") q_command:register_wall_block("q_command_dirac_sqrt_1_2") q_command:register_wall_block("q_command_dirac_sqrt_1_4") q_command:register_wall_block("q_command_dirac_sqrt_1_8") q_command:register_wall_block("q_command_dirac_sqrt_15") q_command:register_wall_block("q_command_dirac_sqrt_85") q_command:register_wall_block("q_command_dirac_sqrt_1_2_vert") q_command:register_wall_block("q_command_dirac_sqrt_1_4_vert") q_command:register_wall_block("q_command_dirac_sqrt_1_8_vert") q_command:register_wall_block("q_command_dirac_plus_state") q_command:register_wall_block("q_command_dirac_minus_state") q_command:register_wall_block("q_command_dirac_i_state") q_command:register_wall_block("q_command_dirac_equal_sign") q_command:register_wall_block("q_command_dirac_111_bottom") q_command:register_wall_block("q_command_dirac_i_eq_000_top") q_command:register_wall_block("q_command_dirac_111_bottom_colors") q_command:register_wall_block("q_command_dirac_i_eq_000_top_colors") q_command:register_wall_block("q_command_math_sum") q_command:register_wall_block("q_command_math_e_i_pi") q_command:register_wall_block("q_command_math_e_i_pi_2") q_command:register_wall_block("q_command_math_e_i_pi_4") q_command:register_wall_block("q_command_math_e_i_3pi_2") q_command:register_wall_block("q_command_char_lower_a") q_command:register_wall_block("q_command_chars_paren_lower_a") q_command:register_wall_block("q_command_char_lower_b") q_command:register_wall_block("q_command_chars_lower_b_paren") q_command:register_wall_block("q_command_char_lower_c") q_command:register_wall_block("q_command_char_lower_d") q_command:register_wall_block("q_command_char_lower_e") q_command:register_wall_block("q_command_char_lower_f") q_command:register_wall_block("q_command_chars_xor_2") q_command:register_wall_block("q_command_chars_lower_ot") q_command:register_wall_block("q_command_chars_lower_he") q_command:register_wall_block("q_command_chars_lower_rw") q_command:register_wall_block("q_command_chars_lower_ise") q_command:register_wall_block("q_command_chars_and_1") q_command:register_wall_block("q_command_chars_and_2") q_command:register_wall_block("q_command_chars_or") q_command:register_wall_block("q_command_chars_nand_1") q_command:register_wall_block("q_command_chars_nand_2") q_command:register_wall_block("q_command_chars_not_1") q_command:register_wall_block("q_command_chars_not_2") q_command:register_wall_block("q_command_chars_nor_1") q_command:register_wall_block("q_command_chars_nor_2") q_command:register_wall_block("q_command_chars_xor_1") q_command:register_wall_block("q_command_chars_xor_2") q_command:register_wall_block("q_command_chars_if_c_underlined") q_command:register_wall_block("q_command_chars_equal_underlined") q_command:register_wall_block("q_command_chars_not_equal_underlined") q_command:register_wall_block("q_command_chars_one_state_underlined") q_command:register_wall_block("q_command_horiz_line_mid") q_command:register_wall_block("q_command_lines_swap_1") q_command:register_wall_block("q_command_lines_swap_2") -- TODO: Define function to create this basis state blocks q_command:register_wall_block("q_command_state_1qb_0") q_command:register_wall_block("q_command_state_1qb_1") q_command:register_wall_block("q_command_state_2qb_0") q_command:register_wall_block("q_command_state_2qb_1") q_command:register_wall_block("q_command_state_2qb_2") q_command:register_wall_block("q_command_state_2qb_3") q_command:register_wall_block("q_command_state_3qb_0") q_command:register_wall_block("q_command_state_3qb_1") q_command:register_wall_block("q_command_state_3qb_2") q_command:register_wall_block("q_command_state_3qb_3") q_command:register_wall_block("q_command_state_3qb_4") q_command:register_wall_block("q_command_state_3qb_5") q_command:register_wall_block("q_command_state_3qb_6") q_command:register_wall_block("q_command_state_3qb_7") q_command:register_wall_block("q_command_state_4qb_0") q_command:register_wall_block("q_command_state_4qb_1") q_command:register_wall_block("q_command_state_4qb_2") q_command:register_wall_block("q_command_state_4qb_3") q_command:register_wall_block("q_command_state_4qb_4") q_command:register_wall_block("q_command_state_4qb_5") q_command:register_wall_block("q_command_state_4qb_6") q_command:register_wall_block("q_command_state_4qb_7") q_command:register_wall_block("q_command_state_4qb_8") q_command:register_wall_block("q_command_state_4qb_9") q_command:register_wall_block("q_command_state_4qb_10") q_command:register_wall_block("q_command_state_4qb_11") q_command:register_wall_block("q_command_state_4qb_12") q_command:register_wall_block("q_command_state_4qb_13") q_command:register_wall_block("q_command_state_4qb_14") q_command:register_wall_block("q_command_state_4qb_15") q_command:register_wall_block("q_command_state_1qb_0_colors") q_command:register_wall_block("q_command_state_1qb_1_colors") q_command:register_wall_block("q_command_state_2qb_0_colors") q_command:register_wall_block("q_command_state_2qb_1_colors") q_command:register_wall_block("q_command_state_2qb_2_colors") q_command:register_wall_block("q_command_state_2qb_3_colors") q_command:register_wall_block("q_command_state_3qb_0_colors") q_command:register_wall_block("q_command_state_3qb_1_colors") q_command:register_wall_block("q_command_state_3qb_2_colors") q_command:register_wall_block("q_command_state_3qb_3_colors") q_command:register_wall_block("q_command_state_3qb_4_colors") q_command:register_wall_block("q_command_state_3qb_5_colors") q_command:register_wall_block("q_command_state_3qb_6_colors") q_command:register_wall_block("q_command_state_3qb_7_colors") q_command:register_wall_block("q_command_esc_room_exit_wall_tile") q_command:register_wall_block("q_command_esc_room_exit_left") q_command:register_wall_block("q_command_esc_room_no_entry_wall_tile") q_command:register_wall_block("q_command_construction_wall_tile") q_command:register_wall_block("q_command_portal_top_wall_tile") q_command:register_wall_block("q_command_portal_bottom_wall_tile") q_command:register_wall_block("q_command_portal_return_top_wall_tile") q_command:register_wall_block("q_command_portal_return_bottom_wall_tile") q_command:register_wall_block("q_command_read_first_wall_tile") q_command:register_wall_block("q_command_bloch_minus_state_wall_tile") q_command:register_wall_block("q_command_9_3_4_wall_tile") q_command:register_wall_block("q_command_silver_sandstone_wall_tile") q_command:register_wall_block("prof_q_top_low_res") q_command:register_wall_block("prof_q_bottom_low_res") --Added by team #49 q_command:register_wall_block("q_command_human_ch_wall_tile") q_command:register_wall_block("q_command_letter_capital_C_wall_tile") q_command:register_wall_block("q_command_letter_capital_D_wall_tile") q_command:register_wall_block("q_command_letter_capital_G_wall_tile") q_command:register_wall_block("q_command_letter_capital_H_wall_tile") q_command:register_wall_block("q_command_letter_capital_J_wall_tile") q_command:register_wall_block("q_command_letter_capital_M_wall_tile") q_command:register_wall_block("q_command_letter_capital_Q_wall_tile") q_command:register_wall_block("q_command_letter_capital_S_wall_tile") q_command:register_wall_block("q_command_letter_capital_T_wall_tile") q_command:register_wall_block("q_command_letter_capital_W_wall_tile") q_command:register_wall_block("q_command_letter_capital_Y_wall_tile") q_command:register_wall_block("q_command_letter_g_wall_tile") q_command:register_wall_block("q_command_letter_h_wall_tile") q_command:register_wall_block("q_command_letter_i_wall_tile") q_command:register_wall_block("q_command_letter_j_wall_tile") q_command:register_wall_block("q_command_letter_k_wall_tile") q_command:register_wall_block("q_command_letter_l_wall_tile") q_command:register_wall_block("q_command_letter_m_wall_tile") q_command:register_wall_block("q_command_letter_n_wall_tile") q_command:register_wall_block("q_command_letter_o_wall_tile") q_command:register_wall_block("q_command_letter_p_wall_tile") q_command:register_wall_block("q_command_letter_q_wall_tile") q_command:register_wall_block("q_command_letter_r_wall_tile") q_command:register_wall_block("q_command_letter_s_wall_tile") q_command:register_wall_block("q_command_letter_t_wall_tile") q_command:register_wall_block("q_command_letter_u_wall_tile") q_command:register_wall_block("q_command_letter_v_wall_tile") q_command:register_wall_block("q_command_letter_w_wall_tile") q_command:register_wall_block("q_command_letter_x_wall_tile") q_command:register_wall_block("q_command_letter_y_wall_tile") q_command:register_wall_block("q_command_letter_z_wall_tile") q_command:register_wall_block("q_command_letter_capital_I_wall_tile") q_command:register_wall_block("q_command_letter_bra_state_0_wall_tile") q_command:register_wall_block("q_command_letter_number_2_wall_tile") q_command:register_wall_block("q_command_letter_number_wall_tile") q_command:register_wall_block("q_command_letter_4_wall_tile") q_command:register_wall_block("q_command_letter_9_wall_tile") q_command:register_wall_block("q_command_esc_room_1_7") q_command:register_wall_block("q_command_esc_room_2_7") q_command:register_wall_block("q_command_esc_room_3_7") q_command:register_wall_block("q_command_esc_room_4_7") q_command:register_wall_block("q_command_esc_room_5_7") q_command:register_wall_block("q_command_esc_room_6_7") q_command:register_wall_block("q_command_esc_room_7_7") local NUM_ESCAPE_ROOMS = 16 for idx = 1, NUM_ESCAPE_ROOMS do q_command:register_wall_block("q_command_esc_room_" .. tostring(idx) .. "_16") end local NUM_ESCAPE_ROOM_LEVELS = 16 for idx = 1, NUM_ESCAPE_ROOM_LEVELS do q_command:register_wall_block("q_command_esc_room_level_" .. tostring(idx)) end
QiskitBlocks/qiskitblocks/mods/q_command/q_make_wall_blocks.lua/0
{ "file_path": "QiskitBlocks/qiskitblocks/mods/q_command/q_make_wall_blocks.lua", "repo_id": "QiskitBlocks", "token_count": 4533 }
5
dofile(minetest.get_modpath("sfinv") .. "/api.lua") sfinv.register_page("sfinv:crafting", { title = "Crafting", get = function(self, player, context) return sfinv.make_formspec(player, context, [[ list[current_player;craft;1.75,0.5;3,3;] list[current_player;craftpreview;5.75,1.5;1,1;] image[4.75,1.5;1,1;gui_furnace_arrow_bg.png^[transformR270] listring[current_player;main] listring[current_player;craft] image[0,4.7;1,1;gui_hb_bg.png] image[1,4.7;1,1;gui_hb_bg.png] image[2,4.7;1,1;gui_hb_bg.png] image[3,4.7;1,1;gui_hb_bg.png] image[4,4.7;1,1;gui_hb_bg.png] image[5,4.7;1,1;gui_hb_bg.png] image[6,4.7;1,1;gui_hb_bg.png] image[7,4.7;1,1;gui_hb_bg.png] ]], true) end })
QiskitBlocks/qiskitblocks/mods/sfinv/init.lua/0
{ "file_path": "QiskitBlocks/qiskitblocks/mods/sfinv/init.lua", "repo_id": "QiskitBlocks", "token_count": 419 }
6
xschem = {} dofile(minetest.get_modpath("xschem") .. "/api.lua") local function begins(str, start) return str:sub(1, #start) == start end local function file_exists(path) local file = io.open(path, "r") if file then file:close() return true end return false end ----------------------------------------------- -- Add all nodes which begin with one of the -- -- following names to the meta whitelist -- ----------------------------------------------- local prefixes = { "q_command:", "default:chest", "default:sign", "circuit_blocks:", "mobs:", "mobs_npc:" } for name, _ in pairs(minetest.registered_nodes) do for i=1, #prefixes do if begins(name, prefixes[i]) then xschem.whitelist(name) end end end ---------------------- -- CHANGE AREA HERE -- ---------------------- local FROM = vector.new(-50,-5,-192) local TO = vector.new(600,30,370) minetest.register_chatcommand("xschemsave", { privs = { server = true }, func = function(name, param) local wp = minetest.get_worldpath() .. "/" local filename = "save" if param:trim() ~= "" and #param > 5 then filename = param if filename:sub(#filename - 3) == ".mts" then filename = filename:sub(1, #filename - 4) end end xschem.save(name, wp .. filename, FROM, TO) end, }) local savepath = minetest.get_modpath("xschem") .. "/schematics/save" if not file_exists(savepath .. ".mts") or not file_exists(savepath .. ".meta") then minetest.log("error", "Unable to find the saved map") return end if file_exists(minetest.get_worldpath() .. "/xschem_placed.txt") then return end local metalist do local meta_file = io.open(savepath .. ".meta", "r") local json = meta_file:read("*all") meta_file:close() metalist = minetest.parse_json(json) end minetest.register_on_generated(function(minp, maxp, blockseed) if metalist then local vm = minetest.get_mapgen_object("voxelmanip") minetest.place_schematic_on_vmanip(vm, FROM, savepath .. ".mts") vm:write_to_map() xschem.place_metadata(metalist, minp, maxp) end end) xschem.load_area(FROM, TO, function(duration_gen, duration_lighting) metalist = nil local str = "Map generation took %.02fs, and then light calculations took %.02fs" minetest.chat_send_all(str:format(duration_gen, duration_lighting)) local file = io.open(minetest.get_worldpath() .. "/xschem_placed.txt", "w") file:write("yes") file:close() end)
QiskitBlocks/qiskitblocks/mods/xschem/init.lua/0
{ "file_path": "QiskitBlocks/qiskitblocks/mods/xschem/init.lua", "repo_id": "QiskitBlocks", "token_count": 895 }
7
<!-- This course and all its materials can be found at https://github.com/msramalho/Teach-Me-Quantum where they are ket in the most recent version, subject to open source contributions from the community --> <h1 align="center">Teach Me Quantum</h1> A university-level course on **Quantum Computing** and **Quantum Information Science** that incorporates [IBM Q Experience](https://quantumexperience.ng.bluemix.net/qx/experience) and [Qiskit](https://www.qiskit.org/). This course is adequate for general audiences without prior knowledge on Quantum Mechanics and Quantum Computing (see [prior knowledge](#prior-knowledge)), has an estimated average duration of **10 weeks at 3h/week** (see [duration](#duration)) and is meant to be the entrypoint into the **Quantum World**. <p align="center"><img width="300px" src="https://i.imgur.com/39Mv9Ra.gif"></p> This course is **Open-source** and appropriate for both _autodidacticism_ as well as _classroom teaching_ by educators, professors and lecturers in their own classes. Given the dynamic nature of the topic, any open-source contributions and future improvements are welcome. <h3 align="center">🏆 This project was the winner of <a href="https://www.ibm.com/blogs/research/2019/01/ibmq-teach-quantum-winners/">IBM Q Teach Me Quantum award</a>!</h3> ## Course Overview * 📁 [Week 0 - Hello Quantum World](Week%200%20-%20Hello%20Quantum%20World) * 📖 [Slides](Week%200%20-%20Hello%20Quantum%20World/slides.pdf) * 📁 [Week 1 - Quantum Tools](Week%201%20-%20Quantum%20Tools) * 📖 [Slides](Week%201%20-%20Quantum%20Tools/slides.pdf) * 📁 [Exercises](Week%201%20-%20Quantum%20Tools/exercises) * 📁 [Week 2 - Quantum Information Science](Week%202%20-%20Quantum%20Information%20Science) * 📖 [Slides](Week%202%20-%20Quantum%20Information%20Science/slides.pdf) * 📁 [Exercises](Week%202%20-%20Quantum%20Information%20Science/exercises) * 📁 [Week 3 - Quantum Gates](Week%203%20-%20Quantum%20Gates) * 📖 [Slides](Week%203%20-%20Quantum%20Gates/slides.pdf) * 📁 [Exercises](Week%203%20-%20Quantum%20Gates/exercises) * 📁 [Week 4 - Quantum Facts](Week%204%20-%20Quantum%20Facts) * 📖 [Slides](Week%204%20-%20Quantum%20Facts/slides.pdf) * 📁 [Exercises](Week%204%20-%20Quantum%20Facts/exercises) * 📁 [Week 5 - Quantum Algorithms](Week%205%20-%20Quantum%20Algorithms) (Deutsch's algorithm) * 📖 [Slides](Week%205%20-%20Quantum%20Algorithms/slides.pdf) * 📁 [Exercises](Week%205%20-%20Quantum%20Algorithms/exercises) * 📁 [Week 6 - Quantum Search](Week%206%20-%20Quantum%20Search) (Grover's algorithm) * 📖 [Slides](Week%206%20-%20Quantum%20Search/slides.pdf) * 📁 [Exercises](Week%206%20-%20Quantum%20Search/exercises) * 📁 [Week 7 - Quantum Factorization](Week%207%20-%20Quantum%20Factorization) (Shor's algorithm) * 📖 [Slides](Week%207%20-%20Quantum%20Factorization/slides.pdf) * 📁 [Exercises](Week%207%20-%20Quantum%20Factorization/exercises) * 📁 [Week 8 - High Level Quantum Programming](Week%208%20-%20High%20Level%20Quantum%20Programming) (qiskit-aqua) * 📖 [Slides](Week%208%20-%20High%20Level%20Quantum%20Programming/slides.pdf) * 📁 [Exercises](Week%208%20-%20High%20Level%20Quantum%20Programming/exercises) * 📁 [Week 9 - State of the Quantum Art](Week%209%20-%20State%20of%20the%20Quantum%20Art) * 📖 [Slides](Week%209%20-%20State%20of%20the%20Quantum%20Art/slides.pdf) ## Prior Knowledge Students of this course are expected to be familiar with (this can be done while going through the course): * [Python](https://www.python.org/) language * [Jupyter](http://jupyter.org/) Notebook environment * Some linear algebra: inner and outer products, eigenvalues, norms, transpose, adjoints (complex conjugates), tensor product, ... ## Learning Goals After completing this course, students should be able to: * Understand the basics of Quantum Mechanics * Know how a computing model can be built around Quantum Mechanics * Understand the advantages, disadvantages and implications of Quantum Computing * Understand Quantum Information Science and how it contrasts with classical information theory * Leverage QISKit towards research and development in the _Quantum World_ * Understand the empirical differences between Quantum Simulators and real Quantum Devices (such as those available in IBMQ) * Design, interpret and deploy quantum circuits (simulators and real processors) * Know and describe a few of the most common quantum algorithms: Deutsch, Grover, Shor * Be able to quickly understand new quantum algorithms based on the same principles: Simon, ... * Be able to quickly understand new principles of quantum computing: Adiabatic, ... * Understand the impact that the advance of quantum computers can have on the world as we know it * Understand High Level applications of near-end quantum algorithms, namely how to use qiskit-aqua for solving real world problems * Move on to deeper waters, by exploring according to their heart's desire! ## Duration * Estimated average duration of **10 weeks at 3h/week** * Duration is flexible depending on level of depth a teacher imposes on each week. * Usually 1h theory + 2h practice, except for: * week 0 (1h + 0h = 1h) * week 1 (1h + 1h = 2h) * week 9 (2h + 0h = 2h) * Estimated total time: **25h to 30h**. ## Customizing Slides #### Reusing Slides The materials in this course can be adapted to specific classes, contexts, schools,... to the desire of the educators. The `author`, `date` and `instute` properties of each presentation is defined in the respective `macros.sty` file (this file is an exact copy for each week). If you want to update global settings for all weeks (like the author, update links colors, update code snippets display, ...) you can use the [`sh replicate_macros.sh`](utils/replicate_macros.sh) (linux) | [`replicate_macros.bat`](utils/replicate_macros.bat) (windows) to replicate the changes from a copy of the file for every week's folder (the source file must be in the [utils](utils/) folder, there is already an updated version of [macros.sty](utils/macros.sty) in there). The constraint for using this materials is to replace the `\author[]{}` command by the following command: `\author[LASTNAME]{FIRSTNAME LASTNAME,\\ \scriptsize{based on slides by \textbf{Miguel Sozinho Ramalho}}}` with the update author info. #### Animating Slides Each `.pdf` file for slides is static, but if you want to include animations you can do so by replacing the `document` class in the first line of the `main.tex` files by `\documentclass[handout]{beamer}`) and following [these instructions](https://tex.stackexchange.com/a/177060/126771). #### Adding Notes to Slides This can also be accomplished by appending the following lines before `\begin{document}`: ```tex \usepackage{pgfpages} \setbeameroption{show notes} \setbeameroption{show notes on second screen=right} ``` #### Compiling LaTeX files To achieve this use any LaTeX compiler of your choice, if you have [pdflatex](https://www.tug.org/applications/pdftex/) you can simply do `pdflatex main.tex` on each week's latex folder. #### Presenting Slides with Notes and/or Animations To present the slides with **notes** or with **animations** will only work with an external program, I advise [dannyedel/dspdfviewer](https://github.com/dannyedel/dspdfviewer/releases) which also has dual screen and timer functionality. --- ## Aditional notes Each week's slides has a particular theme, that is to help students distinguish between them and strengthen the learning process by fostering association. ## Final remarks This was an excelent oportunity to both teach and learn. I have sought to come up with a methodology of how I wanted my quantum education to have been, hopefully this will help others with similar learning tastes. If not, oh well, shift happens... <p align="center"><img src="http://assets.amuniversal.com/7c4d9f70a05b012f2fe600163e41dd5b"></p>
Teach-Me-Quantum/README.md/0
{ "file_path": "Teach-Me-Quantum/README.md", "repo_id": "Teach-Me-Quantum", "token_count": 2502 }
8
# Week 1 - Quantum Tools * Python and Pip * Jupyter * Google Colaboratory * Binder * Qiskit (and its composing parts) * Community and VSCode extension * IBMQ and IBMQ Experience # Exercises * Installing software * Creating IBMQ account * Local setup by running [this notebook](exercises/IBMQ_setup.ipynb) on your machine. (You can [clone](https://help.github.com/articles/cloning-a-repository/) or download this repo) ## Resources * [PDF slides](slides.pdf) * [slides src](latex/) Latex files and image resources used in the presentation (useful for PR on slide typos and such)
Teach-Me-Quantum/Week 1 - Quantum Tools/README.md/0
{ "file_path": "Teach-Me-Quantum/Week 1 - Quantum Tools/README.md", "repo_id": "Teach-Me-Quantum", "token_count": 178 }
9
\tikzset{every picture/.style={line width=0.75pt}} %set default line width to 0.75pt \begin{tikzpicture}[x=0.75pt,y=0.75pt,yscale=-1,xscale=1] %uncomment if require: \path (0,300); %set diagram left start at 0, and has height of 300 %Straight Lines [id:da09620307218751756] \draw (101.3,111.2) -- (191.3,111.2) ; %Shape: Rectangle [id:dp7033845205148042] \draw [fill={rgb, 255:red, 255; green, 255; blue, 255 } ,fill opacity=1 ] (131.3,95.7) -- (161.3,95.7) -- (161.3,126.7) -- (131.3,126.7) -- cycle ; % Text Node \draw (146,111) node [align=left] {H}; \end{tikzpicture}
Teach-Me-Quantum/Week 3 - Quantum Gates/latex/matcha/hadamard.tex/0
{ "file_path": "Teach-Me-Quantum/Week 3 - Quantum Gates/latex/matcha/hadamard.tex", "repo_id": "Teach-Me-Quantum", "token_count": 274 }
10
<jupyter_start><jupyter_text>Grover Search for Combinatorial ProblemsThis notebook is based on an official notebook by Qiskit team, available at https://github.com/qiskit/qiskit-tutorial under the [Apache License 2.0](https://github.com/Qiskit/qiskit-tutorial/blob/master/LICENSE) license. Initially done by Giacomo Nannicini and Rudy Raymond (based on [this paper](https://arxiv.org/abs/1708.03684)).Your **TASK** is to follow the tutorial, as you implement the Grover algorithm (studied this week) to a real SAT problem! IntroductionGrover search is one of the most popular algorithms used for searching a solution among many possible candidates using Quantum Computers. If there are $N$ possible solutions among which there is exactly one solution (that can be verified by some function evaluation), then Grover search can be used to find the solution with $O(\sqrt{N})$ function evaluations. This is in contrast to classical computers that require $\Omega(N)$ function evaluations: the Grover search is a quantum algorithm that provably can be used search the correct solutions quadratically faster than its classical counterparts. Here, we are going to illustrate the use of Grover search to solve a combinatorial problem called [Exactly-1 3-SAT problem](https://en.wikipedia.org/wiki/Boolean_satisfiability_problemExactly-1_3-satisfiability). The Exactly-1 3-SAT problem is a NP-complete problem, namely, it is one of the most difficult problems that are interconnected (meaning that if we solve any one of them, we essentially can solve all of them). Unfortunately, there are many natural problems that are NP-complete, such as, the Traveling Salesman Problem (TSP), the Maximum Cut (MaxCut) and so on. Up to now, there is no classical and quantum algorithm that can efficiently solve such NP-hard problems. We begin with an example of the Exactly-1 3-SAT problem. Then, we show how to design an evaluation function which is also known as the oracle (or, blackbox) which is essential to Grover search. Finally, we show the circuit of Grover search using the oracle and present their results on simulator and real-device backends. Exactly-1 3-SAT problemThe Exactly-1 3-SAT problem is best explained with the following concrete problem. Let us consider a Boolean function $f$ with three Boolean variables $x_1, x_2, x_3$ as below.$$f(x_1, x_2, x_3) = (x_1 \vee x_2 \vee \neg x_3) \wedge (\neg x_1 \vee \neg x_2 \vee \neg x_3) \wedge (\neg x_1 \vee x_2 \vee x_3) $$In the above function, the terms on the right-hand side equation which are inside $()$ are called clauses. Each clause has exactly three literals. Namely, the first clause has $x_1$, $x_2$ and $\neg x_3$ as its literals. The symbol $\neg$ is the Boolean NOT that negates (or, flips) the value of its succeeding literal. The symbols $\vee$ and $\wedge$ are, respectively, the Boolean OR and AND. The Boolean $f$ is satisfiable if there is an assignment of $x_1, x_2, x_3$ that evaluates to $f(x_1, x_2, x_3) = 1$ (or, $f$ evaluates to True). The Exactly-1 3-SAT problem requires us to find an assignment such that $f = 1$ (or, True) and there is *exactly* one literal that evaluates to True in every clause of $f$. A naive way to find such an assignment is by trying every possible combinations of input values of $f$. Below is the table obtained from trying all possible combinations of $x_1, x_2, x_3$. For ease of explanation, we interchangably use $0$ and False, as well as $1$ and True. |$x_1$ | $x_2$ | $x_3$ | $f$ | Comment | |------|-------|-------|-----|---------|| 0 | 0 | 0 | 1 | Not a solution because there are three True literals in the second clause | | 0 | 0 | 1 | 0 | Not a solution because $f$ is False | | 0 | 1 | 0 | 1 | Not a solution because there are two True literals in the first clause | | 0 | 1 | 1 | 1 | Not a solution because there are three True literals in the third clause | | 1 | 0 | 0 | 0 | Not a solution because $f$ is False | | 1 | 0 | 1 | 1 | **Solution**. BINGO!! | | 1 | 1 | 0 | 1 | Not a soluton because there are three True literals in the first clause | | 1 | 1 | 1 | 0 | Not a solution because $f$ is False | From the table above, we can see that the assignment $x_1x_2x_3 = 101$ is the solution fo the Exactly-1 3-SAT problem to $f$. In general, the Boolean function $f$ can have many clauses and more Boolean variables. A blackbox function to check the assignment of Exactly-1 3-SAT problemHere, we describe a method to construct a circuit to check the assignment of Exactly-1 3-SAT problem. The circuit can then be used as a blackbox (or, oracle) in Grover search. To design the blackbox, we do not need to know the solution to the problem in advance: it suffices to design a blackbox that checks if the assignment results in $f$ evaluates to True or False. It turns out that we can design such a blackbox efficiently (in fact, any NP-complete problem has the property that although finding the solution is difficult, checking the solution is easy). For each clause of $f$, we design a sub-circuit that outputs True if and only if there is exactly one True literal in the clause. Combining all sub-circuits for all clauses, we can then obtain the blackbox that outputs True if and only if all clauses are satisfied with exactly one True literal each. For example, let us consider the clause $(x_1 \vee \neg x_2 \vee x_3)$. It is easy to see that $y$ defined as $$y = x_1 \oplus \neg x_2 \oplus x_3 \oplus ( x_1 \wedge \neg x_2 \wedge x_3), $$import matplotlib.pyplot as plt%matplotlib inlineimport numpy as npis True if and only if exactly one of $x_1$, $\neg x_2$, and $x_3$ is True. Using two working qubits, $y$ can be computed by the following sub-circuit. Below, $x_1x_2x_3$ is renamed as $q_1q_2q_3$, $q_4$ is used as a working qubit, and $q_5$ is used to store the value of $y$.<jupyter_code>import numpy as np import matplotlib.pyplot as plt %matplotlib inline # importing Qiskit from qiskit import Aer, IBMQ from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit import available_backends, execute, register, get_backend, compile from qiskit.tools import visualization from qiskit.tools.visualization import circuit_drawer q = QuantumRegister(6) qc = QuantumCircuit(q) qc.x(q[2]) qc.cx(q[1], q[5]) qc.cx(q[2], q[5]) qc.cx(q[3], q[5]) qc.ccx(q[1], q[2], q[4]) qc.ccx(q[3], q[4], q[5]) qc.ccx(q[1], q[2], q[4]) qc.x(q[2]) circuit_drawer(qc)<jupyter_output><empty_output><jupyter_text>In the sub-circuit above, the three `ccx` gates on the right are used to compute $( q_1 \wedge \neg q_2 \wedge q_3)$ and write the result to $q_5$, while the three `cx` gates on the left are used to compute $q_1 \oplus \neg q_2 \oplus q_3$ and write the result to $q_5$. Notice that the right-most `ccx` gate is used to reset the value of $q_4$ so that it can be reused in the succeeding sub-circuits. From the above sub-circuit, we can define a blackbox function to check the solution of the Exactly-1 3-SAT problem as follows.<jupyter_code>def black_box_u_f(circuit, f_in, f_out, aux, n, exactly_1_3_sat_formula): """Circuit that computes the black-box function from f_in to f_out. Create a circuit that verifies whether a given exactly-1 3-SAT formula is satisfied by the input. The exactly-1 version requires exactly one literal out of every clause to be satisfied. """ num_clauses = len(exactly_1_3_sat_formula) for (k, clause) in enumerate(exactly_1_3_sat_formula): # This loop ensures aux[k] is 1 if an odd number of literals # are true for literal in clause: if literal > 0: circuit.cx(f_in[literal-1], aux[k]) else: circuit.x(f_in[-literal-1]) circuit.cx(f_in[-literal-1], aux[k]) # Flip aux[k] if all literals are true, using auxiliary qubit # (ancilla) aux[num_clauses] circuit.ccx(f_in[0], f_in[1], aux[num_clauses]) circuit.ccx(f_in[2], aux[num_clauses], aux[k]) # Flip back to reverse state of negative literals and ancilla circuit.ccx(f_in[0], f_in[1], aux[num_clauses]) for literal in clause: if literal < 0: circuit.x(f_in[-literal-1]) # The formula is satisfied if and only if all auxiliary qubits # except aux[num_clauses] are 1 if (num_clauses == 1): circuit.cx(aux[0], f_out[0]) elif (num_clauses == 2): circuit.ccx(aux[0], aux[1], f_out[0]) elif (num_clauses == 3): circuit.ccx(aux[0], aux[1], aux[num_clauses]) circuit.ccx(aux[2], aux[num_clauses], f_out[0]) circuit.ccx(aux[0], aux[1], aux[num_clauses]) else: raise ValueError('We only allow at most 3 clauses') # Flip back any auxiliary qubits to make sure state is consistent # for future executions of this routine; same loop as above. for (k, clause) in enumerate(exactly_1_3_sat_formula): for literal in clause: if literal > 0: circuit.cx(f_in[literal-1], aux[k]) else: circuit.x(f_in[-literal-1]) circuit.cx(f_in[-literal-1], aux[k]) circuit.ccx(f_in[0], f_in[1], aux[num_clauses]) circuit.ccx(f_in[2], aux[num_clauses], aux[k]) circuit.ccx(f_in[0], f_in[1], aux[num_clauses]) for literal in clause: if literal < 0: circuit.x(f_in[-literal-1]) # -- end function<jupyter_output><empty_output><jupyter_text>Inversion about the meanAnother important procedure in Grover search is to have an operation that perfom the *inversion-about-the-mean* step, namely, it performs the following transformation:$$\sum_{j=0}^{2^{n}-1} \alpha_j |j\rangle \rightarrow \sum_{j=0}^{2^{n}-1}\left(2 \left( \sum_{k=0}^{k=2^{n}-1} \frac{\alpha_k}{2^n} \right) - \alpha_j \right) |j\rangle $$The above transformation can be used to amplify the probability amplitude $\alpha_s$ when s is the solution and $\alpha_s$ is negative (and small), while $\alpha_j$ for $j \neq s$ is positive. Roughly speaking, the value of $\alpha_s$ increases by twice the mean of the amplitudes, while others are reduced. The inversion-about-the-mean can be realized with the sequence of unitary matrices as below:$$H^{\otimes n} \left(2|0\rangle \langle 0 | - I \right) H^{\otimes n}$$The first and last $H$ are just Hadamard gates applied to each qubit. The operation in the middle requires us to design a sub-circuit that flips the probability amplitude of the component of the quantum state corresponding to the all-zero binary string. The sub-circuit can be realized by the following function, which is a multi-qubit controlled-Z which flips the probability amplitude of the component of the quantum state corresponding to the all-one binary string. Applying X gates to all qubits before and after the function realizes the sub-circuit.<jupyter_code>def n_controlled_Z(circuit, controls, target): """Implement a Z gate with multiple controls""" if (len(controls) > 2): raise ValueError('The controlled Z with more than 2 ' + 'controls is not implemented') elif (len(controls) == 1): circuit.h(target) circuit.cx(controls[0], target) circuit.h(target) elif (len(controls) == 2): circuit.h(target) circuit.ccx(controls[0], controls[1], target) circuit.h(target) # -- end function<jupyter_output><empty_output><jupyter_text>Finally, the inversion-about-the-mean circuit can be realized by the following function:<jupyter_code>def inversion_about_mean(circuit, f_in, n): """Apply inversion about the mean step of Grover's algorithm.""" # Hadamards everywhere for j in range(n): circuit.h(f_in[j]) # D matrix: flips the sign of the state |000> only for j in range(n): circuit.x(f_in[j]) n_controlled_Z(circuit, [f_in[j] for j in range(n-1)], f_in[n-1]) for j in range(n): circuit.x(f_in[j]) # Hadamards everywhere again for j in range(n): circuit.h(f_in[j]) # -- end function<jupyter_output><empty_output><jupyter_text>Here is a circuit of the inversion about the mean on three qubits.<jupyter_code>qr = QuantumRegister(3) qInvAvg = QuantumCircuit(qr) inversion_about_mean(qInvAvg, qr, 3) circuit_drawer(qInvAvg)<jupyter_output><empty_output><jupyter_text>Grover Search: putting all togetherThe complete steps of Grover search is as follow.1. Create the superposition of all possible solutions as the initial state (with working qubits initialized to zero)$$ \sum_{j=0}^{2^{n}-1} \frac{1}{2^n} |j\rangle |0\rangle$$2. Repeat for $T$ times: * Apply the `blackbox` function * Apply the `inversion-about-the-mean` function 3. Measure to obtain the solutionThe code for the above steps is as below:<jupyter_code>""" Grover search implemented in Qiskit. This module contains the code necessary to run Grover search on 3 qubits, both with a simulator and with a real quantum computing device. This code is the companion for the paper "An introduction to quantum computing, without the physics", Giacomo Nannicini, https://arxiv.org/abs/1708.03684. """ def input_state(circuit, f_in, f_out, n): """(n+1)-qubit input state for Grover search.""" for j in range(n): circuit.h(f_in[j]) circuit.x(f_out) circuit.h(f_out) # -- end function # Make a quantum program for the n-bit Grover search. n = 3 # Exactly-1 3-SAT formula to be satisfied, in conjunctive # normal form. We represent literals with integers, positive or # negative, to indicate a Boolean variable or its negation. exactly_1_3_sat_formula = [[1, 2, -3], [-1, -2, -3], [-1, 2, 3]] # Define three quantum registers: 'f_in' is the search space (input # to the function f), 'f_out' is bit used for the output of function # f, aux are the auxiliary bits used by f to perform its # computation. f_in = QuantumRegister(n) f_out = QuantumRegister(1) aux = QuantumRegister(len(exactly_1_3_sat_formula) + 1) # Define classical register for algorithm result ans = ClassicalRegister(n) # Define quantum circuit with above registers grover = QuantumCircuit() grover.add(f_in) grover.add(f_out) grover.add(aux) grover.add(ans) input_state(grover, f_in, f_out, n) T = 2 for t in range(T): # Apply T full iterations black_box_u_f(grover, f_in, f_out, aux, n, exactly_1_3_sat_formula) inversion_about_mean(grover, f_in, n) # Measure the output register in the computational basis for j in range(n): grover.measure(f_in[j], ans[j]) # Execute circuit backend = Aer.get_backend('qasm_simulator') job = execute([grover], backend=backend, shots=1000) result = job.result() # Get counts and plot histogram counts = result.get_counts(grover) visualization.plot_histogram(counts)<jupyter_output><empty_output><jupyter_text>Running the circuit in real devicesWe have seen that the simulator can find the solution to the combinatorial problem. We would like to see what happens if we use the real quantum devices that have noise and imperfect gates. However, due to the restriction on the length of strings that can be sent over the network to the real devices (there are more than sixty thousands charactes of QASM of the circuit), at the moment the above circuit cannot be run on real-device backends. We can see the compiled QASM on real-device `ibmqx5` backend as follows.<jupyter_code>IBMQ.load_accounts() # get ibmq_16_rueschlikon configuration and coupling map backend = IBMQ.get_backend('ibmq_16_melbourne') backend_config = backend.configuration() backend_coupling = backend_config['coupling_map'] # compile the circuit for ibmq_16_rueschlikon grover_compiled = compile(grover, backend=backend, coupling_map=backend_coupling, seed=1) grover_compiled_qasm = grover_compiled.experiments[0].header.compiled_circuit_qasm print("Number of gates for", backend.name(), "is", len(grover_compiled_qasm.split("\n")) - 4)<jupyter_output>Number of gates for ibmq_16_melbourne is 1982<jupyter_text>The number of gates is in the order of thousands which is above the limits of decoherence time of the current near-term quantum computers. It is a challenge to design a quantum circuit for Grover search to solve large optimization problems. Free flowIn addition to using too many gates, the circuit in this notebook uses auxiliary qubits. It is left as future work to improve the efficiency of the circuit as to make it possible to run it in the real devices. Below is the original circuit.<jupyter_code>circuit_drawer(grover)<jupyter_output><empty_output>
Teach-Me-Quantum/Week 6 - Quantum Search/exercises/w6_01.ipynb/0
{ "file_path": "Teach-Me-Quantum/Week 6 - Quantum Search/exercises/w6_01.ipynb", "repo_id": "Teach-Me-Quantum", "token_count": 5783 }
11
# Exercises * [Jupyter notebook 1 with tutorial](w7_01.ipynb): understanding the Quantum Fourier Transform on its own (this one is optional as it is very math-heavy for some students) * [Jupyter notebook 2 with tutorial](w7_02.ipynb): understanding Shor's Algorithm step by step
Teach-Me-Quantum/Week 7 - Quantum Factorization/exercises/README.md/0
{ "file_path": "Teach-Me-Quantum/Week 7 - Quantum Factorization/exercises/README.md", "repo_id": "Teach-Me-Quantum", "token_count": 81 }
12
# Exercises * [Jupyter notebook 1 with tutorial](w8_01.ipynb): Grover's algorithm (High Level Quantum) * [Jupyter notebook 2 with tutorial](w8_02.ipynb): Support Vector Machine for classification of Breast Cancer datapoints (AI) * [Jupyter notebook 3 with tutorial](w8_03.ipynb): Maximum Cut problem (Optimization) * [Jupyter notebook 4 with tutorial](w8_04.ipynb): Traveling Salesman problem (Optimization) * [Jupyter notebook 5 with tutorial](w8_05.ipynb): Ground state oh H2 Molecule (Chemistry)
Teach-Me-Quantum/Week 8 - High Level Quantum Programming/exercises/README.md/0
{ "file_path": "Teach-Me-Quantum/Week 8 - High Level Quantum Programming/exercises/README.md", "repo_id": "Teach-Me-Quantum", "token_count": 163 }
13
# Utils This folder contains useful scripts and files to speed up the process of updating the slides and exercises. Current contents include: * [replicate_macros.bat](replicate_macros.bat) [windows] copy the [macros.sty](macros.sty) in this folder to all the weeks' latex folders * [replicate_macros.sh](replicate_macros.sh) [linux] copy the [macros.sty](macros.sty) in this folder to all the weeks' latex folders * [macros.sty](macros.sty) the current macros file in used, should be updated as needed and replicated with the above files
Teach-Me-Quantum/utils/README.md/0
{ "file_path": "Teach-Me-Quantum/utils/README.md", "repo_id": "Teach-Me-Quantum", "token_count": 151 }
14
# Qiskit Advocate ### Credential Description This credential is for those that have a deep level of understanding with Qiskit including circuits, algorithms, simulators, qubits and noise. Through their contributions to the Qiskit and the quantum community, this individual has demonstrated an ability and commitment to educate and influence others by sharing ideas, knowledge and expertise in the field of quantum computing. ### Badge Description The badge earner has successfully completed the Qiskit Advocate exam, made significant contirbutions to the Qiskit code and the quantum community, as well as submitted an application. ### Additional Information Duration: Approx 200 hours Learning Link: [https://www.ibm.com/training/badge/qiskit-advocate](https://www.ibm.com/training/badge/qiskit-advocate) Credly Acclaim Link: [https://www.credly.com/org/ibm/badge/qiskit-advocate](https://www.credly.com/org/ibm/badge/qiskit-advocate) Badge Contact: Qiskit Advocate Squad ([[email protected]](mailto:[email protected])) **Credly Support**: For questions related to your Credly badge earner account and profile, as well as issues related to claiming your badge after receiving a notification, go to [https://support.credly.com](https://support.credly.com) NOTICE: IBM leverages the services of Credly, a 3rd party data processor authorized by IBM and located in the United States, to assist in the administration of the IBM Digital Badge program. In order to issue you an IBM Digital Badge, your personal information (name, email address, and badge earned) will be shared with Credly. You will receive an email notification from Credly with instructions for claiming the badge. Your personal information is used to issue your badge and for program reporting and operational purposes. IBM may share the personal information collected with IBM subsidiaries and third parties globally. It will be handled in a manner consistent with IBM privacy practices. The IBM Privacy Statement can be viewed here: [https://www.ibm.com/privacy/us/en/](https://www.ibm.com/privacy/us/en/). IBM employees can view the IBM Internal Privacy Statement here: [https://w3.ibm.com/w3publisher/w3-privacy-notice](https://w3.ibm.com/w3publisher/w3-privacy-notice).
application-guide/docs/README.md/0
{ "file_path": "application-guide/docs/README.md", "repo_id": "application-guide", "token_count": 584 }
15
# Configuration file for the Sphinx documentation builder. # # This file only contains a selection of the most common options. For a full # list see the documentation: # https://www.sphinx-doc.org/en/master/usage/configuration.html # -- Path setup -------------------------------------------------------------- # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. # import datetime import os import shutil import sys import pybtex.style.formatting import pybtex.style.formatting.unsrt import pybtex.style.template from pybtex.plugin import register_plugin as pybtex_register_plugin sys.path.insert(0, os.path.abspath(".")) sys.path.insert(0, os.path.abspath("..")) sys.path.insert(0, os.path.abspath("../../")) # -- Project information ----------------------------------------------------- project = "Mitiq" copyright = f"2020 - {datetime.date.today().year}, Tech Team @ Unitary Fund" author = "Tech Team @ Unitary Fund" # The full version, including alpha/beta/rc tags directory_of_this_file = os.path.dirname(os.path.abspath(__file__)) with open(f"{directory_of_this_file}/../../VERSION.txt", "r") as f: release = f.read().strip() sys.path.append(os.path.abspath("sphinxext")) JUPYTER_EXECUTE_PATH = "../jupyter_execute" def add_notebook_link_to_context_if_exists(app, pagename, context): nb_filename = pagename + ".ipynb" nb_exists = os.path.exists( os.path.join(app.outdir, JUPYTER_EXECUTE_PATH, nb_filename) ) context["notebook_link"] = nb_filename if nb_exists else None def handle_page_context(app, pagename, templatename, context, doctree): add_notebook_link_to_context_if_exists(app, pagename, context) def move_notebook_dir(app): source_dir = os.path.join(app.outdir, JUPYTER_EXECUTE_PATH) target_dir = os.path.join(app.outdir, ".") if os.path.exists(source_dir): shutil.copytree(source_dir, target_dir, dirs_exist_ok=True) print(f"Copied Jupyter execution files to {target_dir}") else: print("No Jupyter execution files found to copy.") def handle_build_finished(app, exception): if exception is None: # Only proceed if the build completed successfully move_notebook_dir(app) def setup(app): app.connect("html-page-context", handle_page_context) app.connect("build-finished", handle_build_finished) # -- General configuration --------------------------------------------------- # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ "myst_nb", "sphinx.ext.mathjax", "IPython.sphinxext.ipython_console_highlighting", "IPython.sphinxext.ipython_directive", "matplotlib.sphinxext.plot_directive", "sphinx.ext.napoleon", "sphinx.ext.autodoc", "sphinx.ext.autosummary", "sphinx_autodoc_typehints", # after napoleon and autodoc "sphinx.ext.todo", "sphinx.ext.extlinks", "sphinx.ext.intersphinx", "sphinx.ext.viewcode", "sphinx.ext.ifconfig", "sphinxcontrib.bibtex", "sphinx_copybutton", "nbsphinx", "sphinx_gallery.load_style", "sphinx_design", "sphinx_tags", ] # to add tags to the documentation tutorials tags_create_tags = True tags_output_dir = "tags/" tags_overview_title = "All tags" tags_create_badges = True tags_intro_text = "Tags on this page: " tags_page_title = "Tags" tags_page_header = "Pages with this tag: " tags_index_head = "Tags in the documentation tutorials: " tags_extension = ["md"] tags_badge_colors = { "zne": "primary", "rem": "primary", "shadows": "primary", "cdr": "primary", "pec": "primary", "ddd": "primary", "calibration": "primary", "cirq": "secondary", "bqskit": "secondary", "braket": "secondary", "pennylane": "secondary", "qiskit": "secondary", "stim": "secondary", "qrack": "secondary", "qibo": "secondary", "ionq": "secondary", "basic": "success", "intermediate": "success", "advanced": "success", } # hide primary sidebar from the following pages html_sidebars = {"apidoc": [], "changelog": [], "bibliography": []} intersphinx_mapping = { "python": ("https://docs.python.org/3.10", None), "numpy": ("https://numpy.org/doc/stable/", None), "scipy": ("https://docs.scipy.org/doc/scipy/", None), # Cirq is no longer using sphinx docs so interlinking is not possible. # "cirq": ("https://quantumai.google/cirq", None), "pyquil": ("https://pyquil-docs.rigetti.com/en/stable/", None), "qiskit": ("https://docs.quantum.ibm.com/api/qiskit/", None), # TODO: qutip docs moved and the objects.inv file not yet found # "qutip": ("https://qutip.org/docs/latest/", None), } # Add any paths that contain templates here, relative to this directory. templates_path = ["_templates"] # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. # # This is also used if you do content translation via gettext catalogs. # Usually you set "language" from the command line for these cases. language = "en" # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. # This pattern also affects html_static_path and html_extra_path. exclude_patterns = [] # The master toctree document. master_doc = "index" # -- Options for myst_parser ------------------------------------------------- # Specifies which of the parsers should handle each file extension. source_suffix = { ".md": "myst-nb", ".ipynb": "myst-nb", } # Enables extensions to MyST parser that allows for richer markup options. # For more info on these, see: # https://myst-parser.readthedocs.io/en/latest/using/syntax-optional.html myst_enable_extensions = [ "amsmath", "colon_fence", "deflist", "dollarmath", "html_image", "smartquotes", ] myst_heading_anchors = 4 # Tells MyST to treat URIs beginning with these prefixes as external links. # Links that don't begin with these will be treated as internal cross-links. myst_url_schemes = ("http", "https", "mailto") # -- Options for myst_nb ----------------------------------------------------- # How long should Sphinx wait while a notebook is being evaluated before # quitting. nb_execution_timeout = 600 # By default, if nothing has changed in the source, a notebook won't be # re-run for a subsequent docs build. nb_execution_mode = "cache" # If SKIP_PYQUIL is True, do not re-run PyQuil notebooks. if os.environ.get("SKIP_PYQUIL"): print("Skipping PyQuil notebooks execution since SKIP_PYQUIL is True") nb_execution_excludepatterns = ["*pyquil*.ipynb"] # -- Options for autodoc ----------------------------------------------------- napoleon_google_docstring = True napoleon_use_ivar = True autodoc_mock_imports = [ "pyquil", ] # autodoc-typehints extension setting typehints_fully_qualified = False always_document_param_types = True set_type_checking_flag = False typehints_document_rtype = True # -- Options for Sphinxcontrib-bibtex ---------------------------------------- pybtex.style.formatting.unsrt.date = pybtex.style.template.words(sep="")[ "(", pybtex.style.template.field("year"), ")" ] bibtex_bibfiles = ["refs.bib"] # Links matching with the following regular expressions will be ignored linkcheck_ignore = [ r"https://arxiv\.org/.*", r"https://doi\.org/.*", r"https://link\.aps\.org/doi/.*", r"https://www\.sciencedirect\.com/science/article/.*", r"https://github.com/unitaryfund/mitiq/compare/.*", ] linkcheck_retries = 3 linkcheck_anchors_ignore_for_url = [ "https://github.com/unitaryfund/qrack/blob/main/README.md" ] class ApsStyle(pybtex.style.formatting.unsrt.Style): """Style that mimicks APS journals.""" def __init__( self, label_style=None, name_style=None, sorting_style=None, abbreviate_names=True, min_crossrefs=2, **kwargs, ): super().__init__( label_style=label_style, name_style=name_style, sorting_style=sorting_style, abbreviate_names=abbreviate_names, min_crossrefs=min_crossrefs, **kwargs, ) def format_title(self, e, which_field, as_sentence=True): """Set titles in italics.""" formatted_title = pybtex.style.template.field( which_field, apply_func=lambda text: text.capitalize() ) formatted_title = pybtex.style.template.tag("em")[formatted_title] if as_sentence: return pybtex.style.template.sentence[formatted_title] else: return formatted_title def get_article_template(self, e): volume_and_pages = pybtex.style.template.first_of[ # volume and pages pybtex.style.template.optional[ pybtex.style.template.join[ " ", pybtex.style.template.tag("strong")[ pybtex.style.template.field("volume") ], ", ", pybtex.style.template.field( "pages", apply_func=pybtex.style.formatting.unsrt.dashify, ), ], ], # pages only pybtex.style.template.words[ "pages", pybtex.style.template.field( "pages", apply_func=pybtex.style.formatting.unsrt.dashify ), ], ] template = pybtex.style.formatting.toplevel[ self.format_names("author"), self.format_title(e, "title"), pybtex.style.template.sentence(sep=" ")[ pybtex.style.template.field("journal"), pybtex.style.template.optional[volume_and_pages], pybtex.style.formatting.unsrt.date, ], self.format_web_refs(e), ] return template def get_book_template(self, e): template = pybtex.style.formatting.toplevel[ self.format_author_or_editor(e), self.format_btitle(e, "title"), self.format_volume_and_series(e), pybtex.style.template.sentence(sep=" ")[ pybtex.style.template.sentence(add_period=False)[ pybtex.style.template.field("publisher"), pybtex.style.template.optional_field("address"), self.format_edition(e), ], pybtex.style.formatting.unsrt.date, ], pybtex.style.template.optional[ pybtex.style.template.sentence[self.format_isbn(e)] ], pybtex.style.template.sentence[ pybtex.style.template.optional_field("note") ], self.format_web_refs(e), ] return template def get_incollection_template(self, e): template = pybtex.style.formatting.toplevel[ pybtex.style.template.sentence[self.format_names("author")], self.format_title(e, "title"), pybtex.style.template.words[ "In", pybtex.style.template.sentence[ pybtex.style.template.optional[ self.format_editor(e, as_sentence=False) ], self.format_btitle(e, "booktitle", as_sentence=False), self.format_volume_and_series(e, as_sentence=False), self.format_chapter_and_pages(e), ], ], pybtex.style.template.sentence(sep=" ")[ pybtex.style.template.sentence(add_period=False)[ pybtex.style.template.optional_field("publisher"), pybtex.style.template.optional_field("address"), self.format_edition(e), ], pybtex.style.formatting.unsrt.date, ], self.format_web_refs(e), ] return template pybtex_register_plugin("pybtex.style.formatting", "apsstyle", ApsStyle) # -- Options for other extensions -------------------------------------------- # The name of the Pygments (syntax highlighting) style to use. pygments_style = "sphinx" # If true, `todo` and `todoList` produce output, else they produce nothing. todo_include_todos = False # -- Options for HTML output ------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. # html_theme = "pydata_sphinx_theme" # 'alabaster', 'sphinx_rtd_theme' # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ["_thumbnails"] # display logo on top-left of html pages html_logo = "img/mitiq-logo.png" html_favicon = "img/mitiq.ico" # Add extra paths that contain custom files here, relative to this directory. # These files are copied directly to the root of the documentation. html_extra_path = ["robots.txt"] html_theme_options = { "icon_links": [ { "name": "Source Repository", "url": "https://github.com/unitaryfund/mitiq", "icon": "fa-brands fa-github", "type": "fontawesome", } ], "secondary_sidebar_items": ["page-toc", "sourcelink", "notebook-download"], } myst_update_mathjax = False nbsphinx_custom_formats = { ".mystnb": ["jupytext.reads", {"fmt": "mystnb"}], } nbsphinx_execute = "always" nbsphinx_thumbnails = { "examples/qibo-noisy-simulation": "_static/qibo-mitiq.png", "examples/hamiltonians": "_static/vqe-cirq-pauli-sum-mitigation-plot.png", "examples/braket_mirror_circuit": "_static/mirror-circuits.png", "examples/maxcut-demo": "_static/max-cut.png", "examples/layerwise-folding": "_static/layerwise.png", "examples/cirq-ibmq-backends": "_static/cirq-mitiq-ibmq.png", "examples/pennylane-ibmq-backends": "_static/zne-pennylane.png", "examples/ibmq-backends": "_static/ibmq-gate-map.png", "examples/simple-landscape-cirq": "_static/simple-landscape-cirq.png", "examples/simple-landscape-braket": "_static/simple-landscape-braket.png", "examples/molecular_hydrogen": "_static/molecular-hydrogen-vqe.png", "examples/molecular_hydrogen_pennylane": "_static/mol-h2-vqe-pl.png", "examples/vqe-pyquil-demo": "_static/vqe-pyquil-demo.png", "examples/pyquil_demo": "_static/pyquil-demo.png", "examples/mitiq-paper/*": "_static/mitiq-codeblocks.png", "examples/zne-braket-ionq": "_static/zne-braket-ionq.png", "examples/bqskit": "_static/bqskit.png", "examples/simple-landscape-qiskit": "_static/simple-landscape-qiskit.png", "examples/simple-landscape-pennylane": "_static/simple-landscape-pln.png", "examples/learning-depolarizing-noise": "_static/learn-depolarizing.png", "examples/pec_tutorial": "_static/pec-tutorial.png", "examples/scaling": "_static/scaling.png", "examples/shadows_tutorial": "_static/shadow-tutorial.png", "examples/rshadows_tutorial": "_static/rshadow_protocol.png", "examples/ddd_tutorial": "_static/ddd-tutorial.png", "examples/ddd_on_ibmq_ghz": "_static/ddd_qiskit_ghz_plot.png", "examples/calibration-tutorial": "_static/calibration.png", "examples/combine_rem_zne": "_static/combine_rem_zne.png", "examples/quantum_simulation_scars_ibmq": "_static/qmbs_ibmq.png", "examples/zne_logical_rb_cirq_stim": "_static/mitiq_stim_logo.png", "examples/quantum_simulation_1d_ising": "_static/quantum_simulation.png", "examples/cdr_qrack": "_static/cdr-qrack.png", # default images if no thumbnail is specified "examples/*": "_static/mitiq-logo.png", }
mitiq/docs/source/conf.py/0
{ "file_path": "mitiq/docs/source/conf.py", "repo_id": "mitiq", "token_count": 6776 }
16
--- jupytext: text_representation: extension: .md format_name: myst format_version: 0.13 jupytext_version: 1.16.1 kernelspec: display_name: Python 3 (ipykernel) language: python name: python3 --- ```{tags} qiskit, zne, basic ``` # Error mitigation on IBMQ backends with Qiskit This tutorial shows an example of how to mitigate noise on IBMQ backends. ## Settings ```{code-cell} ipython3 import qiskit from qiskit_aer import QasmSimulator from qiskit_ibm_runtime import QiskitRuntimeService from mitiq import zne from mitiq.interface.mitiq_qiskit.qiskit_utils import initialized_depolarizing_noise ``` **Note:** If `USE_REAL_HARDWARE` is set to `False`, a classically simulated noisy backend is used instead of a real quantum computer. ```{code-cell} ipython3 USE_REAL_HARDWARE = False ``` ## Setup: Defining a circuit +++ For simplicity, we'll use a random single-qubit circuit with ten gates that compiles to the identity, defined below. ```{code-cell} ipython3 qreg, creg = qiskit.QuantumRegister(1), qiskit.ClassicalRegister(1) circuit = qiskit.QuantumCircuit(qreg, creg) for _ in range(10): circuit.x(qreg) circuit.measure(qreg, creg) print(circuit) ``` We will use the probability of the ground state as our observable to mitigate, the expectation value of which should evaluate to one in the noiseless setting. ## High-level usage To use Mitiq with just a few lines of code, we simply need to define a function which inputs a circuit and outputs the expectation value to mitigate. This function will: 1. [Optionally] Add measurement(s) to the circuit. 2. Run the circuit. 3. Convert from raw measurement statistics (or a different output format) to an expectation value. We define this function in the following code block. Because we are using IBMQ backends, we first load our account. +++ **Note:** Using an IBM quantum computer requires a valid IBMQ account. See <https://quantum-computing.ibm.com/> for instructions to create an account, save credentials, and see online quantum computers. ```{code-cell} ipython3 if QiskitRuntimeService.saved_accounts() and USE_REAL_HARDWARE: service = QiskitRuntimeService() backend = service.least_busy(operational=True, simulator=False) noise_model = False else: # Simulate the circuit with noise noise_model = initialized_depolarizing_noise(noise_level=0.02) # Default to a simulator backend = QasmSimulator(noise_model=noise_model) def ibmq_executor(circuit: qiskit.QuantumCircuit, shots: int = 8192) -> float: """Returns the expectation value to be mitigated. Args: circuit: Circuit to run. shots: Number of times to execute the circuit to compute the expectation value. """ # Transpile the circuit so it can be properly run exec_circuit = qiskit.transpile( circuit, backend=backend, basis_gates=noise_model.basis_gates if noise_model else None, optimization_level=0, # Important to preserve folded gates. ) # Run the circuit job = backend.run(exec_circuit, shots=shots) # Convert from raw measurement counts to the expectation value counts = job.result().get_counts() if counts.get("0") is None: expectation_value = 0. else: expectation_value = counts.get("0") / shots return expectation_value ``` At this point, the circuit can be executed to return a mitigated expectation value by running {func}`zne.execute_with_zne`, as follows. ```{code-cell} ipython3 unmitigated = ibmq_executor(circuit) mitigated = zne.execute_with_zne(circuit, ibmq_executor) print(f"Unmitigated result {unmitigated:.3f}") print(f"Mitigated result {mitigated:.3f}") ``` As long as a circuit and a function for executing the circuit are defined, the {func}`zne.execute_with_zne` function can be called as above to return zero-noise extrapolated expectation value(s). ## Options Different options for noise scaling and extrapolation can be passed into the {func}`zne.execute_with_zne` function. By default, noise is scaled by locally folding gates at random, and the default extrapolation is Richardson. To specify a different extrapolation technique, we can pass a different {class}`.Factory` object to {func}`zne.execute_with_zne`. The following code block shows an example of using linear extrapolation with five different (noise) scale factors. ```{code-cell} ipython3 linear_factory = zne.inference.LinearFactory(scale_factors=[1.0, 1.5, 2.0, 2.5, 3.0]) mitigated = zne.execute_with_zne(circuit, ibmq_executor, factory=linear_factory) print(f"Mitigated result {mitigated:.3f}") ``` To specify a different noise scaling method, we can pass a different function for the argument ``scale_noise``. This function should input a circuit and scale factor and return a circuit. The following code block shows an example of scaling noise by global folding (instead of local folding, the default behavior for {func}`zne.execute_with_zne`). ```{code-cell} ipython3 mitigated = zne.execute_with_zne(circuit, ibmq_executor, scale_noise=zne.scaling.fold_global) print(f"Mitigated result {mitigated:.3f}") ``` Any different combination of noise scaling and extrapolation technique can be passed as arguments to {func}`zne.execute_with_zne`. ## Lower-level usage Here, we give more detailed usage of the Mitiq library which mimics what happens in the call to {func}`zne.execute_with_zne` in the previous example. In addition to showing more of the Mitiq library, this example explains the code in the previous section in more detail. First, we define factors to scale the circuit length by and fold the circuit using the ``fold_gates_at_random`` local folding method. ```{code-cell} ipython3 scale_factors = [1., 1.5, 2., 2.5, 3.] folded_circuits = [ zne.scaling.fold_gates_at_random(circuit, scale) for scale in scale_factors ] # Check that the circuit depth is (approximately) scaled as expected for j, c in enumerate(folded_circuits): print(f"Number of gates of folded circuit {j} scaled by: {len(c) / len(circuit):.3f}") ``` For a noiseless simulation, the expectation of this observable should be 1.0 because our circuit compiles to the identity. For a noisy simulation, the value will be smaller than one. Because folding introduces more gates and thus more noise, the expectation value will decrease as the length (scale factor) of the folded circuits increase. By fitting this to a curve, we can extrapolate to the zero-noise limit and obtain a better estimate. Below we execute the folded circuits using the ``backend`` defined at the start of this example. ```{code-cell} ipython3 shots = 8192 # Transpile the circuit so it can be properly run exec_circuit = qiskit.transpile( folded_circuits, backend=backend, basis_gates=noise_model.basis_gates if noise_model else None, optimization_level=0, # Important to preserve folded gates. ) # Run the circuit job = backend.run(exec_circuit, shots=shots) ``` **Note:** We set the ``optimization_level=0`` to prevent any compilation by Qiskit transpilers. Once the job has finished executing, we can convert the raw measurement statistics to observable values by running the following code block. ```{code-cell} ipython3 all_counts = [job.result().get_counts(i) for i in range(len(folded_circuits))] expectation_values = [counts.get("0") / shots for counts in all_counts] print(f"Expectation values:\n{expectation_values}") ``` We can now see the unmitigated observable value by printing the first element of ``expectation_values``. (This value corresponds to a circuit with scale factor one, i.e., the original circuit.) ```{code-cell} ipython3 print("Unmitigated expectation value:", round(expectation_values[0], 3)) ``` Now we can use the static ``extrapolate`` method of {class}`zne.inference.Factory` objects to extrapolate to the zero-noise limit. Below we use an exponential fit and print out the extrapolated zero-noise value. ```{code-cell} ipython3 zero_noise_value = zne.ExpFactory.extrapolate(scale_factors, expectation_values, asymptote=0.5) print(f"Extrapolated zero-noise value:", round(zero_noise_value, 3)) ```
mitiq/docs/source/examples/ibmq-backends.md/0
{ "file_path": "mitiq/docs/source/examples/ibmq-backends.md", "repo_id": "mitiq", "token_count": 2593 }
17
--- jupytext: text_representation: extension: .md format_name: myst format_version: 0.13 jupytext_version: 1.11.4 kernelspec: display_name: Python 3 language: python name: python3 --- # An example Jupyter Notebook This notebook is a demonstration of directly-parsing Jupyter Notebooks into Sphinx using the MyST parser. ## Markdown ### Configuration https://myst-parser.readthedocs.io/en/latest/using/intro.html#getting-started To build documentation from this notebook, the following options are set: ```python myst_enable_extensions = [ "amsmath", "colon_fence", "deflist", "dollarmath", "html_image", ] myst_url_schemes = ("http", "https", "mailto") ``` ### Syntax As you can see, markdown is parsed as expected. Embedding images should work as expected. For example, here's the MyST-NB logo: ```md ![myst-nb logo](../img/unitary_fund_logo.png) ``` ![myst-nb logo](../img/unitary_fund_logo.png) By adding `"html_image"` to the `myst_enable_extensions` list in the sphinx configuration ([see here](https://myst-parser.readthedocs.io/en/latest/syntax/optional.html#html-images)), you can even add HTML `img` tags with attributes: ```html <img src="../img/unitary_fund_logo.png" alt="logo" width="200px" class="shadow mb-2"> ``` <img src="../img/unitary_fund_logo.png" alt="logo" width="200px" class="shadow mb-2"> Because MyST-NB is using the MyST-markdown parser, you can include rich markdown with Sphinx in your notebook. For example, here's a note admonition block: :::::{note} **Wow**, a note! It was generated with this code ([as explained here](https://myst-parser.readthedocs.io/en/latest/syntax/optional.html#html-admonitions)): ````md :::{note} **Wow**, a note! ::: ```` ::::: If you wish to use "bare" LaTeX equations, then you should add `"amsmath"` to the `myst_enable_extensions` list in the sphinx configuration. This is [explained here](https://myst-parser.readthedocs.io/en/latest/syntax/optional.html#direct-latex-math), and works as such: ```latex \begin{equation} \frac {\partial u}{\partial x} + \frac{\partial v}{\partial y} = - \, \frac{\partial w}{\partial z} \end{equation} \begin{align*} 2x - 5y &= 8 \\ 3x + 9y &= -12 \end{align*} ``` \begin{equation} \frac {\partial u}{\partial x} + \frac{\partial v}{\partial y} = - \, \frac{\partial w}{\partial z} \end{equation} \begin{align*} 2x - 5y &= 8 \\ 3x + 9y &= -12 \end{align*} Also you can use features like **equation numbering** and referencing in the notebooks: ```md $$e^{i\pi} + 1 = 0$$ (euler) ``` $$e^{i\pi} + 1 = 0$$ (euler) Euler's identity, equation {math:numref}`euler`, was elected one of the most beautiful mathematical formulas. You can see the syntax used for this example [here in the MyST documentation](https://myst-parser.readthedocs.io/en/latest/syntax/syntax.html). ## Code cells and outputs You can run cells, and the cell outputs will be captured and inserted into the resulting Sphinx site. ### `__repr__` and HTML outputs For example, here's some simple Python: ```{code-cell} ipython3 import matplotlib.pyplot as plt import numpy as np data = np.random.rand(3, 100) * 100 data[:, :10] ``` This will also work with HTML outputs ```{code-cell} ipython3 import pandas as pd df = pd.DataFrame(data.T, columns=['a', 'b', 'c']) df.head() ``` as well as math outputs ```{code-cell} ipython3 from IPython.display import Math Math(r"\sum_{i=0}^n i^2 = \frac{(n^2+n)(2n+1)}{6}") ``` This works for error messages as well: ```{code-cell} ipython3 :tags: [raises-exception] print("This will be properly printed...") print(thiswont) ``` ### Images Images that are generated from your code (e.g., with Matplotlib) will also be embedded. ```{code-cell} ipython3 fig, ax = plt.subplots() ax.scatter(*data, c=data[2]) ``` ## Thumbnail for the Notebook To add a thumbnail for an example notebook, first add the thumbnail image file to `docs/source/_thumbnails`. Next, modify the `docs/source/conf.py` to include the example and thumbnail in the nbsphinx_thumbnails dictionary at the end of the file. The sample below contains both a generic template and an actual example. ```{code-cell} ipython3 nbsphinx_thumbnails = { "examples/{EXAMPLE_FILENAME_WITHOUT_.md}": "_static/{THUMBNAIL_FILENAME_WITH_EXTENSION}", "examples/hamiltonians": "_static/vqe-cirq-pauli-sum-mitigation-plot.png" } ```
mitiq/docs/source/examples/template.md/0
{ "file_path": "mitiq/docs/source/examples/template.md", "repo_id": "mitiq", "token_count": 1607 }
18
--- jupytext: text_representation: extension: .md format_name: myst format_version: 0.13 jupytext_version: 1.11.1 kernelspec: display_name: Python 3 language: python name: python3 --- # What is the theory behind DDD? Dynamical decoupling (DD) {cite}`Viola_1998_PRA, Viola_1999_PRL, Zhang_2014_PRL` is a quantum control technique to effectively reduce the interaction of a quantum system with its environment. The protocol works by driving a quantum system with rapid sequences of periodic control pulses. The application of DD sequences can have two effects depending on the correlation time {cite}`Breuer_2007_Oxford` of the environment: 1. For Markovian noise, DD can make the overall quantum channel more symmetric (analogous to quantum twirling {cite}`Wallman_2016_PRA`) but cannot actually decouple the system from the environment; 2. For non-Markovian noise, DD can effectively decouple the system from the environment. In theory, ideal sequences of infinitely quick and strong pulses, can result in complete noise suppression. In practice, due to the finite frequency and finite amplitude of DD sequences, both effects are possible but only as imperfect approximations. In the context of quantum computing, DD can be considered as an error mitigation method. With respect to other error mitigation techniques, DD has very peculiar features: - It maps a noisy quantum computation to a _single_ error-mitigated computation (no need to take linear combinations of noisy results as in [ZNE](zne-5-theory.md), [PEC](pec-5-theory.md), and [CDR](cdr-5-theory.md)). - As a consequence of the previous point, there is not a fundamental error mitigation overhead or increase in statistical uncertainty in the final result. - If noise is time-correlated, it can suppress real errors at the physical level instead of applying a virtual noise reduction via classical post-processing. ## Digital dynamical decoupling In a quantum computing device based on the circuit model, sequences of DD pulses can be mapped to sequences of discrete quantum gates (typically Pauli gates). We refer to this gate-level formulation as _digital dynamical decoupling_ (DDD) to distinguish it from the standard pulse-level formulation. ```{note} This type of gate-level approach is very similar to the gate-level abstraction used in Mitiq to implement _digital zero-noise extrapolation_ via _unitary folding_ (see [What is the theory behind ZNE?](zne-5-theory.md)). ``` Experimental evidence showing the practical utility gate-level decoupling sequences is given in several publications {cite}`Pokharel_2018_PRL, Jurcevic_2021_arxiv, GoogleQuantum_2021_nature, Smith_2021_arxiv, Das_2021_ACM`. ```{warning} Gate-level DDD can only be considered as an approximation of the ideal (pulse-level) DD technique. Moreover, quantum backends may internally optimize and schedule gates in unpredictable ways such that, in practice, DDD sequences may not be physically applied as expected. ``` A significant advantage of DDD with respect to pulse-level DD is the possibility of defining it in a backend-independent way, via simple transformations of abstract quantum circuits. For this reason, DDD is particularly suitable for a multi-platform library like Mitiq. ## Common examples of DDD sequences Common dynamical decoupling sequences are arrays of (evenly spaced) Pauli gates. In particular: - The _XX_ sequence is typically appropriate for mitigating (time-correlated) dephasing noise; - The _YY_ sequence is typically appropriate for mitigating (time-correlated) amplitude damping noise; - The _XYXY_ sequence is typically appropriate for mitigating generic single-qubit noise. ```{note} A general property of DDD sequences is that, if executed on a noiseless backend, they are equivalent to the identity operation. ``` All the above examples of DDD sequences are supported in Mitiq and more general ones can be defined and customized by users. For more details on how to define DDD sequences in Mitiq see [What additional options are available for DDD?](ddd-3-options.md). In a practical scenario it is hard to characterize the noise model and the noise spectrum of a quantum device and the choice of the optimal sequence is not obvious _a priori_. A possible strategy is to run a few circuits whose noiseless results are theoretically known, such that one can empirically determine what sequence is optimal for a specific backend. It may happen that, for some sequences, the final error of the quantum computation is actually increased. As with all other error-mitigation techniques, one should always take into account that an improvement of performances is not guaranteed.
mitiq/docs/source/guide/ddd-5-theory.md/0
{ "file_path": "mitiq/docs/source/guide/ddd-5-theory.md", "repo_id": "mitiq", "token_count": 1176 }
19
--- jupytext: text_representation: extension: .md format_name: myst format_version: 0.13 jupytext_version: 1.11.1 kernelspec: display_name: Python 3 (ipykernel) language: python name: python3 --- # What additional options are available when using PT? ```{admonition} Warning: Pauli Twirling in Mitiq is still under construction. This users guide will change in the future after some utility functions are introduced. ``` Currently Pauli Twirling is designed to have relatively few options, in part to make it readily composable with every other Mitiq technique. In the future, we expect a possibility of supporting additional operations as targets (beyond CZ and CNOT gates), with more customization on picking those targets. Stay tuned!
mitiq/docs/source/guide/pt-3-options.md/0
{ "file_path": "mitiq/docs/source/guide/pt-3-options.md", "repo_id": "mitiq", "token_count": 212 }
20
--- jupytext: text_representation: extension: .md format_name: myst format_version: 0.13 jupytext_version: 1.11.1 kernelspec: display_name: Python 3 (ipykernel) language: python name: python3 --- ```{admonition} Note: The documentation for Classical Shadows in Mitiq is still under construction. This users guide will change in the future. ``` # How Do I Use Classical Shadows Estimation? The `mitiq.shadows` module facilitates the application of the classical shadows protocol on quantum circuits, designed for tasks like quantum state tomography or expectation value estimation. In addition this module integrates a robust shadow estimation protocol that's tailored to counteract noise. The primary objective of the classical shadow protocol is to extract information from a quantum state using repeated measurements. The procedure can be broken down as follows: 1. `shadow_quantum_processing`: - Purpose: Execute quantum processing on the provided quantum circuit. - Outcome: Measurement results from the processed circuit. 2. `classical_post_processing`: - Purpose: Handle classical processing of the measurement results. - Outcome: Estimation based on user-defined inputs. For users aiming to employ the robust shadow estimation protocol, an initial step is needed which entails characterizing the noisy quantum channel. This is done by: 0. `pauli_twirling_calibration` - Purpose: Characterize the noisy quantum channel. - Outcome: A dictionary of `calibration_results`. 1. `shadow_quantum_processing`: same as above. 2. `classical_post_processing` - Args: `calibration_results` = output of `pauli_twirling_calibration` - Outcome: Error mitigated estimation based on user-defined inputs. Notes: - The calibration process is specifically designed to mitigate noise encountered during the classical shadow protocol, such as rotation and computational basis measurements. It does not address noise that occurs during state preparation. - Do not need to redo the calibration stage (0. `pauli_twirling_calibration`) if: 1. The input circuit has a consistent number of qubits. 2. The estimated observables have the same or fewer qubit support. ## Protocol Overview The classical shadow protocol aims to create an approximate classical representation of a quantum state using minimal measurements. This approach not only characterizes and mitigates noise effectively but also retains sample efficiency and demonstrates noise resilience. For more details, see the section ([What is the theory behind Classical Shadow Estimation?](shadows-5-theory.md)). One can use the `mitiq.shadows' module as follows. ### User-defined inputs Define a quantum circuit, e.g., a circuit which prepares a GHZ state with $n$ = `3` qubits, ```{code-cell} ipython3 import numpy as np #fix random seed np.random.seed(1) ``` ```{code-cell} ipython3 import cirq qubits = cirq.LineQubit.range(3) num_qubits = len(qubits) circuit = cirq.Circuit( cirq.H(qubits[0]), cirq.CNOT(qubits[0], qubits[1]), cirq.CNOT(qubits[1], qubits[2]), ) print(circuit) ``` Define an executor to run the circuit on a quantum computer or a noisy simulator. Note that the _robust shadow estimation_ technique can only calibrate and mitigate the noise acting on the operations associated to the classical shadow protocol. So, in order to test the technique, we assume that the state preparation part of the circuit is noiseless. In particular, we define an executor in which: 1. A noise channel is added to circuit right before the measurements. I.e. $U_{\Lambda_U}(M_z)_{\Lambda_{\mathcal{M}_Z}}\equiv U\Lambda\mathcal{M}_Z$. 2. A single measurement shot is taken for each circuit, as required by classical shadow protocol. ```{code-cell} ipython3 from mitiq import MeasurementResult def cirq_executor( circuit: cirq.Circuit, noise_model_function=cirq.depolarize, noise_level=(0.2,), sampler=cirq.Simulator(), ) -> MeasurementResult: """ This function returns the measurement outcomes of a circuit with noisy channel added before measurements. Args: circuit: The circuit to execute. Returns: A one shot MeasurementResult object containing the measurement outcomes. """ circuit = circuit.copy() qubits = sorted(list(circuit.all_qubits())) if noise_level[0] > 0: noisy_circuit = cirq.Circuit() operations = list(circuit) n_ops = len(operations) for i, op in enumerate(operations): if i == n_ops - 1: noisy_circuit.append( cirq.Moment( *noise_model_function(*noise_level).on_each(*qubits) ) ) noisy_circuit.append(op) circuit = noisy_circuit executor = cirq_sample_bitstrings( circuit, noise_model_function=None, noise_level=(0,), shots=1, sampler=sampler, ) return executor ``` Given the above general executor, we define a specific example of a noisy executor, assuming a bit flip channel with a probability of `0.1' ```{code-cell} ipython3 from functools import partial noisy_executor = partial( cirq_executor, noise_level=(0.1,), noise_model_function=cirq.bit_flip, ) ``` ### 0. Calibration Stage One can simply skip this stage if one just wants to perform the classical shadow protocol (without calibration). This step can also be skipped if calibration data is already available from previous runs. By setting the total calibration rounds $R$ = `num_total_measurements_calibration` and the number of groups for the "median of means" estimation used for calibration $K$ = `k_calibration`, we can characterize the noisy quantum channel (see [this tutorial](../examples/rshadows_tutorial.md) for more details) by running the following code: ```{code-cell} ipython3 import sys sys.modules["tqdm"] = None # disable tqdm for cleaner notebook rendering from mitiq.shadows import * from mitiq.interface.mitiq_cirq.cirq_utils import ( sample_bitstrings as cirq_sample_bitstrings, ) f_est = pauli_twirling_calibrate( k_calibration=1, locality=2, qubits=qubits, executor=noisy_executor, num_total_measurements_calibration=5000, ) f_est ``` the varible `locality` is the maximum number of qubits on which our operators of interest are acting on. E.g. if our operator is a sequence of two point correlation terms $\{\langle Z_iZ_{i+1}\rangle\}_{0\leq i\leq n-1}$, then `locality` = 2. We note that one could also split the calibration process into two stages: 1. `shadow_quantum_processing` - Outcome: Get quantum measurement result of the calibration circuit $|0\rangle^{\otimes n}$ `zero_state_shadow_outcomes`. 2. `pauli_twirling_calibration` - Outcome: A dictionary of `calibration_results`. For more details, please refer to [this tutorial](../examples/rshadows_tutorial.md) ### 1. Quantum Processing In this step, we obtain classical shadow snapshots from the input state (before applying the invert channel). #### 1.1 Add Rotation Gate and Meausure the Rotated State in Computational Basis At present, the implementation supports random Pauli measurement. This is equivalent to randomly sampling $U$ from the local Clifford group $Cl_2^n$, followed by a $Z$-basis measurement (see [this tutorial](../examples/shadows_tutorial.md) for a clear explanation). #### 1.2 Get the Classical Shadows One can obtain the list of measurement results of local Pauli measurements in terms of bitstrings, and the related Pauli-basis measured in terms of strings as follows. You have two choices: run the quantum measurement or directly use the results from the previous run. - If **True**, the measurement will be run again. - If **False**, the results from the previous run will be used. ```{code-cell} ipython3 import zipfile, pickle, io, requests run_quantum_processing = False run_pauli_twirling_calibration = False file_directory = "../examples/resources" if not run_quantum_processing: saved_data_name = "shadows-1-intro-output1" with open(f"{file_directory}/{saved_data_name}.pkl", "rb") as file: shadow_measurement_output = pickle.load(file) else: shadow_measurement_output = shadow_quantum_processing( circuit, noisy_executor, num_total_measurements_shadow=5000, ) ``` As an example, we print out one of those measurement outcomes and the associated measured operator: ```{code-cell} ipython3 print("one snapshot measurement result = ", shadow_measurement_output[0][0]) print("one snapshot measurement basis = ", shadow_measurement_output[1][0]) ``` ### 2. Classical Post-Processing In this step, we estimate our object of interest (expectation value or density matrix) by post-processing the (previously obtained) measurement outcomes. #### 2.1 Example: Operator Expectation Value Esitimation For example, if we want to estimate the two point correlation function $\{\langle Z_iZ_{i+1}\rangle\}_{0\leq i\leq n-1}$, we will define the corresponding Puali strings: ```{code-cell} ipython3 from mitiq import PauliString two_pt_correlations = [ PauliString("ZZ", support=(i, i + 1), coeff=1) for i in range(0, num_qubits - 1) ] for i in range(0, num_qubits - 1): print(two_pt_correlations[i]._pauli) ``` The corresponding expectation values can be estimated (with and without calibration) as shown in the next code cell. ```{code-cell} ipython3 est_corrs = classical_post_processing( shadow_outcomes=shadow_measurement_output, observables=two_pt_correlations, k_shadows=1, ) cal_est_corrs = classical_post_processing( shadow_outcomes=shadow_measurement_output, calibration_results=f_est, observables=two_pt_correlations, k_shadows=1, ) ``` Let's compare the results with the exact theoretical values: ```{code-cell} ipython3 expval_exact = [] state_vector = circuit.final_state_vector() for i, pauli_string in enumerate(two_pt_correlations): exp = pauli_string._pauli.expectation_from_state_vector( state_vector, qubit_map={q: i for i, q in enumerate(qubits)} ) expval_exact.append(exp.real) ``` ```{code-cell} ipython3 print("Classical shadow estimation:", est_corrs) print("Robust shadow estimation :", cal_est_corrs) print( "Exact expectation values:", "'Z(q(0))*Z(q(1))':", expval_exact[0], "'Z(q(1))*Z(q(2))':", expval_exact[1], ) ``` #### 2.2 Example: GHZ State Reconstruction In addition to the estimation of expectation values, the `mitiq.shadow` module can also be used to reconstruct an approximated version of the density matrix. As an example, we use the 3-qubit GHZ circuit, previously defined. As a first step, we calculate the Pauli fidelities $f_b$ characterizing the noisy quantum channel $\mathcal{M}=\sum_{b\in\{0,1\}^n}f_b\Pi_b$: ```{code-cell} ipython3 noisy_executor = partial( cirq_executor, noise_level=(0.2,), noise_model_function=cirq.bit_flip, ) if not run_pauli_twirling_calibration: saved_data_name = "shadows-1-intro-PTC-50000" with open(f"{file_directory}/{saved_data_name}.pkl", "rb") as file: f_est = pickle.load(file) else: f_est = pauli_twirling_calibrate( k_calibration=1, qubits=qubits, executor=noisy_executor, num_total_measurements_calibration=50000 ) f_est ``` Similar to the previous case (estimation of expectation values), the quantum processing for estimating the density matrix is done as follows. ```{code-cell} ipython3 if not run_quantum_processing: saved_data_name = "shadows-1-intro-output2" with open(f"{file_directory}/{saved_data_name}.pkl", "rb") as file: shadow_measurement_output = pickle.load(file) else: shadow_measurement_output = shadow_quantum_processing( circuit, noisy_executor, num_total_measurements_shadow=50000, ) ``` ```{code-cell} ipython3 est_corrs = classical_post_processing( shadow_outcomes=shadow_measurement_output, state_reconstruction=True, ) cal_est_corrs = classical_post_processing( shadow_outcomes=shadow_measurement_output, calibration_results=f_est, state_reconstruction=True, ) ``` Let's compare the fidelity between the reconstructed state and the ideal state. ```{code-cell} ipython3 from mitiq.utils import operator_ptm_vector_rep ghz_state = circuit.final_state_vector().reshape(-1, 1) ghz_true = ghz_state @ ghz_state.conj().T ptm_ghz_state = operator_ptm_vector_rep(ghz_true) ``` ```{code-cell} ipython3 from mitiq.shadows.shadows_utils import fidelity fidelity_shadow = fidelity(ghz_true, est_corrs["reconstructed_state"]) fidelity_shadow_calibrated = fidelity( ptm_ghz_state, cal_est_corrs["reconstructed_state"] ) print( f"fidelity between true state and shadow reconstruced state {fidelity_shadow}" ) print( f"fidelity between true state and rshadow reconstruced state {fidelity_shadow_calibrated}" ) ```
mitiq/docs/source/guide/shadows-1-intro.md/0
{ "file_path": "mitiq/docs/source/guide/shadows-1-intro.md", "repo_id": "mitiq", "token_count": 4373 }
21
<?xml version="1.0" encoding="UTF-8" standalone="no"?> <svg width="438.94376mm" height="222.25mm" viewBox="0 0 438.94376 222.25" version="1.1" id="svg993" inkscape:version="1.2.2 (b0a8486, 2022-12-01)" sodipodi:docname="ddd_workflow.svg" inkscape:export-filename="G:\My Drive\collaborations\zne_workflow2_steps.png" inkscape:export-xdpi="600" inkscape:export-ydpi="600" xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" xmlns="http://www.w3.org/2000/svg" xmlns:svg="http://www.w3.org/2000/svg" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:cc="http://creativecommons.org/ns#" xmlns:dc="http://purl.org/dc/elements/1.1/"> <defs id="defs987"> <clipPath id="clip0"> <rect x="20" y="125" width="1659" height="852" id="rect1556" /> </clipPath> <clipPath id="clip0-2"> <rect x="20" y="125" width="1659" height="852" id="rect1716" /> </clipPath> </defs> <sodipodi:namedview id="base" pagecolor="#ffffff" bordercolor="#666666" borderopacity="1.0" inkscape:pageopacity="0.0" inkscape:pageshadow="2" inkscape:zoom="0.5" inkscape:cx="953" inkscape:cy="607" inkscape:document-units="mm" inkscape:current-layer="layer1" inkscape:document-rotation="0" showgrid="false" fit-margin-top="0" fit-margin-left="0" fit-margin-right="0" fit-margin-bottom="0" inkscape:window-width="1440" inkscape:window-height="813" inkscape:window-x="0" inkscape:window-y="23" inkscape:window-maximized="1" inkscape:showpageshadow="2" inkscape:pagecheckerboard="0" inkscape:deskcolor="#d1d1d1" /> <metadata id="metadata990"> <rdf:RDF> <cc:Work rdf:about=""> <dc:format>image/svg+xml</dc:format> <dc:type rdf:resource="http://purl.org/dc/dcmitype/StillImage" /> <dc:title /> </cc:Work> </rdf:RDF> </metadata> <g inkscape:label="Layer 1" inkscape:groupmode="layer" id="layer1" transform="translate(215.69211,-315.9881)"> <rect x="-215.69211" y="315.9881" width="119.85625" height="222.25" fill="#ffff93" id="rect1721" style="stroke-width:0.264583" /> <text font-family="'Lucida Console', 'Lucida Console_MSFontService', sans-serif" font-weight="400" font-stretch="semi-condensed" font-size="16.9333px" id="text1723" x="-176.0914" y="334.24435" style="stroke-width:0.264583">User</text> <rect x="-92.660866" y="315.9881" width="192.61667" height="222.25" fill="#afffff" id="rect1725" style="stroke-width:0.264583;fill:#a2d0aa;fill-opacity:1" /> <text font-weight="400" font-stretch="semi-condensed" font-size="16.9333px" id="text1727" x="-40.748028" y="334.24435" style="font-weight:400;font-stretch:semi-condensed;font-size:16.9333px;font-family:'Lucida Console', 'Lucida Console_MSFontService', sans-serif;stroke-width:0.264583">mitiq.ddd</text> <path d="m -105.09628,389.43458 h 41.643564 l 0.709691,-0.76109 -0.79375,0.79375 h 33.706064 v -1.5875 h -34.499814 l -0.709691,0.76109 0.79375,-0.79375 h -40.849814 z m 74.471819,3.20766 7.9375,-3.96875 -7.9375,-3.96875 z" id="path1733" style="stroke-width:0.26458299" inkscape:connector-curvature="0" sodipodi:nodetypes="ccccccccccccccc" /> <rect x="-206.29941" y="355.01413" width="101.33542" height="67.46875" stroke="#000000" stroke-width="1.19062" stroke-miterlimit="8" fill="#ffffe1" id="rect1737" /> <rect x="-206.29941" y="462.17038" width="101.33542" height="67.73333" stroke-miterlimit="8" id="rect1743" style="fill:#ffffe1;stroke:#000000;stroke-width:1.19061995;stroke-miterlimit:8" /> <rect x="103.39539" y="315.9881" width="119.85625" height="222.25" fill="#d9d9d9" id="rect1757" style="stroke-width:0.264583" /> <text font-family="'Lucida Console', 'Lucida Console_MSFontService', sans-serif" font-weight="400" font-stretch="semi-condensed" font-size="16.9333px" id="text1759" x="122.51682" y="334.24435" style="stroke-width:0.264583">Hardware</text> <rect x="112.78809" y="415.86832" width="101.33542" height="45.772915" stroke="#000000" stroke-width="1.19062" stroke-miterlimit="8" fill="#a6a6a6" id="rect1761" style="fill:#ffffff;fill-opacity:1" /> <rect x="-23.207741" y="355.27872" width="101.33542" height="67.204163" stroke="#000000" stroke-width="1.19062" stroke-miterlimit="8" fill="#ddffff" id="rect1769" /> <path d="m 163.97703,461.50893 v 33.70633 H -95.571284 v -1.5875 H 163.18328 l -0.79375,0.79375 v -32.91258 z m -258.754564,36.88133 -7.937496,-3.96875 7.937496,-3.96875 z" id="path1797" style="stroke-width:0.26458299" inkscape:connector-curvature="0" sodipodi:nodetypes="cccccccccccc" /> <path d="m 77.995383,387.95476 h 86.180087 v 20.59146 h -1.5875 v -19.79771 l 0.79375,0.79375 H 77.995383 Z m 89.355087,19.79771 -3.96875,7.9375 -3.96875,-7.9375 z" id="path1807" style="stroke-width:0.264583" /> <g id="g980" transform="matrix(0.82993196,0,0,0.82993196,-18.013783,271.5724)"> <rect x="-97.253273" y="296.23883" width="201.55527" height="16.668762" id="rect1522" style="fill:#f2f2f2;stroke-width:0.314223" /> <text font-weight="400" font-stretch="semi-condensed" font-size="10.5833px" id="text1524" x="-93.00531" y="307.89111" style="font-weight:400;font-stretch:semi-condensed;font-size:10.5833px;font-family:'Lucida Console', 'Lucida Console_MSFontService', sans-serif;stroke-width:0.264583">2. Inference (trivial for DDD)</text> </g> <g id="g996" transform="translate(-18.480468,241.61736)"> <rect x="-82.494347" y="172.71333" width="70.396614" height="26.987499" fill="#f2f2f2" id="rect1512" style="stroke-width:0.227777" /> <text font-weight="400" font-stretch="semi-condensed" font-size="9.525px" id="text1516" x="-78.58831" y="183.82584" style="font-weight:400;font-stretch:semi-condensed;font-size:9.525px;font-family:'Lucida Console', 'Lucida Console_MSFontService', sans-serif;stroke-width:0.264583">1. Generate <tspan font-size="9.525px" x="-78.58831" y="195.20293" id="tspan1514" style="font-size:9.525px;stroke-width:0.0700043">circuit(s)</tspan></text> </g> <text xml:space="preserve" style="font-style:normal;font-weight:normal;font-size:10.2306px;line-height:1.25;font-family:sans-serif;letter-spacing:0px;word-spacing:0px;fill:#000000;fill-opacity:1;stroke:none;stroke-width:0.264583" x="27.340239" y="379.85693" id="text916"><tspan sodipodi:role="line" x="27.340239" y="379.85693" style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:10.2306px;font-family:'Lucida Console', 'Lucida Console_MSFontService', sans-serif;-inkscape-font-specification:'Lucida Console, Lucida Console_MSFontService, sans-serif';text-align:center;text-anchor:middle;stroke-width:0.264583" id="tspan918">Circuit with</tspan><tspan sodipodi:role="line" x="27.34024" y="392.69791" style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:10.2306px;font-family:'Lucida Console', 'Lucida Console_MSFontService', sans-serif;-inkscape-font-specification:'Lucida Console, Lucida Console_MSFontService, sans-serif';text-align:center;text-anchor:middle;stroke-width:0.264583" id="tspan922">DDD sequences</tspan><tspan sodipodi:role="line" x="27.34024" y="405.53891" style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:10.2306px;font-family:'Lucida Console', 'Lucida Console_MSFontService', sans-serif;-inkscape-font-specification:'Lucida Console, Lucida Console_MSFontService, sans-serif';text-align:center;text-anchor:middle;stroke-width:0.264583" id="tspan924">in idle windows</tspan></text> <text xml:space="preserve" style="font-style:normal;font-weight:normal;font-size:10.5833px;line-height:1.25;font-family:sans-serif;letter-spacing:0px;word-spacing:0px;fill:#000000;fill-opacity:1;stroke:none;stroke-width:0.264583" x="-157.39725" y="479.20273" id="text916-7-2"><tspan sodipodi:role="line" x="-157.39725" y="479.20273" style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:11.6417px;font-family:'Lucida Console', 'Lucida Console_MSFontService', sans-serif;-inkscape-font-specification:'Lucida Console, Lucida Console_MSFontService, sans-serif';text-align:center;text-anchor:middle;stroke-width:0.264583" id="tspan918-3-2">Error-</tspan><tspan sodipodi:role="line" x="-157.39725" y="493.75482" style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:11.6417px;font-family:'Lucida Console', 'Lucida Console_MSFontService', sans-serif;-inkscape-font-specification:'Lucida Console, Lucida Console_MSFontService, sans-serif';text-align:center;text-anchor:middle;stroke-width:0.264583" id="tspan990">mitigated</tspan><tspan sodipodi:role="line" x="-157.39725" y="508.30688" style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:11.6417px;font-family:'Lucida Console', 'Lucida Console_MSFontService', sans-serif;-inkscape-font-specification:'Lucida Console, Lucida Console_MSFontService, sans-serif';text-align:center;text-anchor:middle;stroke-width:0.264583" id="tspan964-5">expectation</tspan><tspan sodipodi:role="line" x="-157.39725" y="522.85895" style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:11.6417px;font-family:'Lucida Console', 'Lucida Console_MSFontService', sans-serif;-inkscape-font-specification:'Lucida Console, Lucida Console_MSFontService, sans-serif';text-align:center;text-anchor:middle;stroke-width:0.264583" id="tspan994">value</tspan></text> <text xml:space="preserve" style="font-style:normal;font-weight:normal;font-size:10.5833px;line-height:1.25;font-family:sans-serif;letter-spacing:0px;word-spacing:0px;fill:#000000;fill-opacity:1;stroke:none;stroke-width:0.264583" x="162.76848" y="433.80991" id="text916-7-0"><tspan sodipodi:role="line" x="162.76848" y="433.80991" style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:11.6417px;font-family:'Lucida Console', 'Lucida Console_MSFontService', sans-serif;-inkscape-font-specification:'Lucida Console, Lucida Console_MSFontService, sans-serif';text-align:center;text-anchor:middle;stroke-width:0.264583" id="tspan964-4">Execute on</tspan><tspan sodipodi:role="line" x="162.76848" y="448.362" style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:11.6417px;font-family:'Lucida Console', 'Lucida Console_MSFontService', sans-serif;-inkscape-font-specification:'Lucida Console, Lucida Console_MSFontService, sans-serif';text-align:center;text-anchor:middle;stroke-width:0.264583" id="tspan1013">backend</tspan></text> <text xml:space="preserve" style="font-style:normal;font-weight:normal;font-size:10.5833px;line-height:1.25;font-family:sans-serif;letter-spacing:0px;word-spacing:0px;fill:#000000;fill-opacity:1;stroke:none;stroke-width:0.264583" x="-157.64777" y="384.89777" id="text1017"><tspan sodipodi:role="line" id="tspan1015" x="-157.64777" y="384.89777" style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:11.6417px;font-family:'Lucida Console', 'Lucida Console_MSFontService', sans-serif;-inkscape-font-specification:'Lucida Console, Lucida Console_MSFontService, sans-serif';text-align:center;text-anchor:middle;stroke-width:0.264583">Quantum</tspan><tspan sodipodi:role="line" x="-157.64777" y="399.44989" style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:11.6417px;font-family:'Lucida Console', 'Lucida Console_MSFontService', sans-serif;-inkscape-font-specification:'Lucida Console, Lucida Console_MSFontService, sans-serif';text-align:center;text-anchor:middle;stroke-width:0.264583" id="tspan1021">program</tspan></text> </g> </svg>
mitiq/docs/source/img/ddd_workflow.svg/0
{ "file_path": "mitiq/docs/source/img/ddd_workflow.svg", "repo_id": "mitiq", "token_count": 6647 }
22
# Copyright (C) Unitary Fund # # This source code is licensed under the GPL license (v3) found in the # LICENSE file in the root directory of this source tree. """Functions to create a QPE circuit.""" from typing import Optional import cirq from mitiq import QPROGRAM from mitiq.interface import convert_from_mitiq def generate_qpe_circuit( evalue_reg: int, input_gate: cirq.Gate = cirq.T, return_type: Optional[str] = None, ) -> QPROGRAM: """Returns a circuit to create a quantum phase estimation (QPE) circuit as defined in https://en.wikipedia.org/wiki/Quantum_phase_estimation_algorithm The unitary to estimate the phase of corresponds to a single-qubit gate (``input_gate``). The IQFT circuit defined in this method is taken from taken from Sec 7.7.4 of :cite:`Wong_2022`. The notation for eigenvalue register and eigenstate register used to define this function also follows from :cite:`Wong_2022`. Args: evalue_reg : Number of qubits in the eigenvalue register. The qubits in this variable are used to estimate the phase. input_gate : The unitary to estimate the phase of as a single-qubit Cirq gate. Default gate used here is `cirq.T`. return_type: Return type of the output circuit. Returns: A Quantum Phase Estimation circuit. """ if evalue_reg <= 0: raise ValueError( "{} is invalid for the number of eigenvalue reg qubits. ", evalue_reg, ) num_qubits_for_gate = input_gate.num_qubits() if num_qubits_for_gate > 1: raise ValueError("This QPE method only works for 1-qubit gates.") if evalue_reg == num_qubits_for_gate: raise ValueError( "The eigenvalue reg must be larger than the eigenstate reg." ) total_num_qubits = evalue_reg + num_qubits_for_gate qreg = cirq.LineQubit.range(total_num_qubits) circuit = cirq.Circuit() # QFT circuit # apply hadamard and controlled unitary to the qubits in the eigenvalue reg hadamard_circuit = cirq.Circuit() for i in range(evalue_reg): hadamard_circuit.append(cirq.H(qreg[i])) circuit = circuit + hadamard_circuit for i in range(total_num_qubits - 1)[::-1]: circuit.append( [input_gate(qreg[-1]).controlled_by(qreg[i])] * (2 ** (evalue_reg - 1 - i)) ) # IQFT of the eigenvalue register # swap the qubits in the eigenvalue register for i in range(int(evalue_reg / 2)): circuit.append( cirq.SWAP(qreg[i], qreg[evalue_reg - 1 - i]), strategy=cirq.InsertStrategy.NEW, ) # apply inverse of hadamard followed by controlled unitary circuit.append(cirq.H(qreg[0]), strategy=cirq.InsertStrategy.NEW) for i in range(1, evalue_reg): for j in range(evalue_reg): if j < i: circuit.append( cirq.inverse(input_gate(qreg[i]).controlled_by(qreg[j])), strategy=cirq.InsertStrategy.NEW, ) circuit.append( cirq.H(qreg[i]), strategy=cirq.InsertStrategy.NEW, ) return_type = "cirq" if not return_type else return_type return convert_from_mitiq(circuit, return_type)
mitiq/mitiq/benchmarks/qpe_circuits.py/0
{ "file_path": "mitiq/mitiq/benchmarks/qpe_circuits.py", "repo_id": "mitiq", "token_count": 1384 }
23
# Copyright (C) Unitary Fund # # This source code is licensed under the GPL license (v3) found in the # LICENSE file in the root directory of this source tree. import warnings from enum import Enum from operator import itemgetter from typing import Callable, Dict, List, Optional, Sequence, Tuple, Union, cast import cirq import numpy as np import numpy.typing as npt from tabulate import tabulate from mitiq import ( QPROGRAM, Executor, MeasurementResult, Observable, QuantumResult, ) from mitiq.calibration.settings import ( ZNE_SETTINGS, BenchmarkProblem, Settings, Strategy, ) from mitiq.interface import convert_from_mitiq class MissingResultsError(Exception): pass class OutputForm(str, Enum): flat = "flat" cartesian = "cartesian" class ExperimentResults: """Class to store calibration experiment data, and provide helper methods for computing results based on it.""" def __init__( self, strategies: List[Strategy], problems: List[BenchmarkProblem] ) -> None: self.strategies = strategies self.problems = problems self.num_strategies = len(strategies) self.num_problems = len(problems) self.reset_data() def add_result( self, strategy: Strategy, problem: BenchmarkProblem, *, ideal_val: float, noisy_val: float, mitigated_val: float, ) -> None: """Add a single result from a (Strategy, BenchmarkProblem) pair and store the results.""" self.mitigated[strategy.id, problem.id] = mitigated_val self.noisy[strategy.id, problem.id] = noisy_val self.ideal[strategy.id, problem.id] = ideal_val @staticmethod def _performance_str(noisy_error: float, mitigated_error: float) -> str: """Get human readable performance representaion.""" return ( f"{'✔' if mitigated_error < noisy_error else '✘'}\n" f"Noisy error: {round(noisy_error, 4)}\n" f"Mitigated error: {round(mitigated_error, 4)}\n" f"Improvement factor: {round(noisy_error / mitigated_error, 4)}" ) def _get_errors( self, strategy_id: int, problem_id: int ) -> Tuple[float, float]: """Get errors for a given strategy/problem combination. Returns: A tuple comprising: - absolute value of the noisy error - absolute value of the mitigated error """ mitigated = self.mitigated[strategy_id, problem_id] noisy = self.noisy[strategy_id, problem_id] ideal = self.ideal[strategy_id, problem_id] mitigated_error = abs(ideal - mitigated) noisy_error = abs(ideal - noisy) return noisy_error, mitigated_error def log_results_flat(self) -> None: """Prints calibration results in the following form ┌──────────────────────────┬──────────────────────────────┬────────────────────────────┐ │ benchmark │ strategy │ performance │ ├──────────────────────────┼──────────────────────────────┼────────────────────────────┤ │ Type: rb │ Technique: ZNE │ ✔ │ │ Num qubits: 2 │ Factory: Richardson │ Noisy error: 0.101 │ │ Circuit depth: 323 │ Scale factors: 1.0, 3.0, 5.0 │ Mitigated error: 0.0294 │ │ Two qubit gate count: 77 │ Scale method: fold_global │ Improvement factor: 3.4398 │ ├──────────────────────────┼──────────────────────────────┼────────────────────────────┤ │ Type: rb │ Technique: ZNE │ ✔ │ │ Num qubits: 2 │ Factory: Richardson │ Noisy error: 0.101 │ │ Circuit depth: 323 │ Scale factors: 1.0, 2.0, 3.0 │ Mitigated error: 0.0501 │ │ Two qubit gate count: 77 │ Scale method: fold_global │ Improvement factor: 2.016 │ ├──────────────────────────┼──────────────────────────────┼────────────────────────────┤ │ Type: ghz │ Technique: ZNE │ ✔ │ │ Num qubits: 2 │ Factory: Richardson │ Noisy error: 0.0128 │ │ Circuit depth: 2 │ Scale factors: 1.0, 2.0, 3.0 │ Mitigated error: 0.0082 │ │ Two qubit gate count: 1 │ Scale method: fold_global │ Improvement factor: 1.561 │ ├──────────────────────────┼──────────────────────────────┼────────────────────────────┤ │ Type: ghz │ Technique: ZNE │ ✘ │ │ Num qubits: 2 │ Factory: Richardson │ Noisy error: 0.0128 │ │ Circuit depth: 2 │ Scale factors: 1.0, 3.0, 5.0 │ Mitigated error: 0.0137 │ │ Two qubit gate count: 1 │ Scale method: fold_global │ Improvement factor: 0.9369 │ └──────────────────────────┴──────────────────────────────┴────────────────────────────┘ """ # noqa: E501 table: List[List[Union[str, float]]] = [] headers: List[str] = ["benchmark", "strategy", "performance"] for problem in self.problems: row_group: List[List[Union[str, float]]] = [] for strategy in self.strategies: nerr, merr = self._get_errors(strategy.id, problem.id) row_group.append( [ str(problem), str(strategy), self._performance_str(nerr, merr), # this is only for sorting # removed after sorting merr - nerr, ] ) row_group.sort(key=itemgetter(-1)) table.extend([r[:-1] for r in row_group]) return print(tabulate(table, headers, tablefmt="simple_grid")) def log_results_cartesian(self) -> None: """Prints calibration results in the following form ┌──────────────────────────────┬────────────────────────────┬────────────────────────────┐ │ strategy\benchmark │ Type: rb │ Type: ghz │ │ │ Num qubits: 2 │ Num qubits: 2 │ │ │ Circuit depth: 337 │ Circuit depth: 2 │ │ │ Two qubit gate count: 80 │ Two qubit gate count: 1 │ ├──────────────────────────────┼────────────────────────────┼────────────────────────────┤ │ Technique: ZNE │ ✔ │ ✘ │ │ Factory: Richardson │ Noisy error: 0.1128 │ Noisy error: 0.0117 │ │ Scale factors: 1.0, 2.0, 3.0 │ Mitigated error: 0.0501 │ Mitigated error: 0.0439 │ │ Scale method: fold_global │ Improvement factor: 2.2515 │ Improvement factor: 0.2665 │ ├──────────────────────────────┼────────────────────────────┼────────────────────────────┤ │ Technique: ZNE │ ✔ │ ✘ │ │ Factory: Richardson │ Noisy error: 0.1128 │ Noisy error: 0.0117 │ │ Scale factors: 1.0, 3.0, 5.0 │ Mitigated error: 0.0408 │ Mitigated error: 0.0171 │ │ Scale method: fold_global │ Improvement factor: 2.7672 │ Improvement factor: 0.6852 │ └──────────────────────────────┴────────────────────────────┴────────────────────────────┘ """ # noqa: E501 table: List[List[str]] = [] headers: List[str] = ["strategy\\benchmark"] for problem in self.problems: headers.append(str(problem)) for strategy in self.strategies: row: List[str] = [str(strategy)] for problem in self.problems: nerr, merr = self._get_errors(strategy.id, problem.id) row.append(self._performance_str(nerr, merr)) table.append(row) return print(tabulate(table, headers, tablefmt="simple_grid")) def is_missing_data(self) -> bool: """Method to check if there is any missing data that was expected from the calibration experiments.""" return np.isnan(self.mitigated + self.noisy + self.ideal).any() def ensure_full(self) -> None: """Check to ensure all expected data is collected. All mitigated, noisy and ideal values must be nonempty for this to pass and return True.""" if self.is_missing_data(): raise MissingResultsError( "There are missing results from the expected calibration " "experiments. Please try running the experiments again with " "the `run` function." ) def squared_errors(self) -> npt.NDArray[np.float32]: """Returns an array of squared errors, one for each (strategy, problem) pair.""" return (self.ideal - self.mitigated) ** 2 def best_strategy_id(self) -> int: """Returns the stategy id that corresponds to the strategy that maintained the smallest error across all ``BenchmarkProblem`` instances.""" errors = self.squared_errors() strategy_errors = np.sum(errors, axis=1) strategy_id = int(np.argmin(strategy_errors)) return strategy_id def reset_data(self) -> None: """Reset all experiment result data using NaN values.""" self.mitigated = np.full( (self.num_strategies, self.num_problems), np.nan ) self.noisy = np.full((self.num_strategies, self.num_problems), np.nan) self.ideal = np.full((self.num_strategies, self.num_problems), np.nan) class Calibrator: """An object used to orchestrate experiments for calibrating optimal error mitigation strategies. Args: executor: An unmitigated executor returning a :class:`.MeasurementResult`. settings: A ``Settings`` object which specifies the type and amount of circuits/error mitigation methods to run. frontend: The executor frontend as a string. For a list of supported frontends see ``mitiq.SUPPORTED_PROGRAM_TYPES.keys()``, ideal_executor: An optional simulated executor returning the ideal :class:`.MeasurementResult` without noise. """ def __init__( self, executor: Union[Executor, Callable[[QPROGRAM], QuantumResult]], *, frontend: str, settings: Settings = ZNE_SETTINGS, ideal_executor: Union[ Executor, Callable[[QPROGRAM], QuantumResult], None ] = None, ): self.executor = ( executor if isinstance(executor, Executor) else Executor(executor) ) self.ideal_executor = ( Executor(ideal_executor) if ideal_executor and not isinstance(ideal_executor, Executor) else None ) self.settings = settings self.problems = settings.make_problems() self.strategies = settings.make_strategies() self.results = ExperimentResults( strategies=self.strategies, problems=self.problems ) # Build an executor of Cirq circuits def cirq_execute( circuits: Sequence[cirq.Circuit], ) -> Sequence[MeasurementResult]: q_programs = [convert_from_mitiq(c, frontend) for c in circuits] results = cast( Sequence[MeasurementResult], self.executor.run(q_programs) ) return results self._cirq_executor = Executor(cirq_execute) # type: ignore [arg-type] @property def cirq_executor(self) -> Executor: """Returns an executor which is able to run Cirq circuits by converting them and calling self.executor. Args: executor: Executor which takes as input QPROGRAM circuits. Returns: Executor which takes as input a Cirq circuits. """ return self._cirq_executor def get_cost(self) -> Dict[str, int]: """Returns the expected number of noisy and ideal expectation values required for calibration. Returns: A summary of the number of circuits to be run. """ num_circuits = len(self.problems) num_options = sum( strategy.num_circuits_required() for strategy in self.strategies ) noisy = num_circuits * (num_options + 1) ideal = 0 # TODO: ideal executor is currently unused return { "noisy_executions": noisy, "ideal_executions": ideal, } def run(self, log: Optional[OutputForm] = None) -> None: """Runs all the circuits required for calibration.""" if not self.results.is_missing_data(): self.results.reset_data() for problem in self.problems: # Benchmark circuits have no measurements, so we append them. circuit = problem.circuit.copy() circuit.append(cirq.measure(circuit.all_qubits())) bitstring_to_measure = problem.most_likely_bitstring() expval_executor = convert_to_expval_executor( self.cirq_executor, bitstring_to_measure ) noisy_value = expval_executor.evaluate(circuit)[0] for strategy in self.strategies: with warnings.catch_warnings(): warnings.simplefilter("ignore", UserWarning) mitigated_value = strategy.mitigation_function( circuit, expval_executor ) self.results.add_result( strategy, problem, ideal_val=problem.largest_probability(), noisy_val=noisy_value, mitigated_val=mitigated_value, ) self.results.ensure_full() if log is not None: if log == OutputForm.flat: self.results.log_results_flat() elif log == OutputForm.cartesian: self.results.log_results_cartesian() else: raise ValueError( "log parameter must be one of: " f"{', '.join(OutputForm._member_names_)}" ) def best_strategy(self) -> Strategy: """Finds the best strategy by using the parameters that had the smallest error. Args: results: Calibration experiment results. Obtained by first running :func:`run`. Returns: A single :class:`Strategy` object specifying the technique and parameters that performed best. """ self.results.ensure_full() strategy_id = self.results.best_strategy_id() return self.settings.get_strategy(strategy_id) def execute_with_mitigation( self, circuit: QPROGRAM, expval_executor: Union[Executor, Callable[[QPROGRAM], QuantumResult]], observable: Optional[Observable] = None, ) -> Union[QuantumResult, None]: """See :func:`execute_with_mitigation` for signature and details.""" return execute_with_mitigation( circuit, expval_executor, observable, calibrator=self ) def convert_to_expval_executor(executor: Executor, bitstring: str) -> Executor: """Constructs a new executor returning an expectation value given by the probability that the circuit outputs the most likely state according to the ideal distribution. Args: executor: Executor which returns a :class:`.MeasurementResult` (bitstrings). bitstring: The bitstring to measure the probability of. Defaults to ground state bitstring "00...0". Returns: A tuple containing an executor returning expectation values and, the most likely bitstring, according to the passed ``distribution`` """ def expval_executor(circuit: cirq.Circuit) -> float: circuit_with_meas = circuit.copy() if not cirq.is_measurement(circuit_with_meas): circuit_with_meas.append( cirq.measure(circuit_with_meas.all_qubits()) ) raw = cast(MeasurementResult, executor.run([circuit_with_meas])[0]) distribution = raw.prob_distribution() return distribution.get(bitstring, 0.0) return Executor(expval_executor) # type: ignore [arg-type] def execute_with_mitigation( circuit: QPROGRAM, executor: Union[Executor, Callable[[QPROGRAM], QuantumResult]], observable: Optional[Observable] = None, *, calibrator: Calibrator, ) -> Union[QuantumResult, None]: """Estimates the error-mitigated expectation value associated to the input circuit, via the application of the best mitigation strategy, as determined by calibration. Args: circuit: The input circuit to execute. executor: A Mitiq executor that executes a circuit and returns the unmitigated ``QuantumResult`` (e.g. an expectation value). observable: Observable to compute the expectation value of. If ``None``, the ``executor`` must return an expectation value. Otherwise, the ``QuantumResult`` returned by ``executor`` is used to compute the expectation of the observable. calibrator: ``Calibrator`` object with which to determine the error mitigation strategy to execute the circuit. Returns: The error mitigated expectation expectation value. """ if calibrator.results.is_missing_data(): cost = calibrator.get_cost() answer = input( "Calibration experiments have not yet been run. You can run the " "experiments manually by calling `calibrator.run()`, or they can " f"be run now. The potential cost is:\n{cost}\n" "Would you like the experiments to be run automatically? (yes/no)" ) if answer.lower() == "yes": calibrator.run() else: return None strategy = calibrator.best_strategy() em_func = strategy.mitigation_function return em_func(circuit, executor=executor, observable=observable)
mitiq/mitiq/calibration/calibrator.py/0
{ "file_path": "mitiq/mitiq/calibration/calibrator.py", "repo_id": "mitiq", "token_count": 8194 }
24
# Copyright (C) Unitary Fund # # This source code is licensed under the GPL license (v3) found in the # LICENSE file in the root directory of this source tree. """Tools to determine slack windows in circuits and to insert DDD sequences.""" from typing import Callable import numpy as np import numpy.typing as npt from cirq import Circuit, I, LineQubit, synchronize_terminal_measurements from mitiq import QPROGRAM from mitiq.interface import accept_qprogram_and_validate def _get_circuit_mask(circuit: Circuit) -> npt.NDArray[np.int64]: """Given a circuit with n qubits and d moments returns a matrix :math:`A` with n rows and d columns. The matrix elements are :math:`A_{i,j} = 1` if there is a non-identity gate acting on qubit :math:`i` at moment :math:`j`, while :math:`A_{i,j} = 0` otherwise. Args: circuit: Input circuit to mask with n qubits and d moments Returns: A mask matrix with n rows and d columns """ qubits = sorted(circuit.all_qubits()) indexed_qubits = [(i, n) for (i, n) in enumerate(qubits)] mask_matrix = np.zeros((len(qubits), len(circuit)), dtype=int) for moment_index, moment in enumerate(circuit): for op in moment: qubit_indices = [ qubit[0] for qubit in indexed_qubits if qubit[1] in op.qubits and op.gate != I ] for qubit_index in qubit_indices: mask_matrix[qubit_index, moment_index] = 1 return mask_matrix def _validate_integer_matrix(mask: npt.NDArray[np.int64]) -> None: """Ensures the input is a NumPy 2d array with integer elements.""" if not isinstance(mask, np.ndarray): raise TypeError("The input matrix must be a numpy.ndarray object.") if not np.issubdtype(mask.dtype.type, int): raise TypeError("The input matrix must have integer elements.") if len(mask.shape) != 2: raise ValueError("The input must be a 2-dimensional array.") def get_slack_matrix_from_circuit_mask( mask: npt.NDArray[np.int64], ) -> npt.NDArray[np.int64]: """Given a circuit mask matrix :math:`A`, e.g., the output of ``_get_circuit_mask()``, returns a slack matrix :math:`B`, where :math:`B_{i,j} = t` if the position :math:`A_{i,j}` is the initial element of a sequence of :math:`t` zeros (from left to right). Args: mask: The mask matrix of a quantum circuit. Returns: The matrix of slack lengths. """ _validate_integer_matrix(mask) if not (mask**2 == mask).all(): raise ValueError("The input matrix elements must be 0 or 1.") num_rows, num_cols = mask.shape slack_matrix = np.zeros((num_rows, num_cols), dtype=int) for r in range(num_rows): for c in range(num_cols): previous_elem = mask[r, c - 1] if c != 0 else 1 if previous_elem == 1: # Compute slack length for elem in mask[r, c::]: if elem == 0: slack_matrix[r, c] += 1 else: break return slack_matrix def insert_ddd_sequences( circuit: QPROGRAM, rule: Callable[[int], Circuit], ) -> QPROGRAM: """Returns the circuit with DDD sequences applied according to the input rule. Args: circuit: The QPROGRAM circuit to be modified with DDD sequences. rule: The rule determining what DDD sequences should be applied. A set of built-in DDD rules can be imported from ``mitiq.ddd.rules``. Returns: The circuit with DDD sequences added. """ return _insert_ddd_sequences(circuit, rule) @accept_qprogram_and_validate def _insert_ddd_sequences( circuit: Circuit, rule: Callable[[int], Circuit], ) -> Circuit: """Returns the circuit with DDD sequences applied according to the input rule. Args: circuit: The Cirq circuit to be modified with DDD sequences. rule: The rule determining what DDD sequences should be applied. A set of built-in DDD rules can be imported from ``mitiq.ddd.rules``. Returns: The circuit with DDD sequences added. """ circuit = synchronize_terminal_measurements(circuit) if not circuit.are_all_measurements_terminal(): raise ValueError( "This circuit contains midcircuit measurements which " "are not currently supported by DDD." ) slack_matrix = get_slack_matrix_from_circuit_mask( _get_circuit_mask(circuit) ) # Copy to avoid mutating the input circuit circuit_with_ddd = circuit.copy() qubits = sorted(circuit.all_qubits()) for moment_idx in range(len(circuit)): slack_column = slack_matrix[:, moment_idx] for row_index, slack_length in enumerate(slack_column): if slack_length > 1: ddd_sequence = rule(slack_length).transform_qubits( {LineQubit(0): qubits[row_index]} ) for idx, op in enumerate(ddd_sequence.all_operations()): moment = circuit_with_ddd[moment_idx + idx] op_to_replace = moment.operation_at(*op.qubits) if op_to_replace and op_to_replace.gate == I: moment = moment.without_operations_touching(op.qubits) circuit_with_ddd[moment_idx + idx] = moment.with_operation( op ) return circuit_with_ddd
mitiq/mitiq/ddd/insertion.py/0
{ "file_path": "mitiq/mitiq/ddd/insertion.py", "repo_id": "mitiq", "token_count": 2379 }
25
# Copyright (C) Unitary Fund # # This source code is licensed under the GPL license (v3) found in the # LICENSE file in the root directory of this source tree. """Tests for Cirq executors defined in cirq_utils.py""" import cirq import numpy as np from mitiq import MeasurementResult from mitiq.interface.mitiq_cirq import ( compute_density_matrix, execute_with_depolarizing_noise, sample_bitstrings, ) def test_sample_bitstrings(): """Tests if the outcome is as expected with different noise models and error rate.""" # testing default options i.e. noise model is amplitude damping with # the default error rate, shots is also the default number qc = cirq.Circuit(cirq.X(cirq.LineQubit(0))) + cirq.Circuit( cirq.measure(cirq.LineQubit(0)) ) result_default = sample_bitstrings(qc) assert result_default.nqubits == 1 assert result_default.qubit_indices == (0,) assert result_default.shots == 8192 assert isinstance(result_default, MeasurementResult) # test for sum(noise_level) = 0 result_no_noise = sample_bitstrings(qc, noise_level=(0.00,), shots=10) assert np.allclose( result_no_noise.asarray, np.array([[1], [1], [1], [1], [1], [1], [1], [1], [1], [1]]), ) # test result with inputs different from default result_not_default = sample_bitstrings( qc, cirq.GeneralizedAmplitudeDampingChannel, (0.1, 0.1), cirq.DensityMatrixSimulator(), 8000, ) assert result_not_default.nqubits == 1 assert result_not_default.qubit_indices == (0,) assert result_not_default.shots == 8000 def test_compute_density_matrix(): """Tests if the density matrix of a noisy circuit is output as expected.""" qc = cirq.Circuit(cirq.X(cirq.LineQubit(0))) assert np.isclose(np.trace(compute_density_matrix(qc)), 1) assert np.isclose( np.trace( compute_density_matrix( qc, cirq.GeneralizedAmplitudeDampingChannel, (0.1, 0.1) ) ), 1, ) def test_execute_with_depolarizing_noise(): """Tests if executor function for Cirq returns a proper expectation value when used for noisy depoalrizing simulation.""" qc = cirq.Circuit() for _ in range(100): qc += cirq.X(cirq.LineQubit(0)) observable = np.diag([0, 1]) # Test 1 noise1 = 0.0 observable_exp_value = execute_with_depolarizing_noise( qc, observable, noise1 ) assert 0.0 == observable_exp_value # Test 2 noise2 = 0.5 observable_exp_value = execute_with_depolarizing_noise( qc, observable, noise2 ) assert np.isclose(observable_exp_value, 0.5) # Test 3 noise3 = 0.001 observable_exp_value = execute_with_depolarizing_noise( qc, observable, noise3 ) assert np.isclose(observable_exp_value, 0.062452)
mitiq/mitiq/interface/mitiq_cirq/tests/test_cirq_utils.py/0
{ "file_path": "mitiq/mitiq/interface/mitiq_cirq/tests/test_cirq_utils.py", "repo_id": "mitiq", "token_count": 1191 }
26
# Copyright (C) Unitary Fund # # This source code is licensed under the GPL license (v3) found in the # LICENSE file in the root directory of this source tree. """Unit tests for conversions between Mitiq circuits and Qiskit circuits.""" import copy import cirq import numpy as np import pytest import qiskit from qiskit import qasm2 from mitiq.interface import convert_to_mitiq from mitiq.interface.mitiq_qiskit.conversions import ( _add_identity_to_idle, _map_bit_index, _measurement_order, _remove_identity_from_idle, _remove_qasm_barriers, _transform_registers, from_qasm, from_qiskit, to_qasm, to_qiskit, ) from mitiq.utils import _equal def _multi_reg_circuits(): """Returns a circuit with multiple registers and an equivalent circuit with a single register.""" qregs = [qiskit.QuantumRegister(1, f"q{j}") for j in range(4)] circuit_multi_reg = qiskit.QuantumCircuit(*qregs) for q in qregs[1:]: circuit_multi_reg.x(q) circuit_multi_reg.x(3) qreg = qiskit.QuantumRegister(4, "q") circuit_single_reg = qiskit.QuantumCircuit(qreg) for q in qreg[1:]: circuit_single_reg.x(q) circuit_single_reg.x(3) return circuit_multi_reg, circuit_single_reg def test_remove_qasm_barriers(): assert ( _remove_qasm_barriers( """ // quantum ripple-carry adder from Cuccaro et al, quant-ph/0410184 OPENQASM 2.0; include "qelib1.inc"; include "barrier.inc"; include ";barrier.inc"; gate majority a,b,c { cx c,b; cx c,a; ccx a,b,c; } gate barrier1 a,a,a,a,a{ barrier x,y,z; barrier1; barrier; } gate unmaj a,b,c { ccx a,b,c; cx c,a; cx a,b; } qreg cin[1]; qreg a[4]; qreg b[4]; // barrier; qreg cout[1]; barrier x,y,z; creg ans[5]; // set input states x a[0]; // a = 0001 x b; // b = 1111 // add a to b, storing result in b majority cin[0],b[0],a[0]; majority a[0],b[1],a[1]; majority a[1],b[2],a[2]; majority a[2],b[3],a[3]; cx a[3],cout[0]; unmaj a[2],b[3],a[3]; unmaj a[1],b[2],a[2]; unmaj a[0],b[1],a[1]; unmaj cin[0],b[0],a[0]; measure b[0] -> ans[0]; measure b[1] -> ans[1]; measure b[2] -> ans[2]; measure b[3] -> ans[3]; measure cout[0] -> ans[4]; // quantum ripple-carry adder from Cuccaro et al, quant-ph/0410184 """ ) == """ // quantum ripple-carry adder from Cuccaro et al, quant-ph/0410184 OPENQASM 2.0; include "qelib1.inc"; include "barrier.inc"; include ";barrier.inc"; gate majority a,b,c { cx c,b; cx c,a; ccx a,b,c; } gate barrier1 a,a,a,a,a{ barrier1; } gate unmaj a,b,c { ccx a,b,c; cx c,a; cx a,b; } qreg cin[1]; qreg a[4]; qreg b[4]; // barrier; qreg cout[1]; creg ans[5]; // set input states x a[0]; // a = 0001 x b; // b = 1111 // add a to b, storing result in b majority cin[0],b[0],a[0]; majority a[0],b[1],a[1]; majority a[1],b[2],a[2]; majority a[2],b[3],a[3]; cx a[3],cout[0]; unmaj a[2],b[3],a[3]; unmaj a[1],b[2],a[2]; unmaj a[0],b[1],a[1]; unmaj cin[0],b[0],a[0]; measure b[0] -> ans[0]; measure b[1] -> ans[1]; measure b[2] -> ans[2]; measure b[3] -> ans[3]; measure cout[0] -> ans[4]; // quantum ripple-carry adder from Cuccaro et al, quant-ph/0410184 """ ) def test_bell_state_to_from_circuits(): """Tests cirq.Circuit --> qiskit.QuantumCircuit --> cirq.Circuit with a Bell state circuit. """ qreg = cirq.LineQubit.range(2) cirq_circuit = cirq.Circuit( [cirq.ops.H.on(qreg[0]), cirq.ops.CNOT.on(qreg[0], qreg[1])] ) qiskit_circuit = to_qiskit(cirq_circuit) # Qiskit from Cirq circuit_cirq = from_qiskit(qiskit_circuit) # Cirq from Qiskit assert _equal(cirq_circuit, circuit_cirq) def test_bell_state_to_from_qasm(): """Tests cirq.Circuit --> QASM string --> cirq.Circuit with a Bell state circuit. """ qreg = cirq.LineQubit.range(2) cirq_circuit = cirq.Circuit( [cirq.ops.H.on(qreg[0]), cirq.ops.CNOT.on(qreg[0], qreg[1])] ) qasm = to_qasm(cirq_circuit) # Qasm from Cirq circuit_cirq = from_qasm(qasm) assert _equal(cirq_circuit, circuit_cirq) def test_random_circuit_to_from_circuits(): """Tests cirq.Circuit --> qiskit.QuantumCircuit --> cirq.Circuit with a random two-qubit circuit. """ cirq_circuit = cirq.testing.random_circuit( qubits=2, n_moments=10, op_density=0.99, random_state=1 ) qiskit_circuit = to_qiskit(cirq_circuit) circuit_cirq = from_qiskit(qiskit_circuit) assert cirq.equal_up_to_global_phase( cirq_circuit.unitary(), circuit_cirq.unitary() ) def test_random_circuit_to_from_qasm(): """Tests cirq.Circuit --> QASM string --> cirq.Circuit with a random one-qubit circuit. """ cirq_circuit = cirq.testing.random_circuit( qubits=2, n_moments=10, op_density=0.99, random_state=2 ) qasm = to_qasm(cirq_circuit) circuit_cirq = from_qasm(qasm) assert cirq.equal_up_to_global_phase( cirq_circuit.unitary(), circuit_cirq.unitary() ) def test_convert_with_qft(): """Tests converting a Qiskit circuit with a QFT to a Cirq circuit.""" circuit = qiskit.QuantumCircuit(1) circuit &= qiskit.circuit.library.QFT(1) circuit.measure_all() qft_cirq = from_qiskit(circuit) qreg = cirq.LineQubit.range(1) cirq_circuit = cirq.Circuit( [cirq.ops.H.on(qreg[0]), cirq.ops.measure(qreg[0], key="meas")] ) assert _equal(cirq_circuit, qft_cirq) @pytest.mark.parametrize("as_qasm", (True, False)) def test_convert_with_barrier(as_qasm): """Tests converting a Qiskit circuit with a barrier to a Cirq circuit.""" n = 5 qiskit_circuit = qiskit.QuantumCircuit(qiskit.QuantumRegister(n)) qiskit_circuit.barrier() if as_qasm: cirq_circuit = from_qasm(qasm2.dumps(qiskit_circuit)) else: cirq_circuit = from_qiskit(qiskit_circuit) assert _equal(cirq_circuit, cirq.Circuit()) @pytest.mark.parametrize("as_qasm", (True, False)) def test_convert_with_multiple_barriers(as_qasm): """Tests converting a Qiskit circuit with barriers to a Cirq circuit.""" n = 1 num_ops = 10 qreg = qiskit.QuantumRegister(n) qiskit_circuit = qiskit.QuantumCircuit(qreg) for _ in range(num_ops): qiskit_circuit.h(qreg) qiskit_circuit.barrier() if as_qasm: cirq_circuit = from_qasm(qasm2.dumps(qiskit_circuit)) else: cirq_circuit = from_qiskit(qiskit_circuit) qbit = cirq.LineQubit(0) correct = cirq.Circuit(cirq.ops.H.on(qbit) for _ in range(num_ops)) assert _equal(cirq_circuit, correct) @pytest.mark.parametrize("reg_sizes", [[2, 4, 1, 6], [5, 4, 2], [6]]) def test_map_bit_index(reg_sizes): expected_register_index = 0 expected_mapped_index = 0 for bit_index in range(sum(reg_sizes)): register_index, mapped_index = _map_bit_index(bit_index, reg_sizes) assert register_index == expected_register_index assert mapped_index == expected_mapped_index expected_mapped_index += 1 if bit_index == sum(reg_sizes[: expected_register_index + 1]) - 1: expected_register_index += 1 expected_mapped_index = 0 @pytest.mark.parametrize("nqubits", [1, 5]) @pytest.mark.parametrize("with_ops", [True, False]) @pytest.mark.parametrize("measure", [True, False]) def test_transform_qregs_one_qubit_ops(nqubits, with_ops, measure): qreg = qiskit.QuantumRegister(nqubits) circ = qiskit.QuantumCircuit(qreg) if with_ops: circ.h(qreg) if measure: circ.add_register(qiskit.ClassicalRegister(nqubits)) circ.measure(qreg, circ.cregs[0]) orig = circ.copy() assert circ.qregs == [qreg] new_qregs = [qiskit.QuantumRegister(1) for _ in range(nqubits)] circ = _transform_registers(circ, new_qregs=new_qregs) assert circ.qregs == new_qregs assert circ.cregs == orig.cregs assert _equal(from_qiskit(circ), from_qiskit(orig)) @pytest.mark.parametrize("nqubits", [1, 5]) @pytest.mark.parametrize("with_ops", [True, False]) @pytest.mark.parametrize("measure", [True, False]) def test_transform_circuit_with_multiple_qregs(nqubits, with_ops, measure): qreg_1 = qiskit.QuantumRegister(nqubits) qreg_2 = qiskit.QuantumRegister(nqubits) circ = qiskit.QuantumCircuit(qreg_1, qreg_2) if with_ops: circ.h(qreg_1) circ.h(qreg_2) if measure: circ.add_register(qiskit.ClassicalRegister(nqubits)) circ.measure(qreg_1, circ.cregs[0]) circ.measure(qreg_2, circ.cregs[0]) orig = circ.copy() assert circ.qregs == [qreg_1, qreg_2] new_qregs_1 = [qiskit.QuantumRegister(1) for _ in range(nqubits)] new_qregs_2 = [qiskit.QuantumRegister(1) for _ in range(nqubits)] circ = _transform_registers(circ, new_qregs=new_qregs_1 + new_qregs_2) assert circ.qregs == new_qregs_1 + new_qregs_2 assert circ.cregs == orig.cregs assert _equal(from_qiskit(circ), from_qiskit(orig)) @pytest.mark.parametrize("new_reg_sizes", [[1], [1, 2], [2, 1], [1, 1, 1]]) def test_transform_qregs_two_qubit_ops(new_reg_sizes): nqubits = sum(new_reg_sizes) circ = to_qiskit( cirq.testing.random_circuit( nqubits, n_moments=5, op_density=1, random_state=1 ) ) orig = circ.copy() new_qregs = [qiskit.QuantumRegister(s) for s in new_reg_sizes] circ = _transform_registers(circ, new_qregs=new_qregs) assert circ.qregs == new_qregs assert circ.cregs == orig.cregs assert _equal(from_qiskit(circ), from_qiskit(orig)) @pytest.mark.parametrize("new_reg_sizes", [[1], [1, 2], [2, 1], [1, 1, 1]]) @pytest.mark.parametrize("measure", [True, False]) def test_transform_qregs_random_circuit(new_reg_sizes, measure): nbits = sum(new_reg_sizes) circ = to_qiskit( cirq.testing.random_circuit( nbits, n_moments=5, op_density=1, random_state=10 ) ) creg = qiskit.ClassicalRegister(nbits) circ.add_register(creg) if measure: circ.measure(circ.qregs[0], creg) orig = circ.copy() new_qregs = [qiskit.QuantumRegister(s) for s in new_reg_sizes] circ = _transform_registers(circ, new_qregs=new_qregs) assert circ.qregs == new_qregs assert _equal(from_qiskit(circ), from_qiskit(orig)) def test_transform_qregs_no_new_qregs(): qreg = qiskit.QuantumRegister(5) circ = qiskit.QuantumCircuit(qreg) circ = _transform_registers(circ, new_qregs=None) assert circ.qregs == [qreg] def test_transform_registers_too_few_qubits(): circ = qiskit.QuantumCircuit(qiskit.QuantumRegister(2)) new_qregs = [qiskit.QuantumRegister(1)] with pytest.raises(ValueError): _transform_registers(circ, new_qregs=new_qregs) def test_transform_registers_adds_idle_qubits(): """Tests transforming registers in a circuit with n qubits to a circuit with m > n qubits. """ qreg = qiskit.QuantumRegister(1) creg = qiskit.ClassicalRegister(1) circuit = qiskit.QuantumCircuit(qreg, creg) circuit.x(qreg[0]) circuit.measure(qreg[0], creg[0]) assert len(circuit.qregs) == 1 assert circuit.num_qubits == 1 old_data = copy.deepcopy(circuit.data) circuit = _transform_registers( circuit, new_qregs=[qreg, qiskit.QuantumRegister(4)] ) assert len(circuit.qregs) == 2 assert circuit.num_qubits == 5 assert circuit.data == old_data def test_transform_registers_wrong_reg_number(): nqubits = 2 circ = qiskit.QuantumCircuit(qiskit.QuantumRegister(nqubits)) new_qregs = [qiskit.QuantumRegister(1) for _ in range(2 * nqubits)] circ.add_register(*new_qregs) with pytest.raises(ValueError): _transform_registers(circ, new_qregs=new_qregs) @pytest.mark.parametrize("size", [5]) def test_measurement_order(size): q, c = qiskit.QuantumRegister(size), qiskit.ClassicalRegister(size) circuit = qiskit.QuantumCircuit(q, c) index_order = [int(i) for i in np.random.RandomState(1).permutation(size)] for i in index_order: circuit.measure(q[i], c[i]) order = _measurement_order(circuit) assert order == [(q[i], c[i]) for i in index_order] def test_add_identity_to_idle(): circuit = qiskit.QuantumCircuit(9) circuit.x([0, 8]) circuit.cx(0, 8) expected_idle_qubits = circuit.qubits[1:-1] idle_qubits = _add_identity_to_idle(circuit) id_qubits = [] for gates, qubits, cargs in circuit.get_instructions("id"): for qubit in qubits: id_qubits.append(qubit) assert idle_qubits == set(expected_idle_qubits) assert set(id_qubits) == idle_qubits def test_remove_identity_from_idle(): idle_indices = set(range(1, 8)) circuit = qiskit.QuantumCircuit(9) circuit.x([0, 8]) circuit.cx(0, 8) _remove_identity_from_idle(circuit, idle_indices) id_indices = [] for gates, qubits, cargs in circuit.get_instructions("id"): for qubit in qubits: id_indices.append(qubit.index) assert id_indices == [] def test_add_identity_to_idle_with_multiple_registers(): """Tests idle qubits are correctly detected even with many registers.""" circuit_multi_reg, circuit_single_reg = _multi_reg_circuits() _add_identity_to_idle(circuit_multi_reg) _add_identity_to_idle(circuit_single_reg) # The result should be the same for both types of registers assert _equal( convert_to_mitiq(circuit_multi_reg)[0], convert_to_mitiq(circuit_single_reg)[0], require_qubit_equality=False, # Qubit names can be different ) def test_remove_identity_from_idle_with_multiple_registers(): """Tests identities are correctly removed even with many registers.""" circuit_multi_reg, circuit_single_reg = _multi_reg_circuits() idle_qubits_multi = _add_identity_to_idle(circuit_multi_reg.copy()) idle_qubits_single = _add_identity_to_idle(circuit_single_reg.copy()) _remove_identity_from_idle(circuit_multi_reg, idle_qubits_multi) _remove_identity_from_idle(circuit_single_reg, idle_qubits_single) # Adding and removing identities should preserve the input input_multi, input_single = _multi_reg_circuits() assert circuit_multi_reg == input_multi assert circuit_single_reg == input_single
mitiq/mitiq/interface/mitiq_qiskit/tests/test_conversions_qiskit.py/0
{ "file_path": "mitiq/mitiq/interface/mitiq_qiskit/tests/test_conversions_qiskit.py", "repo_id": "mitiq", "token_count": 6436 }
27
# Copyright (C) Unitary Fund # # This source code is licensed under the GPL license (v3) found in the # LICENSE file in the root directory of this source tree. """High-level probabilistic error cancellation tools.""" import warnings from functools import wraps from typing import ( Any, Callable, Dict, List, Optional, Sequence, Tuple, Union, cast, ) import numpy as np from mitiq import QPROGRAM, Executor, Observable, QuantumResult from mitiq.pec import OperationRepresentation, sample_circuit class LargeSampleWarning(Warning): """Warning is raised when PEC sample size is greater than 10 ** 5""" pass _LARGE_SAMPLE_WARN = ( "The number of PEC samples is very large. It may take several minutes." " It may be necessary to reduce 'precision' or 'num_samples'." ) def execute_with_pec( circuit: QPROGRAM, executor: Union[Executor, Callable[[QPROGRAM], QuantumResult]], observable: Optional[Observable] = None, *, representations: Sequence[OperationRepresentation], precision: float = 0.03, num_samples: Optional[int] = None, force_run_all: bool = True, random_state: Optional[Union[int, np.random.RandomState]] = None, full_output: bool = False, ) -> Union[float, Tuple[float, Dict[str, Any]]]: r"""Estimates the error-mitigated expectation value associated to the input circuit, via the application of probabilistic error cancellation (PEC). :cite:`Temme_2017_PRL` :cite:`Endo_2018_PRX`. This function implements PEC by: 1. Sampling different implementable circuits from the quasi-probability representation of the input circuit; 2. Evaluating the noisy expectation values associated to the sampled circuits (through the "executor" function provided by the user); 3. Estimating the ideal expectation value from a suitable linear combination of the noisy ones. Args: circuit: The input circuit to execute with error-mitigation. executor: A Mitiq executor that executes a circuit and returns the unmitigated ``QuantumResult`` (e.g. an expectation value). observable: Observable to compute the expectation value of. If None, the `executor` must return an expectation value. Otherwise, the `QuantumResult` returned by `executor` is used to compute the expectation of the observable. representations: Representations (basis expansions) of each operation in the input circuit. precision: The desired estimation precision (assuming the observable is bounded by 1). The number of samples is deduced according to the formula (one_norm / precision) ** 2, where 'one_norm' is related to the negativity of the quasi-probability representation :cite:`Temme_2017_PRL`. If 'num_samples' is explicitly set by the user, 'precision' is ignored and has no effect. num_samples: The number of noisy circuits to be sampled for PEC. If not given, this is deduced from the argument 'precision'. force_run_all: If True, all sampled circuits are executed regardless of uniqueness, else a minimal unique set is executed. random_state: Seed for sampling circuits. full_output: If False only the average PEC value is returned. If True a dictionary containing all PEC data is returned too. Returns: The tuple ``(pec_value, pec_data)`` where ``pec_value`` is the expectation value estimated with PEC and ``pec_data`` is a dictionary which contains all the raw data involved in the PEC process (including the PEC estimation error). The error is estimated as ``pec_std / sqrt(num_samples)``, where ``pec_std`` is the standard deviation of the PEC samples, i.e., the square root of the mean squared deviation of the sampled values from ``pec_value``. If ``full_output`` is ``True``, only ``pec_value`` is returned. """ if isinstance(random_state, int): random_state = np.random.RandomState(random_state) if not (0 < precision <= 1): raise ValueError( "The value of 'precision' should be within the interval (0, 1]," f" but precision is {precision}." ) # Get the 1-norm of the circuit quasi-probability representation _, _, norm = sample_circuit( circuit, representations, num_samples=1, ) # Deduce the number of samples (if not given by the user) if not isinstance(num_samples, int): num_samples = int((norm / precision) ** 2) # Issue warning for very large sample size if num_samples > 10**5: warnings.warn(_LARGE_SAMPLE_WARN, LargeSampleWarning) # Sample all the circuits sampled_circuits, signs, _ = sample_circuit( circuit, representations, random_state=random_state, num_samples=num_samples, ) # Execute all sampled circuits if not isinstance(executor, Executor): executor = Executor(executor) results = executor.evaluate(sampled_circuits, observable, force_run_all) # Evaluate unbiased estimators [Temme2017] [Endo2018] [Takagi2020] unbiased_estimators = [norm * s * val for s, val in zip(signs, results)] pec_value = cast(float, np.average(unbiased_estimators)) if not full_output: return pec_value # Build dictionary with additional results and data pec_data: Dict[str, Any] = { "num_samples": num_samples, "precision": precision, "pec_value": pec_value, "pec_error": np.std(unbiased_estimators) / np.sqrt(num_samples), "unbiased_estimators": unbiased_estimators, "measured_expectation_values": results, "sampled_circuits": sampled_circuits, } return pec_value, pec_data def mitigate_executor( executor: Callable[[QPROGRAM], QuantumResult], observable: Optional[Observable] = None, *, representations: Sequence[OperationRepresentation], precision: float = 0.03, num_samples: Optional[int] = None, force_run_all: bool = True, random_state: Optional[Union[int, np.random.RandomState]] = None, full_output: bool = False, ) -> Callable[[QPROGRAM], Union[float, Tuple[float, Dict[str, Any]]]]: """Returns a modified version of the input 'executor' which is error-mitigated with probabilistic error cancellation (PEC). Args: executor: A function that executes a circuit and returns the unmitigated `QuantumResult` (e.g. an expectation value). observable: Observable to compute the expectation value of. If None, the `executor` must return an expectation value. Otherwise, the `QuantumResult` returned by `executor` is used to compute the expectation of the observable. representations: Representations (basis expansions) of each operation in the input circuit. precision: The desired estimation precision (assuming the observable is bounded by 1). The number of samples is deduced according to the formula (one_norm / precision) ** 2, where 'one_norm' is related to the negativity of the quasi-probability representation :cite:`Temme_2017_PRL`. If 'num_samples' is explicitly set, 'precision' is ignored and has no effect. num_samples: The number of noisy circuits to be sampled for PEC. If not given, this is deduced from the argument 'precision'. force_run_all: If True, all sampled circuits are executed regardless of uniqueness, else a minimal unique set is executed. random_state: Seed for sampling circuits. full_output: If False only the average PEC value is returned. If True a dictionary containing all PEC data is returned too. Returns: The error-mitigated version of the input executor. """ executor_obj = Executor(executor) if not executor_obj.can_batch: @wraps(executor) def new_executor( circuit: QPROGRAM, ) -> Union[float, Tuple[float, Dict[str, Any]]]: return execute_with_pec( circuit, executor, observable, representations=representations, precision=precision, num_samples=num_samples, force_run_all=force_run_all, random_state=random_state, full_output=full_output, ) else: @wraps(executor) def new_executor( circuits: List[QPROGRAM], ) -> List[Union[float, Tuple[float, Dict[str, Any]]]]: return [ execute_with_pec( circuit, executor, observable, representations=representations, precision=precision, num_samples=num_samples, force_run_all=force_run_all, random_state=random_state, full_output=full_output, ) for circuit in circuits ] return new_executor def pec_decorator( observable: Optional[Observable] = None, *, representations: Sequence[OperationRepresentation], precision: float = 0.03, num_samples: Optional[int] = None, force_run_all: bool = True, random_state: Optional[Union[int, np.random.RandomState]] = None, full_output: bool = False, ) -> Callable[ [Callable[[QPROGRAM], QuantumResult]], Callable[ [QPROGRAM], Union[float, Tuple[float, Dict[str, Any]]], ], ]: """Decorator which adds an error-mitigation layer based on probabilistic error cancellation (PEC) to an executor function, i.e., a function which executes a quantum circuit with an arbitrary backend and returns a ``QuantumResult`` (e.g. an expectation value). Args: observable: Observable to compute the expectation value of. If None, the `executor` function being decorated must return an expectation value. Otherwise, the `QuantumResult` returned by this `executor` is used to compute the expectation of the observable. representations: Representations (basis expansions) of each operation in the input circuit. precision: The desired estimation precision (assuming the observable is bounded by 1). The number of samples is deduced according to the formula (one_norm / precision) ** 2, where 'one_norm' is related to the negativity of the quasi-probability representation :cite:`Temme_2017_PRL`. If 'num_samples' is explicitly set by the user, 'precision' is ignored and has no effect. num_samples: The number of noisy circuits to be sampled for PEC. If not given, this is deduced from the argument 'precision'. force_run_all: If True, all sampled circuits are executed regardless of uniqueness, else a minimal unique set is executed. random_state: Seed for sampling circuits. full_output: If False only the average PEC value is returned. If True a dictionary containing all PEC data is returned too. Returns: The error-mitigating decorator to be applied to an executor function. """ def decorator( executor: Callable[[QPROGRAM], QuantumResult], ) -> Callable[[QPROGRAM], Union[float, Tuple[float, Dict[str, Any]]]]: return mitigate_executor( executor, observable, representations=representations, precision=precision, num_samples=num_samples, force_run_all=force_run_all, random_state=random_state, full_output=full_output, ) return decorator
mitiq/mitiq/pec/pec.py/0
{ "file_path": "mitiq/mitiq/pec/pec.py", "repo_id": "mitiq", "token_count": 4660 }
28
# Copyright (C) Unitary Fund # # This source code is licensed under the GPL license (v3) found in the # LICENSE file in the root directory of this source tree. import os import numpy as np import pytest import qiskit from cirq import ( Circuit, CXPowGate, DepolarizingChannel, I, LineQubit, MixedUnitaryChannel, Rx, Rz, X, Y, Z, ops, unitary, ) from mitiq import Executor, Observable, PauliString from mitiq.cdr import generate_training_circuits from mitiq.cdr._testing import random_x_z_cnot_circuit from mitiq.interface.mitiq_cirq import compute_density_matrix from mitiq.interface.mitiq_qiskit import qiskit_utils from mitiq.interface.mitiq_qiskit.conversions import to_qiskit from mitiq.pec.representations.learning import ( _parse_learning_kwargs, biased_noise_loss_function, depolarizing_noise_loss_function, learn_biased_noise_parameters, learn_depolarizing_noise_parameter, ) rng = np.random.RandomState(1) circuit = random_x_z_cnot_circuit( LineQubit.range(2), n_moments=5, random_state=rng ) # Set number of samples used to calculate mitigated value in loss function pec_kwargs = {"num_samples": 20, "random_state": 1} observable = Observable(PauliString("XZ"), PauliString("YY")) training_circuits = generate_training_circuits( circuit=circuit, num_training_circuits=3, fraction_non_clifford=0, method_select="uniform", method_replace="closest", ) CNOT_ops = list(circuit.findall_operations_with_gate_type(CXPowGate)) Rx_ops = list(circuit.findall_operations_with_gate_type(Rx)) Rz_ops = list(circuit.findall_operations_with_gate_type(Rz)) def ideal_execute(circ: Circuit) -> np.ndarray: return compute_density_matrix(circ, noise_level=(0.0,)) ideal_executor = Executor(ideal_execute) ideal_values = np.array(ideal_executor.evaluate(training_circuits, observable)) def biased_noise_channel(epsilon: float, eta: float) -> MixedUnitaryChannel: a = 1 - epsilon b = epsilon * (3 * eta + 1) / (3 * (eta + 1)) c = epsilon / (3 * (eta + 1)) mix = [ (a, unitary(I)), (b, unitary(Z)), (c, unitary(X)), (c, unitary(Y)), ] return ops.MixedUnitaryChannel(mix) @pytest.mark.parametrize("epsilon", [0.05, 0.1]) @pytest.mark.parametrize( "operations", [[Circuit(CNOT_ops[0][1])], [Circuit(Rx_ops[0][1])]] ) def test_depolarizing_noise_loss_function(epsilon, operations): """Test that the biased noise loss function value (calculated with error mitigation) is less than (or equal to) the loss calculated with the noisy (unmitigated) executor""" def noisy_execute(circ: Circuit) -> np.ndarray: noisy_circ = circ.with_noise(DepolarizingChannel(epsilon)) return ideal_execute(noisy_circ) noisy_executor = Executor(noisy_execute) noisy_values = np.array( noisy_executor.evaluate(training_circuits, observable) ) loss = depolarizing_noise_loss_function( epsilon=np.array([epsilon]), operations_to_mitigate=operations, training_circuits=training_circuits, ideal_values=ideal_values, noisy_executor=noisy_executor, pec_kwargs=pec_kwargs, observable=observable, ) assert loss <= np.mean((noisy_values - ideal_values) ** 2) @pytest.mark.parametrize("epsilon", [0, 0.7, 1]) @pytest.mark.parametrize("eta", [0, 1]) @pytest.mark.parametrize( "operations", [[Circuit(CNOT_ops[0][1])], [Circuit(Rx_ops[0][1])]] ) def test_biased_noise_loss_function(epsilon, eta, operations): """Test that the biased noise loss function value (calculated with error mitigation) is less than (or equal to) the loss calculated with the noisy (unmitigated) executor""" def noisy_execute(circ: Circuit) -> np.ndarray: noisy_circ = circ.with_noise(biased_noise_channel(epsilon, eta)) return ideal_execute(noisy_circ) noisy_executor = Executor(noisy_execute) noisy_values = np.array( noisy_executor.evaluate(training_circuits, observable) ) loss = biased_noise_loss_function( params=[epsilon, eta], operations_to_mitigate=operations, training_circuits=training_circuits, ideal_values=ideal_values, noisy_executor=noisy_executor, pec_kwargs=pec_kwargs, observable=observable, ) assert loss <= np.mean((noisy_values - ideal_values) ** 2) @pytest.mark.parametrize( "operations", [[Circuit(CNOT_ops[0][1])], [Circuit(Rz_ops[0][1])]] ) def test_biased_noise_loss_compare_ideal(operations): """Test that the loss function is zero when the noise strength is zero""" def noisy_execute(circ: Circuit) -> np.ndarray: noisy_circ = circ.with_noise(biased_noise_channel(0, 0)) return ideal_execute(noisy_circ) noisy_executor = Executor(noisy_execute) loss = biased_noise_loss_function( params=[0, 0], operations_to_mitigate=operations, training_circuits=training_circuits, ideal_values=ideal_values, noisy_executor=noisy_executor, pec_kwargs=pec_kwargs, observable=observable, ) assert np.isclose(loss, 0) @pytest.mark.parametrize( "operations", [ [to_qiskit(Circuit(CNOT_ops[0][1]))], [to_qiskit(Circuit(Rx_ops[0][1]))], [to_qiskit(Circuit(Rz_ops[0][1]))], ], ) def test_biased_noise_loss_function_qiskit(operations): """Test the learning function with initial noise strength and noise bias with a small offset from the simulated noise model values""" qiskit_circuit = to_qiskit(circuit) qiskit_training_circuits = generate_training_circuits( circuit=qiskit_circuit, num_training_circuits=3, fraction_non_clifford=0.2, method_select="uniform", method_replace="closest", random_state=rng, ) obs = Observable(PauliString("XY"), PauliString("ZZ")) def ideal_execute_qiskit(circ: qiskit.QuantumCircuit) -> float: return qiskit_utils.execute(circ, obs.matrix()) ideal_executor_qiskit = Executor(ideal_execute_qiskit) ideal_values = np.array( ideal_executor_qiskit.evaluate(qiskit_training_circuits) ) epsilon = 0.1 def noisy_execute_qiskit(circ: qiskit.QuantumCircuit) -> float: noise_model = qiskit_utils.initialized_depolarizing_noise(epsilon) return qiskit_utils.execute_with_noise(circ, obs.matrix(), noise_model) noisy_executor_qiskit = Executor(noisy_execute_qiskit) noisy_values = np.array( noisy_executor_qiskit.evaluate(qiskit_training_circuits) ) loss = biased_noise_loss_function( params=[epsilon, 0], operations_to_mitigate=operations, training_circuits=qiskit_training_circuits, ideal_values=ideal_values, noisy_executor=noisy_executor_qiskit, pec_kwargs=pec_kwargs, ) assert loss <= np.mean((noisy_values - ideal_values) ** 2) @pytest.mark.parametrize("epsilon", [0.05, 0.1]) def test_learn_depolarizing_noise_parameter(epsilon): """Test the learning function with initial noise strength with a small offset from the simulated noise model values""" operations_to_learn = [Circuit(op[1]) for op in CNOT_ops] offset = 0.1 def noisy_execute(circ: Circuit) -> np.ndarray: noisy_circ = circ.copy() insertions = [] for op in CNOT_ops: index = op[0] + 1 qubits = op[1].qubits for q in qubits: insertions.append((index, DepolarizingChannel(epsilon)(q))) noisy_circ.batch_insert(insertions) return ideal_execute(noisy_circ) noisy_executor = Executor(noisy_execute) epsilon0 = (1 - offset) * epsilon eps_string = str(epsilon).replace(".", "_") pec_data = np.loadtxt( os.path.join( "./mitiq/pec/representations/tests/learning_pec_data", f"learning_pec_data_eps_{eps_string}.txt", ) ) [success, epsilon_opt] = learn_depolarizing_noise_parameter( operations_to_learn=operations_to_learn, circuit=circuit, ideal_executor=ideal_executor, noisy_executor=noisy_executor, num_training_circuits=5, fraction_non_clifford=0.2, training_random_state=np.random.RandomState(1), epsilon0=epsilon0, observable=observable, learning_kwargs={"pec_data": pec_data}, ) assert success assert abs(epsilon_opt - epsilon) < offset * epsilon @pytest.mark.parametrize("epsilon", [0.05, 0.1]) @pytest.mark.parametrize("eta", [1, 2]) def test_learn_biased_noise_parameters(epsilon, eta): """Test the learning function can run without pre-executed data""" operations_to_learn = [Circuit(op[1]) for op in CNOT_ops] def noisy_execute(circ: Circuit) -> np.ndarray: noisy_circ = circ.copy() insertions = [] for op in CNOT_ops: index = op[0] + 1 qubits = op[1].qubits for q in qubits: insertions.append( (index, biased_noise_channel(epsilon, eta)(q)) ) noisy_circ.batch_insert(insertions) return ideal_execute(noisy_circ) noisy_executor = Executor(noisy_execute) eps_offset = 0.1 eta_offset = 0.2 epsilon0 = (1 - eps_offset) * epsilon eta0 = (1 - eta_offset) * eta num_training_circuits = 5 pec_data = np.zeros([122, 122, num_training_circuits]) eps_string = str(epsilon).replace(".", "_") for tc in range(0, num_training_circuits): pec_data[:, :, tc] = np.loadtxt( os.path.join( "./mitiq/pec/representations/tests/learning_pec_data", f"learning_pec_data_eps_{eps_string}eta_{eta}tc_{tc}.txt", ) ) [success, epsilon_opt, eta_opt] = learn_biased_noise_parameters( operations_to_learn=operations_to_learn, circuit=circuit, ideal_executor=ideal_executor, noisy_executor=noisy_executor, num_training_circuits=num_training_circuits, fraction_non_clifford=0.2, training_random_state=np.random.RandomState(1), epsilon0=epsilon0, eta0=eta0, observable=observable, learning_kwargs={"pec_data": pec_data}, ) assert success assert abs(epsilon_opt - epsilon) < eps_offset * epsilon assert abs(eta_opt - eta) < eta_offset * eta def test_empty_learning_kwargs(): learning_kwargs = {} pec_data, method, minimize_kwargs = _parse_learning_kwargs( learning_kwargs=learning_kwargs ) assert pec_data is None assert method == "Nelder-Mead" assert minimize_kwargs == {}
mitiq/mitiq/pec/representations/tests/test_learning.py/0
{ "file_path": "mitiq/mitiq/pec/representations/tests/test_learning.py", "repo_id": "mitiq", "token_count": 4648 }
29
# Copyright (C) Unitary Fund # # This source code is licensed under the GPL license (v3) found in the # LICENSE file in the root directory of this source tree. """Run experiments without error mitigation using the same interface as error mitigation.""" from mitiq.raw.raw import execute
mitiq/mitiq/raw/__init__.py/0
{ "file_path": "mitiq/mitiq/raw/__init__.py", "repo_id": "mitiq", "token_count": 74 }
30
# Copyright (C) Unitary Fund # # This source code is licensed under the GPL license (v3) found in the # LICENSE file in the root directory of this source tree. """Unit tests for quantum processing functions for classical shadows.""" import importlib from typing import Callable, List from unittest.mock import patch import cirq import cirq.testing import pytest from qiskit_aer import Aer import mitiq from mitiq import MeasurementResult from mitiq.interface.mitiq_cirq.cirq_utils import ( sample_bitstrings as cirq_sample_bitstrings, ) from mitiq.interface.mitiq_qiskit.conversions import to_qiskit from mitiq.interface.mitiq_qiskit.qiskit_utils import ( sample_bitstrings as qiskit_sample_bitstrings, ) from mitiq.shadows.quantum_processing import ( generate_random_pauli_strings, get_rotated_circuits, random_pauli_measurement, ) def test_tqdm_import_available(): # Test the case where tqdm is available import tqdm as tqdm_orig assert tqdm_orig is not None assert mitiq.shadows.quantum_processing.tqdm is not None def test_tqdm_import_not_available(): with patch.dict("sys.modules", {"tqdm": None}): importlib.reload( mitiq.shadows.quantum_processing ) # Reload the module to trigger the import assert mitiq.shadows.quantum_processing.tqdm is None # Reload the module again to restore the original tqdm import. # Otherwise, the rest of the tests are affected by the patch (issue #2318) importlib.reload(mitiq.shadows.quantum_processing) def test_generate_random_pauli_strings(): """Tests that the function generates random Pauli strings.""" num_qubits = 5 num_strings = 10 # Generate random pauli strings result = generate_random_pauli_strings(num_qubits, num_strings) # Check that the result is a list assert isinstance(result, List) # Check that the number of strings matches the input assert len(result) == num_strings # Check that each string has the right number of qubits for pauli_string in result: assert len(pauli_string) == num_qubits # Check that each string contains only the letters X, Y, and Z for pauli_string in result: assert set(pauli_string).issubset(set(["X", "Y", "Z"])) # Check that the function raises an exception for negative num_qubits # or num_strings with pytest.raises(ValueError): generate_random_pauli_strings(-1, num_strings) with pytest.raises(ValueError): generate_random_pauli_strings(num_qubits, -1) def cirq_executor(circuit: cirq.Circuit) -> MeasurementResult: return cirq_sample_bitstrings( circuit, noise_level=(0,), shots=1, sampler=cirq.Simulator(), ) def qiskit_executor(circuit: cirq.Circuit) -> MeasurementResult: return qiskit_sample_bitstrings( to_qiskit(circuit), noise_model=None, backend=Aer.get_backend("aer_simulator"), shots=1, measure_all=False, ) def test_get_rotated_circuits(): """Tests that the circuit is rotated.""" # define circuit circuit = cirq.Circuit() qubits = cirq.LineQubit.range(4) circuit.append(cirq.H(qubits[0])) circuit.append(cirq.CNOT(qubits[0], qubits[1])) circuit.append(cirq.CNOT(qubits[1], qubits[2])) circuit.append(cirq.CNOT(qubits[2], qubits[3])) # define the pauli measurements to be performed on the circuit pauli_strings = ["XYZX"] # Rotate the circuit. rotated_circuits = get_rotated_circuits(circuit, pauli_strings) # Verify that the circuit was rotated. circuit_1 = circuit.copy() circuit_1.append(cirq.H(qubits[0])) circuit_1.append(cirq.S(qubits[1]) ** -1) circuit_1.append(cirq.H(qubits[1])) circuit_1.append(cirq.H(qubits[3])) circuit_1.append(cirq.measure(*qubits)) assert rotated_circuits[0] == circuit_1 for rc in rotated_circuits: assert isinstance(rc, cirq.Circuit) # define a simple test circuit for the following tests def simple_test_circuit(qubits): circuit = cirq.Circuit() num_qubits = len(qubits) circuit.append(cirq.H.on_each(*qubits)) for i in range(num_qubits - 1): circuit.append(cirq.CNOT(qubits[i], qubits[i + 1])) return circuit @pytest.mark.parametrize("n_qubits", [1, 2, 5]) @pytest.mark.parametrize("executor", [cirq_executor, qiskit_executor]) def test_random_pauli_measurement_no_errors(n_qubits, executor): """Test that random_pauli_measurement runs without errors.""" qubits = cirq.LineQubit.range(n_qubits) circuit = simple_test_circuit(qubits) random_pauli_measurement( circuit, n_total_measurements=10, executor=executor ) @pytest.mark.parametrize("n_qubits", [1, 2, 5]) @pytest.mark.parametrize("executor", [cirq_executor, qiskit_executor]) def test_random_pauli_measurement_output_dimensions( n_qubits: int, executor: Callable ): """Test that random_pauli_measurement returns the correct output dimensions.""" qubits = cirq.LineQubit.range(n_qubits) circuit = simple_test_circuit(qubits) n_total_measurements = 10 shadow_outcomes, pauli_strings = random_pauli_measurement( circuit, n_total_measurements, executor=executor ) shadow_outcomes_shape = len(shadow_outcomes), len(shadow_outcomes[0]) pauli_strings_shape = len(pauli_strings), len(pauli_strings[0]) assert shadow_outcomes_shape == (n_total_measurements, n_qubits), ( f"Shadow outcomes have incorrect shape, expected " f"{(n_total_measurements, n_qubits)}, got {shadow_outcomes_shape}" ) assert pauli_strings_shape == (n_total_measurements, n_qubits), ( f"Pauli strings have incorrect shape, expected " f"{(n_total_measurements, n_qubits)}, got {pauli_strings_shape}" ) @pytest.mark.parametrize("n_qubits", [1, 2, 5]) @pytest.mark.parametrize("executor", [cirq_executor, qiskit_executor]) def test_random_pauli_measurement_output_types( n_qubits: int, executor: Callable ): """Test that random_pauli_measurement returns the correct output types.""" qubits = cirq.LineQubit.range(n_qubits) circuit = simple_test_circuit(qubits) shadow_outcomes, pauli_strings = random_pauli_measurement( circuit, n_total_measurements=10, executor=executor ) assert isinstance(shadow_outcomes[0], str) assert isinstance(pauli_strings[0], str)
mitiq/mitiq/shadows/tests/test_quantum_processing.py/0
{ "file_path": "mitiq/mitiq/shadows/tests/test_quantum_processing.py", "repo_id": "mitiq", "token_count": 2535 }
31
# Copyright (C) Unitary Fund # # This source code is licensed under the GPL license (v3) found in the # LICENSE file in the root directory of this source tree. """Functions for layer-wise unitary folding on supported circuits.""" from copy import deepcopy from typing import Callable, List import cirq import numpy as np from cirq import Moment, inverse from mitiq import QPROGRAM from mitiq.interface import accept_qprogram_and_validate from mitiq.utils import _append_measurements, _pop_measurements from mitiq.zne.scaling.folding import _check_foldable @accept_qprogram_and_validate def layer_folding( circuit: cirq.Circuit, layers_to_fold: List[int] ) -> cirq.Circuit: """Applies a variable amount of folding to select layers of a circuit. Note that this method only works for the univariate extrapolation methods. It allows a user to choose which layers in the input circuit will be scaled. .. seealso:: If you would prefer to use a multivariate extrapolation method for unitary folding, use :func:`mitiq.lre.multivariate_scaling.layerwise_folding` instead. The layerwise folding required for multivariate extrapolation is different as the layers in the input circuit have to be scaled in a specific pattern. The required specific pattern for multivariate extrapolation does not allow a user to provide a choice of which layers to fold. Args: circuit: The input circuit. layers_to_fold: A list with the index referring to the layer number, and the element filled by an integer representing the number of times the layer is folded. Returns: The folded circuit. """ folded = deepcopy(circuit) measurements = _pop_measurements(folded) layers = [] for i, layer in enumerate(folded): layers.append(layer) # Apply the requisite number of folds to each layer. num_fold = layers_to_fold[i] for _ in range(num_fold): # We only fold the layer if it does not contain a measurement. if not cirq.is_measurement(layer): layers.append(Moment(inverse(layer))) layers.append(Moment(layer)) # We combine each layer into a single circuit. combined_circuit = cirq.Circuit() for layer in layers: combined_circuit.append(layer) _append_measurements(combined_circuit, measurements) return combined_circuit def get_layer_folding( layer_index: int, ) -> Callable[[QPROGRAM, float], QPROGRAM]: """Return function to perform folding. The function return can be used as an argument to define the noise scaling within the `execute_with_zne` function. Args: layer_index: The layer of the circuit to apply folding to. Returns: The function for folding the ith layer. """ @accept_qprogram_and_validate def fold_ith_layer( circuit: cirq.Circuit, scale_factor: int ) -> cirq.Circuit: """Returns a circuit folded according to integer scale factors. Args: circuit: Circuit to fold. scale_factor: Factor to scale the circuit by. Returns: The folded quantum circuit. """ _check_foldable(circuit) layers = [0] * len(circuit) num_folds = (scale_factor - 1) // 2 if np.isclose(num_folds, int(num_folds)): num_folds = int(num_folds) layers[layer_index] = num_folds folded = layer_folding(circuit, layers_to_fold=layers) return folded return fold_ith_layer
mitiq/mitiq/zne/scaling/layer_scaling.py/0
{ "file_path": "mitiq/mitiq/zne/scaling/layer_scaling.py", "repo_id": "mitiq", "token_count": 1369 }
32
""" Sphinx extension to add ReadTheDocs-style "Edit on GitHub" links to the sidebar. Loosely based on https://github.com/astropy/astropy/pull/347 """ import os import warnings __licence__ = 'BSD (3 clause)' def get_github_url(app, view, path): return 'https://github.com/{project}/{view}/{branch}/{path}'.format( project=app.config.edit_on_github_project, view=view, branch=app.config.edit_on_github_branch, path=path) def html_page_context(app, pagename, templatename, context, doctree): if templatename != 'page.html': return if not app.config.edit_on_github_project: warnings.warn("edit_on_github_project not specified") return if not doctree: return path = os.path.relpath(doctree.get('source'), app.builder.srcdir) show_url = get_github_url(app, 'blob', path) edit_url = get_github_url(app, 'edit', path) context['show_on_github_url'] = show_url context['edit_on_github_url'] = edit_url def setup(app): app.add_config_value('edit_on_github_project', '', True) app.add_config_value('edit_on_github_branch', 'master', True) app.connect('html-page-context', html_page_context)
pennylane-qiskit/doc/_ext/edit_on_github.py/0
{ "file_path": "pennylane-qiskit/doc/_ext/edit_on_github.py", "repo_id": "pennylane-qiskit", "token_count": 489 }
33
.. include:: ../README.rst :start-after: installation-start-inclusion-marker-do-not-remove :end-before: installation-end-inclusion-marker-do-not-remove
pennylane-qiskit/doc/installation.rst/0
{ "file_path": "pennylane-qiskit/doc/installation.rst", "repo_id": "pennylane-qiskit", "token_count": 57 }
34
# Copyright 2021-2024 Xanadu Quantum Technologies Inc. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. r""" This module contains some configuration for PennyLane IBMQ devices. """ import os import pytest import numpy as np import pennylane as qml from qiskit_ibm_provider import IBMProvider from pennylane_qiskit import AerDevice, BasicSimulatorDevice # pylint: disable=protected-access, unused-argument, redefined-outer-name np.random.seed(42) U = np.array( [ [0.83645892 - 0.40533293j, -0.20215326 + 0.30850569j], [-0.23889780 - 0.28101519j, -0.88031770 - 0.29832709j], ] ) U2 = np.array([[0, 1, 1, 1], [1, 0, 1, -1], [1, -1, 0, 1], [1, 1, -1, 0]]) / np.sqrt(3) A = np.array([[1.02789352, 1.61296440 - 0.3498192j], [1.61296440 + 0.3498192j, 1.23920938 + 0j]]) test_devices = [AerDevice, BasicSimulatorDevice] hw_backends = ["qasm_simulator", "aer_simulator", "basic_simulator"] state_backends = [ "statevector_simulator", "unitary_simulator", "aer_simulator_statevector", "aer_simulator_unitary", ] @pytest.fixture def skip_if_no_account(): t = os.getenv("IBMQX_TOKEN", None) try: IBMProvider(token=t) except: # pylint: disable=broad-except, bare-except missing = "token" if t else "account" pytest.skip(f"Skipping test, no IBMQ {missing} available") @pytest.fixture def skip_if_account_saved(): if IBMProvider.saved_accounts(): pytest.skip("Skipping test, IBMQ will load an account successfully") @pytest.fixture def tol(shots): if shots is None: return {"atol": 0.01, "rtol": 0} return {"atol": 0.05, "rtol": 0.1} @pytest.fixture def init_state(scope="session"): def _init_state(n): state = np.random.random([2**n]) + np.random.random([2**n]) * 1j state /= np.linalg.norm(state) return state return _init_state @pytest.fixture def skip_unitary(backend): if "unitary" in backend: pytest.skip("This test does not support the unitary simulator backend.") @pytest.fixture def run_only_for_unitary(backend): if "unitary" not in backend: pytest.skip("This test only supports the unitary simulator.") @pytest.fixture(params=state_backends + hw_backends) def backend(request): return request.param @pytest.fixture(params=state_backends) def statevector_backend(request): return request.param @pytest.fixture(params=hw_backends) def hardware_backend(request): return request.param @pytest.fixture(params=test_devices) def device(request, backend, shots): print("getting a device") if backend not in state_backends: if shots is None: pytest.skip("Hardware simulators do not support analytic mode") if backend == "aer_simulator" and not issubclass(request.param, AerDevice): print("I should be skipping this test") pytest.skip("Only the AerDevice can use the aer_simulator backend") if issubclass(request.param, BasicSimulatorDevice) and backend != "basic_simulator": pytest.skip("BasicSimulator is the only supported backend for the BasicSimulatorDevice") if backend == "basic_simulator" and not issubclass(request.param, BasicSimulatorDevice): pytest.skip("BasicSimulator is the only supported backend for the BasicSimulatorDevice") def _device(n, device_options=None): if device_options is None: device_options = {} return request.param(wires=n, backend=backend, shots=shots, **device_options) return _device @pytest.fixture(params=test_devices) def state_vector_device(request, statevector_backend, shots): if backend == "aer_simulator" and not issubclass(request.param, AerDevice): pytest.skip("Only the AerDevice can use the aer_simulator backend") if issubclass(request.param, BasicSimulatorDevice) and backend != "basic_simulator": pytest.skip("BasicSimulator is the only supported backend for the BasicSimulatorDevice") if backend == "basic_simulator" and not issubclass(request.param, BasicSimulatorDevice): pytest.skip("BasicSimulator is the only supported backend for the BasicSimulatorDevice") def _device(n): return request.param(wires=n, backend=statevector_backend, shots=shots) return _device @pytest.fixture(scope="function") def mock_device(monkeypatch): """A mock instance of the abstract Device class""" with monkeypatch.context() as m: dev = qml.Device m.setattr(dev, "__abstractmethods__", frozenset()) yield qml.Device() @pytest.fixture(scope="function") def recorder(): return qml.tape.OperationRecorder() @pytest.fixture(scope="function") def qubit_device_single_wire(): return qml.device("default.qubit", wires=1) @pytest.fixture(scope="function") def qubit_device_2_wires(): return qml.device("default.qubit", wires=2)
pennylane-qiskit/tests/conftest.py/0
{ "file_path": "pennylane-qiskit/tests/conftest.py", "repo_id": "pennylane-qiskit", "token_count": 1956 }
35
<p align="center"> <!-- Tests (GitHub actions) --> <a href="https://github.com/PennyLaneAI/pennylane/actions?query=workflow%3ATests"> <img src="https://img.shields.io/github/actions/workflow/status/PennyLaneAI/PennyLane/tests.yml?branch=master&style=flat-square" /> </a> <!-- CodeCov --> <a href="https://codecov.io/gh/PennyLaneAI/pennylane"> <img src="https://img.shields.io/codecov/c/github/PennyLaneAI/pennylane/master.svg?logo=codecov&style=flat-square" /> </a> <!-- ReadTheDocs --> <a href="https://docs.pennylane.ai/en/latest"> <img src="https://readthedocs.com/projects/xanaduai-pennylane/badge/?version=latest&style=flat-square" /> </a> <!-- PyPI --> <a href="https://pypi.org/project/PennyLane"> <img src="https://img.shields.io/pypi/v/PennyLane.svg?style=flat-square" /> </a> <!-- Forum --> <a href="https://discuss.pennylane.ai"> <img src="https://img.shields.io/discourse/https/discuss.pennylane.ai/posts.svg?logo=discourse&style=flat-square" /> </a> <!-- License --> <a href="https://www.apache.org/licenses/LICENSE-2.0"> <img src="https://img.shields.io/pypi/l/PennyLane.svg?logo=apache&style=flat-square" /> </a> </p> <p align="center"> <a href="https://pennylane.ai">PennyLane</a> is a cross-platform Python library for <a href="https://pennylane.ai/qml/quantum-computing/">quantum computing</a>, <a href="https://pennylane.ai/qml/quantum-machine-learning/">quantum machine learning</a>, and <a href="https://pennylane.ai/qml/quantum-chemistry/">quantum chemistry</a>. </p> <p align="center"> <strong>Train a quantum computer the same way as a neural network.</strong> <img src="https://raw.githubusercontent.com/PennyLaneAI/pennylane/master/doc/_static/header.png#gh-light-mode-only" width="700px"> <!-- Use a relative import for the dark mode image. When loading on PyPI, this will fail automatically and show nothing. --> <img src="./doc/_static/header-dark-mode.png#gh-dark-mode-only" width="700px" onerror="this.style.display='none'" alt=""/> </p> ## Key Features <img src="https://raw.githubusercontent.com/PennyLaneAI/pennylane/master/doc/_static/code.png" width="400px" align="right"> - *Machine learning on quantum hardware*. Connect to quantum hardware using **PyTorch**, **TensorFlow**, **JAX**, **Keras**, or **NumPy**. Build rich and flexible hybrid quantum-classical models. - *Just in time compilation*. Experimental support for just-in-time compilation. Compile your entire hybrid workflow, with support for advanced features such as adaptive circuits, real-time measurement feedback, and unbounded loops. See [Catalyst](https://github.com/pennylaneai/catalyst) for more details. - *Device-independent*. Run the same quantum circuit on different quantum backends. Install [plugins](https://pennylane.ai/plugins.html) to access even more devices, including **Strawberry Fields**, **Amazon Braket**, **IBM Q**, **Google Cirq**, **Rigetti Forest**, **Qulacs**, **Pasqal**, **Honeywell**, and more. - *Follow the gradient*. Hardware-friendly **automatic differentiation** of quantum circuits. - *Batteries included*. Built-in tools for **quantum machine learning**, **optimization**, and **quantum chemistry**. Rapidly prototype using built-in quantum simulators with backpropagation support. ## Installation PennyLane requires Python version 3.9 and above. Installation of PennyLane, as well as all dependencies, can be done using pip: ```console python -m pip install pennylane ``` ## Docker support **Docker** support exists for building using **CPU** and **GPU** (Nvidia CUDA 11.1+) images. [See a more detailed description here](https://pennylane.readthedocs.io/en/stable/development/guide/installation.html#docker). ## Getting started For an introduction to quantum machine learning, guides and resources are available on PennyLane's [quantum machine learning hub](https://pennylane.ai/qml/): <img src="https://raw.githubusercontent.com/PennyLaneAI/pennylane/master/doc/_static/readme/gpu_to_qpu.png" align="right" width="400px"> * [What is quantum machine learning?](https://pennylane.ai/qml/whatisqml.html) * [QML tutorials and demos](https://pennylane.ai/qml/demonstrations.html) * [Frequently asked questions](https://pennylane.ai/faq.html) * [Key concepts of QML](https://pennylane.ai/qml/glossary.html) * [QML videos](https://pennylane.ai/qml/videos.html) You can also check out our [documentation](https://pennylane.readthedocs.io) for [quickstart guides](https://pennylane.readthedocs.io/en/stable/introduction/pennylane.html) to using PennyLane, and detailed developer guides on [how to write your own](https://pennylane.readthedocs.io/en/stable/development/plugins.html) PennyLane-compatible quantum device. ## Tutorials and demonstrations Take a deeper dive into quantum machine learning by exploring cutting-edge algorithms on our [demonstrations page](https://pennylane.ai/qml/demonstrations.html). <a href="https://pennylane.ai/qml/demonstrations.html"> <img src="https://raw.githubusercontent.com/PennyLaneAI/pennylane/master/doc/_static/readme/demos.png" width="900px"> </a> All demonstrations are fully executable, and can be downloaded as Jupyter notebooks and Python scripts. If you would like to contribute your own demo, see our [demo submission guide](https://pennylane.ai/qml/demos_submission.html). ## Videos Seeing is believing! Check out [our videos](https://pennylane.ai/qml/videos.html) to learn about PennyLane, quantum computing concepts, and more. <a href="https://pennylane.ai/qml/videos.html"> <img src="https://raw.githubusercontent.com/PennyLaneAI/pennylane/master/doc/_static/readme/videos.png" width="900px"> </a> ## Contributing to PennyLane We welcome contributions—simply fork the PennyLane repository, and then make a [pull request](https://help.github.com/articles/about-pull-requests/) containing your contribution. All contributors to PennyLane will be listed as authors on the releases. All users who contribute significantly to the code (new plugins, new functionality, etc.) will be listed on the PennyLane arXiv paper. We also encourage bug reports, suggestions for new features and enhancements, and even links to cool projects or applications built on PennyLane. See our [contributions page](https://github.com/PennyLaneAI/pennylane/blob/master/.github/CONTRIBUTING.md) and our [developer hub](https://pennylane.readthedocs.io/en/stable/development/guide.html) for more details. ## Support - **Source Code:** https://github.com/PennyLaneAI/pennylane - **Issue Tracker:** https://github.com/PennyLaneAI/pennylane/issues If you are having issues, please let us know by posting the issue on our GitHub issue tracker. We also have a [PennyLane discussion forum](https://discuss.pennylane.ai)—come join the community and chat with the PennyLane team. Note that we are committed to providing a friendly, safe, and welcoming environment for all. Please read and respect the [Code of Conduct](.github/CODE_OF_CONDUCT.md). ## Authors PennyLane is the work of [many contributors](https://github.com/PennyLaneAI/pennylane/graphs/contributors). If you are doing research using PennyLane, please cite [our paper](https://arxiv.org/abs/1811.04968): > Ville Bergholm et al. *PennyLane: Automatic differentiation of hybrid quantum-classical > computations.* 2018. arXiv:1811.04968 ## License PennyLane is **free** and **open source**, released under the Apache License, Version 2.0.
pennylane/README.md/0
{ "file_path": "pennylane/README.md", "repo_id": "pennylane", "token_count": 2496 }
36
# Copyright 2018-2021 Xanadu Quantum Technologies Inc. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ This file automatically generates and saves a series of example pictures for the circuit drawer. This will be useful during early stages when the project is still undergoing cosmetic changes. """ import pathlib import matplotlib.pyplot as plt from pennylane.drawer import MPLDrawer from pennylane.drawer.style import _set_style folder = pathlib.Path(__file__).parent def labels(savefile="labels_test.png"): drawer = MPLDrawer(n_wires=2, n_layers=1) drawer.label(["a", "b"]) plt.savefig(folder / savefile) plt.close() def labels_formatted(savefile="labels_formatted.png"): drawer = MPLDrawer(n_wires=2, n_layers=1) drawer.label(["a", "b"], text_options={"color": "indigo", "fontsize": "xx-large"}) plt.savefig(folder / savefile) plt.close() def box_gates(savefile="box_gates.png"): drawer = MPLDrawer(n_wires=2, n_layers=1) drawer.box_gate(layer=0, wires=(0, 1), text="CY") plt.savefig(folder / savefile) plt.close() def box_gates_formatted(savefile="box_gates_formatted.png"): box_options = {"facecolor": "lightcoral", "edgecolor": "maroon", "linewidth": 5} text_options = {"fontsize": "xx-large", "color": "maroon"} drawer = MPLDrawer(n_wires=2, n_layers=1) drawer.box_gate( layer=0, wires=(0, 1), text="CY", box_options=box_options, text_options=text_options ) plt.savefig(folder / savefile) plt.close() def autosize(savefile="box_gates_autosized.png"): drawer = MPLDrawer(n_layers=4, n_wires=2) drawer.box_gate(layer=0, wires=0, text="A longer label") drawer.box_gate(layer=0, wires=1, text="Label") drawer.box_gate(layer=1, wires=(0, 1), text="long multigate label") drawer.box_gate(layer=3, wires=(0, 1), text="Not autosized label", autosize=False) plt.savefig(folder / savefile) plt.close() def ctrl(savefile="ctrl.png"): drawer = MPLDrawer(n_wires=2, n_layers=3) drawer.ctrl(layer=0, wires=0, wires_target=1) drawer.ctrl(layer=1, wires=(0, 1), control_values=[0, 1]) options = {"color": "indigo", "linewidth": 4} drawer.ctrl(layer=2, wires=(0, 1), control_values=[1, 0], options=options) plt.savefig(folder / savefile) plt.close() def cond(savefile="cond.png"): drawer = MPLDrawer(n_wires=3, n_layers=4) drawer.cond(layer=1, measured_layer=0, wires=[0], wires_target=[1]) options = {'color': "indigo", 'linewidth': 1.5} drawer.cond(layer=3, measured_layer=2, wires=(1,), wires_target=(2,), options=options) plt.savefig(folder / savefile) plt.close() def CNOT(savefile="cnot.png"): drawer = MPLDrawer(n_wires=2, n_layers=2) drawer.CNOT(0, (0, 1)) options = {"color": "indigo", "linewidth": 4} drawer.CNOT(1, (1, 0), options=options) plt.savefig(folder / savefile) plt.close() def SWAP(savefile="SWAP.png"): drawer = MPLDrawer(n_wires=2, n_layers=2) drawer.SWAP(0, (0, 1)) swap_options = {"linewidth": 2, "color": "indigo"} drawer.SWAP(1, (0, 1), options=swap_options) plt.savefig(folder / savefile) plt.close() def measure(savefile="measure.png"): drawer = MPLDrawer(n_wires=2, n_layers=1) drawer.measure(layer=0, wires=0) measure_box = {"facecolor": "white", "edgecolor": "indigo"} measure_lines = {"edgecolor": "indigo", "facecolor": "plum", "linewidth": 2} drawer.measure(layer=0, wires=1, box_options=measure_box, lines_options=measure_lines) plt.savefig(folder / savefile) plt.close() def integration(style="default", savefile="example_basic.png"): _set_style(style) drawer = MPLDrawer(n_wires=5, n_layers=6) drawer.label(["0", "a", r"$|\Psi\rangle$", r"$|\theta\rangle$", "aux"]) drawer.box_gate(0, [0, 1, 2, 3, 4], "Entangling Layers") drawer.box_gate(1, [0, 2, 3], "U(θ)") drawer.box_gate(1, 4, "Z") drawer.SWAP(2, (3, 4)) drawer.CNOT(2, (0, 2)) drawer.ctrl(3, [1, 3], control_values=[True, False]) drawer.box_gate( layer=3, wires=2, text="H", box_options={"zorder": 4}, text_options={"zorder": 5} ) drawer.ctrl(4, [1, 2]) drawer.measure(5, 0) drawer.fig.suptitle("My Circuit", fontsize="xx-large") plt.savefig(folder / savefile) _set_style("default") plt.close() def integration_rcParams(savefile="example_rcParams.png"): plt.rcParams["patch.facecolor"] = "mistyrose" plt.rcParams["patch.edgecolor"] = "maroon" plt.rcParams["text.color"] = "maroon" plt.rcParams["font.weight"] = "bold" plt.rcParams["patch.linewidth"] = 4 plt.rcParams["patch.force_edgecolor"] = True plt.rcParams["lines.color"] = "indigo" plt.rcParams["lines.linewidth"] = 5 plt.rcParams["figure.facecolor"] = "ghostwhite" drawer = MPLDrawer(n_wires=5, n_layers=5) drawer = MPLDrawer(n_wires=5, n_layers=6) drawer.label(["0", "a", r"$|\Psi\rangle$", r"$|\theta\rangle$", "aux"]) drawer.box_gate(0, [0, 1, 2, 3, 4], "Entangling Layers") drawer.box_gate(1, [0, 2, 3], "U(θ)") drawer.box_gate(1, 4, "Z") drawer.SWAP(2, (3, 4)) drawer.CNOT(2, (0, 2)) drawer.ctrl(3, [1, 3], control_values=[True, False]) drawer.box_gate( layer=3, wires=2, text="H", box_options={"zorder": 4}, text_options={"zorder": 5} ) drawer.ctrl(4, [1, 2]) drawer.measure(5, 0) drawer.fig.suptitle("My Circuit", fontsize="xx-large") plt.savefig(folder / savefile) _set_style("default") plt.close() def integration_formatted(savefile="example_formatted.png"): wire_options = {"color": "indigo", "linewidth": 4} drawer = MPLDrawer(n_wires=2, n_layers=4, wire_options=wire_options) label_options = {"fontsize": "x-large", "color": "indigo"} drawer.label(["0", "a"], text_options=label_options) box_options = {"facecolor": "lightcoral", "edgecolor": "maroon", "linewidth": 5} text_options = {"fontsize": "xx-large", "color": "maroon"} drawer.box_gate(layer=0, wires=0, text="Z", box_options=box_options, text_options=text_options) swap_options = {"linewidth": 4, "color": "darkgreen"} drawer.SWAP(layer=1, wires=(0, 1), options=swap_options) ctrl_options = {"linewidth": 4, "color": "teal"} drawer.CNOT(layer=2, wires=(0, 1), options=ctrl_options) drawer.ctrl(layer=3, wires=(0, 1), options=ctrl_options) measure_box = {"facecolor": "white", "edgecolor": "indigo"} measure_lines = {"edgecolor": "indigo", "facecolor": "plum", "linewidth": 2} for wire in range(2): drawer.measure(layer=4, wires=wire, box_options=measure_box, lines_options=measure_lines) drawer.fig.suptitle("My Circuit", fontsize="xx-large") plt.savefig(folder / savefile) plt.close() def float_layer(savefile="float_layer.png"): drawer = MPLDrawer(2, 2) drawer.box_gate(layer=0.5, wires=0, text="Big Gate", extra_width=0.5) drawer.box_gate(layer=0, wires=1, text="X") drawer.box_gate(layer=1, wires=1, text="Y") plt.savefig(folder / savefile) plt.close() if __name__ == "__main__": labels() labels_formatted() box_gates() box_gates_formatted() autosize() ctrl() CNOT() SWAP() measure() integration() float_layer() integration(style="black_white", savefile="black_white_style.png") integration_rcParams() integration_formatted() cond()
pennylane/doc/_static/drawer/mpldrawer_examples.py/0
{ "file_path": "pennylane/doc/_static/drawer/mpldrawer_examples.py", "repo_id": "pennylane", "token_count": 3296 }
37
% Q-circuit version 1.06 % Copyright (C) 2004 Steve Flammia & Bryan Eastin % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA \usepackage[matrix,frame,arrow]{xy} \usepackage{amsmath} \newcommand{\bra}[1]{\left\langle{#1}\right\vert} \newcommand{\ket}[1]{\left\vert{#1}\right\rangle} % Defines Dirac notation. \newcommand{\qw}[1][-1]{\ar @{-} [0,#1]} % Defines a wire that connects horizontally. By default it connects to the object on the left of the current object. % WARNING: Wire commands must appear after the gate in any given entry. \newcommand{\qwx}[1][-1]{\ar @{-} [#1,0]} % Defines a wire that connects vertically. By default it connects to the object above the current object. % WARNING: Wire commands must appear after the gate in any given entry. \newcommand{\cw}[1][-1]{\ar @{=} [0,#1]} % Defines a classical wire that connects horizontally. By default it connects to the object on the left of the current object. % WARNING: Wire commands must appear after the gate in any given entry. \newcommand{\cwx}[1][-1]{\ar @{=} [#1,0]} % Defines a classical wire that connects vertically. By default it connects to the object above the current object. % WARNING: Wire commands must appear after the gate in any given entry. \newcommand{\gate}[1]{*{\xy *+<.6em>{#1};p\save+LU;+RU **\dir{-}\restore\save+RU;+RD **\dir{-}\restore\save+RD;+LD **\dir{-}\restore\POS+LD;+LU **\dir{-}\endxy} \qw} % Boxes the argument, making a gate. \newcommand{\meter}{\gate{\xy *!<0em,1.1em>h\cir<1.1em>{ur_dr},!U-<0em,.4em>;p+<.5em,.9em> **h\dir{-} \POS <-.6em,.4em> *{},<.6em,-.4em> *{} \endxy}} % Inserts a measurement meter. \newcommand{\measure}[1]{*+[F-:<.9em>]{#1} \qw} % Inserts a measurement bubble with user defined text. \newcommand{\measuretab}[1]{*{\xy *+<.6em>{#1};p\save+LU;+RU **\dir{-}\restore\save+RU;+RD **\dir{-}\restore\save+RD;+LD **\dir{-}\restore\save+LD;+LC-<.5em,0em> **\dir{-} \restore\POS+LU;+LC-<.5em,0em> **\dir{-} \endxy} \qw} % Inserts a measurement tab with user defined text. \newcommand{\measureD}[1]{*{\xy*+=+<.5em>{\vphantom{#1}}*\cir{r_l};p\save*!R{#1} \restore\save+UC;+UC-<.5em,0em>*!R{\hphantom{#1}}+L **\dir{-} \restore\save+DC;+DC-<.5em,0em>*!R{\hphantom{#1}}+L **\dir{-} \restore\POS+UC-<.5em,0em>*!R{\hphantom{#1}}+L;+DC-<.5em,0em>*!R{\hphantom{#1}}+L **\dir{-} \endxy} \qw} % Inserts a D-shaped measurement gate with user defined text. \newcommand{\multimeasure}[2]{*+<1em,.9em>{\hphantom{#2}} \qw \POS[0,0].[#1,0];p !C *{#2},p \drop\frm<.9em>{-}} % Draws a multiple qubit measurement bubble starting at the current position and spanning #1 additional gates below. % #2 gives the label for the gate. % You must use an argument of the same width as #2 in \ghost for the wires to connect properly on the lower lines. \newcommand{\multimeasureD}[2]{*+<1em,.9em>{\hphantom{#2}}\save[0,0].[#1,0];p\save !C *{#2},p+LU+<0em,0em>;+RU+<-.8em,0em> **\dir{-}\restore\save +LD;+LU **\dir{-}\restore\save +LD;+RD-<.8em,0em> **\dir{-} \restore\save +RD+<0em,.8em>;+RU-<0em,.8em> **\dir{-} \restore \POS !UR*!UR{\cir<.9em>{r_d}};!DR*!DR{\cir<.9em>{d_l}}\restore \qw} % Draws a multiple qubit D-shaped measurement gate starting at the current position and spanning #1 additional gates below. % #2 gives the label for the gate. % You must use an argument of the same width as #2 in \ghost for the wires to connect properly on the lower lines. \newcommand{\control}{*-=-{\bullet}} % Inserts an unconnected control. \newcommand{\controlo}{*!<0em,.04em>-<.07em,.11em>{\xy *=<.45em>[o][F]{}\endxy}} % Inserts a unconnected control-on-0. \newcommand{\ctrl}[1]{\control \qwx[#1] \qw} % Inserts a control and connects it to the object #1 wires below. \newcommand{\ctrlo}[1]{\controlo \qwx[#1] \qw} % Inserts a control-on-0 and connects it to the object #1 wires below. \newcommand{\targ}{*{\xy{<0em,0em>*{} \ar @{ - } +<.4em,0em> \ar @{ - } -<.4em,0em> \ar @{ - } +<0em,.4em> \ar @{ - } -<0em,.4em>},*+<.8em>\frm{o}\endxy} \qw} % Inserts a CNOT target. \newcommand{\qswap}{*=<0em>{\times} \qw} % Inserts half a swap gate. % Must be connected to the other swap with \qwx. \newcommand{\multigate}[2]{*+<1em,.9em>{\hphantom{#2}} \qw \POS[0,0].[#1,0];p !C *{#2},p \save+LU;+RU **\dir{-}\restore\save+RU;+RD **\dir{-}\restore\save+RD;+LD **\dir{-}\restore\save+LD;+LU **\dir{-}\restore} % Draws a multiple qubit gate starting at the current position and spanning #1 additional gates below. % #2 gives the label for the gate. % You must use an argument of the same width as #2 in \ghost for the wires to connect properly on the lower lines. \newcommand{\ghost}[1]{*+<1em,.9em>{\hphantom{#1}} \qw} % Leaves space for \multigate on wires other than the one on which \multigate appears. Without this command wires will cross your gate. % #1 should match the second argument in the corresponding \multigate. \newcommand{\push}[1]{*{#1}} % Inserts #1, overriding the default that causes entries to have zero size. This command takes the place of a gate. % Like a gate, it must precede any wire commands. % \push is useful for forcing columns apart. % NOTE: It might be useful to know that a gate is about 1.3 times the height of its contents. I.e. \gate{M} is 1.3em tall. % WARNING: \push must appear before any wire commands and may not appear in an entry with a gate or label. \newcommand{\gategroup}[6]{\POS"#1,#2"."#3,#2"."#1,#4"."#3,#4"!C*+<#5>\frm{#6}} % Constructs a box or bracket enclosing the square block spanning rows #1-#3 and columns=#2-#4. % The block is given a margin #5/2, so #5 should be a valid length. % #6 can take the following arguments -- or . or _\} or ^\} or \{ or \} or _) or ^) or ( or ) where the first two options yield dashed and % dotted boxes respectively, and the last eight options yield bottom, top, left, and right braces of the curly or normal variety. % \gategroup can appear at the end of any gate entry, but it's good form to pick one of the corner gates. % BUG: \gategroup uses the four corner gates to determine the size of the bounding box. Other gates may stick out of that box. See \prop. \newcommand{\rstick}[1]{*!L!<-.5em,0em>=<0em>{#1}} % Centers the left side of #1 in the cell. Intended for lining up wire labels. Note that non-gates have default size zero. \newcommand{\lstick}[1]{*!R!<.5em,0em>=<0em>{#1}} % Centers the right side of #1 in the cell. Intended for lining up wire labels. Note that non-gates have default size zero. \newcommand{\ustick}[1]{*!D!<0em,-.5em>=<0em>{#1}} % Centers the bottom of #1 in the cell. Intended for lining up wire labels. Note that non-gates have default size zero. \newcommand{\dstick}[1]{*!U!<0em,.5em>=<0em>{#1}} % Centers the top of #1 in the cell. Intended for lining up wire labels. Note that non-gates have default size zero. \newcommand{\Qcircuit}{\xymatrix @*=<0em>} % Defines \Qcircuit as an \xymatrix with entries of default size 0em.
pennylane/doc/_static/qcircuit/Qcircuit.tex/0
{ "file_path": "pennylane/doc/_static/qcircuit/Qcircuit.tex", "repo_id": "pennylane", "token_count": 3005 }
38
<?xml version="1.0" encoding="UTF-8" standalone="no"?> <!-- Created with Inkscape (http://www.inkscape.org/) --> <svg width="232.71077mm" height="116.79622mm" viewBox="0 0 232.71076 116.79622" version="1.1" id="svg5" inkscape:version="1.2.2 (b0a84865, 2022-12-01)" sodipodi:docname="transforms_order.svg" inkscape:export-filename="transforms_order.png" inkscape:export-xdpi="96" inkscape:export-ydpi="96" xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" xmlns="http://www.w3.org/2000/svg" xmlns:svg="http://www.w3.org/2000/svg"> <sodipodi:namedview id="namedview7" pagecolor="#ffffff" bordercolor="#000000" borderopacity="0.25" inkscape:showpageshadow="2" inkscape:pageopacity="0.0" inkscape:pagecheckerboard="0" inkscape:deskcolor="#d1d1d1" inkscape:document-units="mm" showgrid="false" inkscape:zoom="1" inkscape:cx="324.5" inkscape:cy="233.5" inkscape:window-width="1790" inkscape:window-height="847" inkscape:window-x="1471" inkscape:window-y="26" inkscape:window-maximized="0" inkscape:current-layer="layer1" /> <defs id="defs2"> <marker style="overflow:visible" id="marker24587" refX="0" refY="0" orient="auto-start-reverse" inkscape:stockid="TriangleStart" markerWidth="5.3244081" markerHeight="6.155385" viewBox="0 0 5.3244081 6.1553851" inkscape:isstock="true" inkscape:collect="always" preserveAspectRatio="xMidYMid"> <path transform="scale(0.5)" style="fill:context-stroke;fill-rule:evenodd;stroke:context-stroke;stroke-width:1pt" d="M 5.77,0 -2.88,5 V -5 Z" id="path24585" /> </marker> <marker style="overflow:visible" id="TriangleStart" refX="0" refY="0" orient="auto-start-reverse" inkscape:stockid="TriangleStart" markerWidth="5.3244081" markerHeight="6.155385" viewBox="0 0 5.3244081 6.1553851" inkscape:isstock="true" inkscape:collect="always" preserveAspectRatio="xMidYMid"> <path transform="scale(0.5)" style="fill:context-stroke;fill-rule:evenodd;stroke:context-stroke;stroke-width:1pt" d="M 5.77,0 -2.88,5 V -5 Z" id="path135" /> </marker> </defs> <g inkscape:label="Layer 1" inkscape:groupmode="layer" id="layer1" transform="translate(3.3370349,-77.64167)"> <rect style="fill:#e2edb1;fill-opacity:1;stroke:none;stroke-width:0.239088;stroke-dasharray:none;stroke-opacity:1" id="rect14580" width="232.71077" height="56.729591" x="-3.3370345" y="137.7083" /> <rect style="fill:#fff7e5;fill-opacity:1;stroke:none;stroke-width:0.223391;stroke-dasharray:none;stroke-opacity:1" id="rect11564" width="232.03218" height="60.511562" x="-3.3370349" y="77.64167" ry="0" /> <path style="fill:#d0eefe;fill-opacity:1;stroke:#024061;stroke-width:1.09817;stroke-dasharray:none;stroke-opacity:1" d="M -3.3035019,137.19854 228.91007,138.31863" id="path10828" sodipodi:nodetypes="cc" /> <text xml:space="preserve" style="font-size:7.05556px;fill:#000000;fill-opacity:1;stroke:none;stroke-width:0.2;stroke-dasharray:none;stroke-opacity:1" x="103.14642" y="91.21228" id="text10884"><tspan sodipodi:role="line" id="tspan10882" style="fill:#000000;fill-opacity:1;stroke:none;stroke-width:0.2;stroke-dasharray:none" x="103.14642" y="91.21228">tapes</tspan></text> <text xml:space="preserve" style="font-size:7.05556px;fill:#000000;fill-opacity:1;stroke:none;stroke-width:0.2;stroke-dasharray:none;stroke-opacity:1" x="100.08373" y="185.7616" id="text11460"><tspan sodipodi:role="line" id="tspan11458" style="stroke-width:0.2" x="100.08373" y="185.7616">results</tspan></text> <rect style="fill:#d0eefe;fill-opacity:1;stroke:#024061;stroke-width:0.90638;stroke-dasharray:none;stroke-opacity:1" id="rect234" width="21.941887" height="74.029007" x="16.198851" y="99.025276" ry="5.3460126" /> <text xml:space="preserve" style="font-size:7.05556px;writing-mode:lr-tb;direction:ltr;white-space:pre;inline-size:48.0044;display:inline;fill:#000000;fill-opacity:1;stroke:none;stroke-width:0.2;stroke-dasharray:none;stroke-opacity:1" x="30.033312" y="119.91077" id="text16770" transform="rotate(-90.466046,48.329231,138.45956)"><tspan x="30.033312" y="119.91077" id="tspan501">transform 1</tspan></text> <rect style="fill:#d0eefe;fill-opacity:1;stroke:#024061;stroke-width:0.90638;stroke-dasharray:none;stroke-opacity:1" id="rect16993" width="21.941887" height="74.029007" x="47.845062" y="99.025276" ry="5.3460126" /> <text xml:space="preserve" style="font-size:7.05556px;writing-mode:lr-tb;direction:ltr;fill:#000000;fill-opacity:1;stroke:none;stroke-width:0.2;stroke-dasharray:none;stroke-opacity:1" x="-156.4115" y="62.916519" id="text16982" transform="rotate(-89.362676)"><tspan sodipodi:role="line" id="tspan16980" style="stroke-width:0.2" x="-156.4115" y="62.916519">transform 2</tspan></text> <rect style="fill:#ffdcf9;fill-opacity:1;stroke:#6c0059;stroke-width:0.90638;stroke-dasharray:none;stroke-opacity:1" id="rect16995" width="21.941887" height="74.029007" x="79.491272" y="99.025276" ry="5.3460126" /> <text xml:space="preserve" style="font-size:7.05556px;writing-mode:lr-tb;direction:ltr;fill:#000000;fill-opacity:1;stroke:none;stroke-width:0.2;stroke-dasharray:none;stroke-opacity:1" x="-151.41635" y="91.295265" id="text18247" transform="rotate(-90.392907)"><tspan sodipodi:role="line" id="tspan18245" style="fill:#000000;fill-opacity:1;stroke-width:0.2" x="-151.41635" y="91.295265">gradient</tspan></text> <rect style="fill:#eacffa;fill-opacity:1;stroke:#600e90;stroke-width:0.90638;stroke-dasharray:none;stroke-opacity:1" id="rect19476" width="21.941887" height="74.029007" x="111.13748" y="99.025276" ry="5.3460126" /> <text xml:space="preserve" style="font-size:7.05556px;writing-mode:lr-tb;direction:ltr;fill:#000000;fill-opacity:1;stroke:none;stroke-width:0.2;stroke-dasharray:none;stroke-opacity:1" x="-149.25452" y="122.42915" id="text20308" transform="rotate(-90.903545)"><tspan sodipodi:role="line" id="tspan20306" style="fill:#000000;fill-opacity:1;stroke:none;stroke-width:0.2;stroke-opacity:1" x="-149.25452" y="122.42915">device</tspan></text> <rect style="fill:#ffffff;fill-opacity:1;stroke:#000000;stroke-width:0.90638;stroke-dasharray:none;stroke-opacity:1" id="rect20622" width="21.941887" height="74.029007" x="142.78369" y="99.025276" ry="5.3460126" /> <text xml:space="preserve" style="font-size:7.05556px;writing-mode:lr-tb;direction:ltr;fill:#000000;fill-opacity:1;stroke:none;stroke-width:0.2;stroke-dasharray:none;stroke-opacity:1" x="-142.96228" y="157.56412" id="text20728" transform="rotate(-89.474585)"><tspan sodipodi:role="line" id="tspan20726" style="fill:#000000;fill-opacity:1;stroke:none;stroke-width:0.2" x="-142.96228" y="157.56412">final</tspan></text> <rect style="fill:#d0eefe;fill-opacity:1;stroke:#024061;stroke-width:2;stroke-dasharray:none;stroke-opacity:1;paint-order:stroke markers fill" id="rect20834" width="34.614815" height="73.798737" x="178.04892" y="99.140411" ry="5.3293834" /> <text xml:space="preserve" style="font-size:7.05556px;writing-mode:lr-tb;direction:ltr;fill:#000000;fill-opacity:1;stroke:none;stroke-width:0.2;stroke-dasharray:none;stroke-opacity:1" x="-166.29468" y="200.38033" id="text20838" transform="rotate(-91.740943)"><tspan sodipodi:role="line" id="tspan20836" style="stroke-width:0.2" x="-166.29468" y="200.38033">ML boundary</tspan></text> <path style="fill:none;fill-opacity:1;stroke:#000000;stroke-width:1.2;stroke-dasharray:none;stroke-opacity:1;marker-mid:url(#TriangleStart);marker-end:url(#marker24587)" d="m 8.4538214,110.81412 0.2236689,0.008 90.0998867,0.24019 71.633863,0.19679 c 13.99885,0.0385 23.6858,12.70205 24.02664,26.25135 0.25167,10.00437 -2.0064,22.31423 -21.57949,22.46936 l -70.07685,0.55543 -98.3321602,0.77937" id="path20894" sodipodi:nodetypes="cccssscc" /> </g> </svg>
pennylane/doc/_static/transforms_order.svg/0
{ "file_path": "pennylane/doc/_static/transforms_order.svg", "repo_id": "pennylane", "token_count": 4780 }
39
qml.data ========= .. currentmodule:: pennylane.data .. automodule:: pennylane.data
pennylane/doc/code/qml_data.rst/0
{ "file_path": "pennylane/doc/code/qml_data.rst", "repo_id": "pennylane", "token_count": 31 }
40
qml.pulse ========= .. automodule:: pennylane.pulse
pennylane/doc/code/qml_pulse.rst/0
{ "file_path": "pennylane/doc/code/qml_pulse.rst", "repo_id": "pennylane", "token_count": 22 }
41
.. _contributing_operators: Adding new operators ==================== The following steps will help you to create custom operators, and to potentially add them to PennyLane. Note that in PennyLane, a circuit ansatz consisting of multiple gates is also an operator --- one whose action is defined by specifying a representation as a combination of other operators. For historical reasons, you find circuit ansaetze in the ``pennylane/template/`` folder, while all other operations are found in ``pennylane/ops/``. The base classes to construct new operators, :class:`~.Operator` and corresponding subclasses, are found in ``pennylane/operations.py``. .. note:: Check :doc:`/code/qml_measurements` for documentation on how to create new measurements. Abstraction ########### Operators in quantum mechanics are maps that act on vector spaces, and in differentiable quantum computing, these maps can depend on a set of trainable parameters. The :class:`~.Operator` class serves as the main abstraction of such objects, and all operators (such as gates, channels, observables) inherit from it. >>> from jax import numpy as jnp >>> op = qml.Rot(jnp.array(0.1), jnp.array(0.2), jnp.array(0.3), wires=["a"]) >>> isinstance(op, qml.operation.Operator) True The basic components of operators are the following: #. **The name of the operator** (:attr:`.Operator.name`), which may have a canonical, universally known interpretation (such as a "Hadamard" gate), or could be a name specific to PennyLane. >>> op.name Rot #. **The subsystems that the operator addresses** (:attr:`.Operator.wires`), which mathematically speaking defines the subspace that it acts on. >>> op.wires Wires(['a']) #. **Trainable parameters** (:attr:`.Operator.parameters`) that the map depends on, such as a rotation angle, which can be fed to the operator as tensor-like objects. For example, since we used jax arrays to specify the three rotation angles of ``op``, the parameters are jax ``Arrays``. >>> op.parameters [Array(0.1, dtype=float32, weak_type=True), Array(0.2, dtype=float32, weak_type=True), Array(0.3, dtype=float32, weak_type=True)] #. **Non-trainable hyperparameters** (:attr:`.Operator.hyperparameters`) that influence the action of the operator. Not every operator has hyperparameters. >>> op.hyperparameters {} #. Possible **symbolic or numerical representations** of the operator, which can be used by PennyLane's devices to interpret the map. Examples are: * Representation as a **product of operators** (:meth:`.Operator.decomposition`): >>> op = qml.Rot(0.1, 0.2, 0.3, wires=["a"]) >>> op.decomposition() [RZ(0.1, wires=['a']), RY(0.2, wires=['a']), RZ(0.3, wires=['a'])] * Representation as a **linear combination of operators** (:meth:`.Operator.terms`): >>> op = qml.Hamiltonian([1., 2.], [qml.PauliX(0), qml.PauliZ(0)]) >>> op.terms() ((1.0, 2.0), [PauliX(wires=[0]), PauliZ(wires=[0])]) * Representation via the **eigenvalue decomposition** specified by eigenvalues (for the diagonal matrix, :meth:`.Operator.eigvals`) and diagonalizing gates (for the unitaries :meth:`.Operator.diagonalizing_gates`): >>> op = qml.PauliX(0) >>> op.diagonalizing_gates() [Hadamard(wires=[0])] >>> op.eigvals() [ 1 -1] * Representation as a **matrix** (:meth:`.Operator.matrix`), as specified by a global wire order that tells us where the wires are found on a register: >>> op = qml.PauliRot(0.2, "X", wires=["b"]) >>> op.matrix(wire_order=["a", "b"]) [[9.95e-01-2.26e-18j 2.72e-17-9.98e-02j, 0+0j, 0+0j] [2.72e-17-9.98e-02j 9.95e-01-2.26e-18j, 0+0j, 0+0j] [0+0j, 0+0j, 9.95e-01-2.26e-18j 2.72e-17-9.98e-02j] [0+0j, 0+0j, 2.72e-17-9.98e-02j 9.95e-01-2.26e-18j]] * Representation as a **sparse matrix** (:meth:`.Operator.sparse_matrix`): >>> from scipy.sparse.coo import coo_matrix >>> row = np.array([0, 1]) >>> col = np.array([1, 0]) >>> data = np.array([1, -1]) >>> mat = coo_matrix((data, (row, col)), shape=(4, 4)) >>> op = qml.SparseHamiltonian(mat, wires=["a"]) >>> op.sparse_matrix(wire_order=["a"]) (0, 1) 1 (1, 0) - 1 New operators can be created by applying arithmetic functions to operators, such as addition, scalar multiplication, multiplication, taking the adjoint, or controlling an operator. At the moment, such arithmetic is only implemented for specific subclasses. * Operators inheriting from :class:`~.Observable` support addition and scalar multiplication: >>> op = qml.PauliX(0) + 0.1 * qml.PauliZ(0) >>> op.name Hamiltonian >>> op (0.1) [Z0] + (1.0) [X0] * Operators may define a hermitian conjugate: >>> qml.RX(1., wires=0).adjoint() RX(-1.0, wires=[0]) Creating custom operators ######################### A custom operator can be created by inheriting from :class:`~.Operator` or one of its subclasses. The following is an example for a custom gate that possibly flips a qubit and then rotates another qubit. The custom operator defines a decomposition, which the devices can use (since it is unlikely that a device knows a native implementation for ``FlipAndRotate``). It also defines an adjoint operator. .. code-block:: python import pennylane as qml class FlipAndRotate(qml.operation.Operation): # Define how many wires the operator acts on in total. # In our case this may be one or two, which is why we # use the AnyWires Enumeration to indicate a variable number. num_wires = qml.operation.AnyWires # This attribute tells PennyLane what differentiation method to use. Here # we request parameter-shift (or "analytic") differentiation. grad_method = "A" def __init__(self, angle, wire_rot, wire_flip=None, do_flip=False, id=None): # checking the inputs -------------- if do_flip and wire_flip is None: raise ValueError("Expected a wire to flip; got None.") # note: we use the framework-agnostic math library since # trainable inputs could be tensors of different types shape = qml.math.shape(angle) if len(shape) > 1: raise ValueError(f"Expected a scalar angle; got angle of shape {shape}.") #------------------------------------ # do_flip is not trainable but influences the action of the operator, # which is why we define it to be a hyperparameter self._hyperparameters = { "do_flip": do_flip } # we extract all wires that the operator acts on, # relying on the Wire class arithmetic all_wires = qml.wires.Wires(wire_rot) + qml.wires.Wires(wire_flip) # The parent class expects all trainable parameters to be fed as positional # arguments, and all wires acted on fed as a keyword argument. # The id keyword argument allows users to give their instance a custom name. super().__init__(angle, wires=all_wires, id=id) @property def num_params(self): # if it is known before creation, define the number of parameters to expect here, # which makes sure an error is raised if the wrong number was passed return 1 @staticmethod def compute_decomposition(angle, wires, do_flip): # pylint: disable=arguments-differ # Overwriting this method defines the decomposition of the new gate, as it is # called by Operator.decomposition(). # The general signature of this function is (*parameters, wires, **hyperparameters). op_list = [] if do_flip: op_list.append(qml.PauliX(wires=wires[1])) op_list.append(qml.RX(angle, wires=wires[0])) return op_list def adjoint(self): # the adjoint operator of this gate simply negates the angle return FlipAndRotate(-self.parameters[0], self.wires[0], self.wires[1], do_flip=self.hyperparameters["do_flip"]) @classmethod def _unflatten(cls, data, metadata): # as the class differs from the standard `__init__` call signature of # (*data, wires=wires, **hyperparameters), the _unflatten method that # must be defined as well # _unflatten recreates a opeartion from the serialized data and metadata of ``Operator._flatten`` # copied_op = type(op)._unflatten(*op._flatten()) wires = metadata[0] hyperparams = dict(metadata[1]) return cls(data[0], wire_rot=wires[0], wire_flip=wires[1], do_flip=hyperparams['do_flip']) The new gate can now be created as follows: >>> op = FlipAndRotate(0.1, wire_rot="q3", wire_flip="q1", do_flip=True) >>> op FlipAndRotate(0.1, wires=['q3', 'q1']) >>> op.decomposition() [PauliX(wires=['q1']), RX(0.1, wires=['q3'])] >>> op.adjoint() FlipAndRotate(-0.1, wires=['q3', 'q1']) Once the class has been created, you can run a suite of validation checks using :func:`.ops.functions.assert_valid`. This function will warn you of some common errors in custom operators. >>> qml.ops.functions.assert_valid(op) If the above operator omitted the ``_unflatten`` custom definition, it would raise: .. code-block:: TypeError: FlipAndRotate.__init__() got an unexpected keyword argument 'wires' The above exception was the direct cause of the following exception: AssertionError: FlipAndRotate._unflatten must be able to reproduce the original operation from (0.1,) and (Wires(['q3', 'q1']), (('do_flip', True),)). You may need to override either the _unflatten or _flatten method. For local testing, try type(op)._unflatten(*op._flatten()) The new gate can be used with PennyLane devices. Device support for an operation can be checked via ``dev.stopping_condition(op)``. If ``True``, then the device supports the operation. ``DefaultQubitLegacy`` first checks if the operator has a matrix using the :attr:`~.Operator.has_matrix` property. If the Operator doesn't have a matrix, the device then checks if the name of the Operator is explicitly specified in :attr:`~DefaultQubitLegacy.operations` or :attr:`~DefaultQubitLegacy.observables`. Other devices that do not inherit from ``DefaultQubitLegacy`` only check if the name is explicitly specified in the ``operations`` property. - If the device registers support for an operation with the same name, PennyLane leaves the gate implementation up to the device. The device might have a hardcoded implementation, *or* it may refer to one of the numerical representations of the operator (such as :meth:`.Operator.matrix`). - If the device does not support an operation, PennyLane will automatically decompose the gate using :meth:`.Operator.decomposition`. .. code-block:: python from pennylane import numpy as np dev = qml.device("default.qubit", wires=["q1", "q2", "q3"]) @qml.qnode(dev) def circuit(angle): FlipAndRotate(angle, wire_rot="q1", wire_flip="q1") return qml.expval(qml.PauliZ("q1")) >>> a = np.array(3.14) >>> circuit(a) -0.9999987318946099 If all gates used in the decomposition have gradient recipes defined, we can even compute gradients of circuits that use the new gate without any extra effort. >>> qml.grad(circuit)(a) -0.0015926529164868282 .. note:: The example of ``FlipAndRotate`` is simple enough that one could write a function .. code-block:: python def FlipAndRotate(angle, wire_rot, wire_flip=None, do_flip=False): if do_flip: qml.PauliX(wires=wire_flip) qml.RX(angle, wires=wire_rot) and call it in the quantum function *as if it was a gate*. However, classes allow much more functionality, such as defining the adjoint gate above, defining the shape expected for the trainable parameter(s), or specifying gradient rules. Defining special properties of an operator ########################################## Apart from the main :class:`~.Operator` class, operators with special methods or representations are implemented as subclasses :class:`~.Operation`, :class:`~.Observable`, :class:`~.Channel`, :class:`~.CVOperation` and :class:`~.CVObservable`. However, unlike many other frameworks, PennyLane does not use class inheritance to define fine-grained properties of operators, such as whether it is its own self-inverse, if it is diagonal, or whether it can be decomposed into Pauli rotations. This avoids changing the inheritance structure every time an application needs to query a new property. Instead, PennyLane uses "attributes", which are bookkeeping classes that list operators which fulfill a specific property. For example, we can create a new attribute, ``pauli_ops``, like so: >>> from pennylane.ops.qubits.attributes import Attribute >>> pauli_ops = Attribute(["PauliX", "PauliY", "PauliZ"]) We can check either a string or an Operation for inclusion in this set: >>> qml.PauliX(0) in pauli_ops True >>> "Hadamard" in pauli_ops False We can also dynamically add operators to the sets at runtime. This is useful for adding custom operations to the attributes such as ``composable_rotations`` and ``self_inverses`` that are used in compilation transforms. For example, suppose you have created a new operation ``MyGate``, which you know to be its own inverse. Adding it to the set, like so >>> from pennylane.ops.qubits.attributes import self_inverses >>> self_inverses.add("MyGate") Attributes can also be queried by devices to use special tricks that allow more efficient implementations. The onus is on the contributors of new operators to add them to the right attributes. .. note:: The attributes for qubit gates are currently found in ``pennylane/ops/qubit/attributes.py``. Included attributes are listed in the ``Operation`` `documentation <https://pennylane.readthedocs.io/en/latest/code/qml_operation.html#operation-attributes>`__. Adding your new operator to PennyLane ##################################### If you want PennyLane to natively support your new operator, you have to make a Pull Request that adds it to the appropriate folder in ``pennylane/ops/``. The tests are added to a file of a similar name and location in ``tests/ops/``. If your operator defines an ansatz, add it to the appropriate subfolder in ``pennylane/templates/``. The new operation may have to be imported in the module's ``__init__.py`` file in order to be imported correctly. Make sure that all hyperparameters and errors are tested, and that the parameters can be passed as tensors from all supported autodifferentiation frameworks. Don't forget to also add the new operator to the documentation in the ``docs/introduction/operations.rst`` file, or to the template gallery if it is an ansatz. The latter is done by adding a ``gallery-item`` to the correct section in ``doc/introduction/templates.rst``: .. code-block:: .. gallery-item:: :link: ../code/api/pennylane.templates.<templ_type>.MyNewTemplate.html :description: MyNewTemplate :figure: ../_static/templates/<templ_type>/my_new_template.png .. note:: This loads the image of the template added to ``doc/_static/templates/test_<templ_type>/``. Make sure that this image has the same dimensions and style as other template icons in the folder. Here are a few more tips for adding operators: * *Choose the name carefully.* Good names tell the user what the operator is used for, or what architecture it implements. Ask yourself if a gate of a similar name could be added soon in a different context. * *Write good docstrings.* Explain what your operator does in a clear docstring with ample examples. You find more about Pennylane standards in the guidelines on :doc:`/development/guide/documentation`. * *Efficient representations.* Try to implement representations as efficiently as possible, since they may be constructed several times. * *Input checks.* Checking the inputs of the operation introduces an overhead and clashes with tools like just-in-time compilation. Find a balance of adding meaningful sanity checks (such as for the shape of tensors), but keeping them to a minimum.
pennylane/doc/development/adding_operators.rst/0
{ "file_path": "pennylane/doc/development/adding_operators.rst", "repo_id": "pennylane", "token_count": 5586 }
42
.. role:: html(raw) :format: html .. _intro_inspecting_circuits: Inspecting circuits =================== PennyLane offers functionality to inspect, visualize or analyze quantum circuits. .. _intro_qtransforms: Most of these tools are implemented as **transforms**. Transforms take a :class:`~pennylane.QNode` instance and return a function: >>> @qml.qnode(dev, diff_method='parameter-shift') ... def my_qnode(x, a=True): ... # ... >>> new_func = my_transform(qnode) This new function accepts the same arguments as the QNode and returns the desired outcome, such as a dictionary of the QNode's properties, a matplotlib figure drawing the circuit, or a DAG representing its connectivity structure. >>> new_func(0.1, a=False) More information on the concept of transforms can be found in `Di Matteo et al. (2022) <https://arxiv.org/abs/2202.13414>`_. Extracting properties of a circuit ---------------------------------- The :func:`~pennylane.specs` transform takes a QNode and creates a function that returns details about the QNode, including depth, number of gates, and number of gradient executions required. For example: .. code-block:: python dev = qml.device('default.qubit', wires=4) @qml.qnode(dev, diff_method='parameter-shift') def circuit(x, y): qml.RX(x[0], wires=0) qml.Toffoli(wires=(0, 1, 2)) qml.CRY(x[1], wires=(0, 1)) qml.Rot(x[2], x[3], y, wires=0) return qml.expval(qml.Z(0)), qml.expval(qml.X(1)) We can now use the :func:`~pennylane.specs` transform to generate a function that returns details and resource information: >>> x = np.array([0.05, 0.1, 0.2, 0.3], requires_grad=True) >>> y = np.array(0.4, requires_grad=False) >>> specs_func = qml.specs(circuit) >>> specs_func(x, y) {'resources': Resources(num_wires=3, num_gates=4, gate_types=defaultdict(<class 'int'>, {'RX': 1, 'Toffoli': 1, 'CRY': 1, 'Rot': 1}), depth=4, shots=0), 'gate_sizes': defaultdict(int, {1: 2, 3: 1, 2: 1}), 'gate_types': defaultdict(int, {'RX': 1, 'Toffoli': 1, 'CRY': 1, 'Rot': 1}), 'num_operations': 4, 'num_observables': 2, 'num_diagonalizing_gates': 1, 'num_used_wires': 3, 'num_trainable_params': 4, 'depth': 4, 'num_device_wires': 4, 'device_name': 'default.qubit', 'expansion_strategy': 'gradient', 'gradient_options': {}, 'interface': 'auto', 'diff_method': 'parameter-shift', 'gradient_fn': 'pennylane.gradients.parameter_shift.param_shift', 'num_gradient_executions': 10} Circuit drawing --------------- PennyLane has two built-in circuit drawers, :func:`~pennylane.draw` and :func:`~pennylane.draw_mpl`. For example: .. code-block:: python dev = qml.device('default.qubit') @qml.qnode(dev) def circuit(x, z): qml.QFT(wires=(0,1,2,3)) qml.IsingXX(1.234, wires=(0,2)) qml.Toffoli(wires=(0,1,2)) mcm = qml.measure(1) mcm_out = qml.measure(2) qml.CSWAP(wires=(0,2,3)) qml.RX(x, wires=0) qml.cond(mcm, qml.RY)(np.pi / 4, wires=3) qml.CRZ(z, wires=(3,0)) return qml.expval(qml.Z(0)), qml.probs(op=mcm_out) fig, ax = qml.draw_mpl(circuit)(1.2345,1.2345) fig.show() .. image:: ../_static/draw_mpl/main_example.png :align: center :width: 400px :target: javascript:void(0); >>> print(qml.draw(circuit)(1.2345,1.2345)) 0: ─╭QFT─╭IsingXX(1.23)─╭●───────────╭●─────RX(1.23)─╭RZ(1.23)─┤ <Z> 1: ─├QFT─│──────────────├●──┤↗├──────│───────────────│─────────┤ 2: ─├QFT─╰IsingXX(1.23)─╰X───║───┤↗├─├SWAP───────────│─────────┤ 3: ─╰QFT─────────────────────║────║──╰SWAP──RY(0.79)─╰●────────┤ ╚════║═════════╝ ╚════════════════════════════╡ Probs[MCM] More information, including various fine-tuning options, can be found in the :doc:`drawing module <../code/qml_drawer>`. Debugging with mid-circuit snapshots ------------------------------------ When debugging quantum circuits run on simulators, we may want to inspect the current quantum state between gates. :class:`~pennylane.Snapshot` is an operator like a gate, but it saves the device state at its location in the circuit instead of manipulating the quantum state. Currently supported devices include: * ``default.qubit``: each snapshot saves the quantum state vector * ``default.mixed``: each snapshot saves the density matrix * ``default.gaussian``: each snapshot saves the covariance matrix and vector of means A :class:`~pennylane.Snapshot` can be used in a QNode like any other operation: .. code-block:: python dev = qml.device("default.qubit", wires=2) @qml.qnode(dev, interface=None) def circuit(): qml.Snapshot(measurement=qml.expval(qml.Z(0))) qml.Hadamard(wires=0) qml.Snapshot("very_important_state") qml.CNOT(wires=[0, 1]) qml.Snapshot() return qml.expval(qml.X(0)) During normal execution, the snapshots are ignored: >>> circuit() 0.0 However, when using the :func:`~pennylane.snapshots` transform, intermediate device states will be stored and returned alongside the results. >>> qml.snapshots(circuit)() {0: 1.0, 'very_important_state': array([0.707+0.j, 0.+0.j, 0.707+0.j, 0.+0.j]), 2: array([0.707+0.j, 0.+0.j, 0.+0.j, 0.707+0.j]), 'execution_results': 0.0} All snapshots are numbered with consecutive integers, and if no tag was provided, the number of a snapshot is used as a key in the output dictionary instead. Interactive Debugging on Simulators ----------------------------------- PennyLane allows for more interactive debugging of quantum circuits in a programmatic fashion using quantum breakpoints via :func:`~pennylane.breakpoint`. This feature is currently supported on ``default.qubit`` and ``lightning.qubit`` devices. Consider the following python script containing the quantum circuit with breakpoints. .. code-block:: python3 dev = qml.device("default.qubit", wires=2) @qml.qnode(dev) def circuit(x): qml.breakpoint() qml.RX(x, wires=0) qml.Hadamard(wires=1) qml.breakpoint() qml.CNOT(wires=[0, 1]) return qml.expval(qml.Z(0)) circuit(1.23) Running the circuit above launches an interactive :code:`[pldb]` prompt. Here we can step through the circuit execution: .. code-block:: console > /Users/your/path/to/script.py(8)circuit() -> qml.RX(x, wires=0) [pldb] list 3 4 @qml.qnode(dev) 5 def circuit(x): 6 qml.breakpoint() 7 8 -> qml.RX(x, wires=0) 9 qml.Hadamard(wires=1) 10 11 qml.breakpoint() 12 13 qml.CNOT(wires=[0, 1]) [pldb] next > /Users/your/path/to/script.py(9)circuit() -> qml.Hadamard(wires=1) We can extract information by making measurements which do not change the state of the circuit in execution: .. code-block:: console [pldb] qml.debug_state() array([0.81677345+0.j , 0. +0.j , 0. -0.57695852j, 0. +0.j ]) [pldb] continue > /Users/your/path/to/script.py(13)circuit() -> qml.CNOT(wires=[0, 1]) [pldb] next > /Users/your/path/to/script.py(14)circuit() -> return qml.expval(qml.Z(0)) [pldb] list 8 qml.RX(x, wires=0) 9 qml.Hadamard(wires=1) 10 11 qml.breakpoint() 12 13 qml.CNOT(wires=[0, 1]) 14 -> return qml.expval(qml.Z(0)) 15 16 circuit(1.23) [EOF] We can also visualize the circuit and dynamically queue operations directly to the circuit: .. code-block:: console [pldb] print(qml.debug_tape().draw()) 0: ──RX─╭●─┤ 1: ──H──╰X─┤ [pldb] qml.RZ(-4.56, 1) RZ(-4.56, wires=[1]) [pldb] print(qml.debug_tape().draw()) 0: ──RX─╭●─────┤ 1: ──H──╰X──RZ─┤ See :doc:`/code/qml_debugging` for more information and detailed examples. Graph representation -------------------- PennyLane makes use of several ways to represent a quantum circuit as a Directed Acyclic Graph (DAG). DAG of causal relations between ops ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ A DAG can be used to represent which operator in a circuit is causally related to another. There are two options to construct such a DAG: The :class:`~pennylane.CircuitGraph` class takes a list of gates or channels and hermitian observables as well as a set of wire labels and constructs a DAG in which the :class:`~.Operator` instances are the nodes, and each directed edge corresponds to a wire (or a group of wires) on which the "nodes" act subsequently. For example, this can be used to compute the effective depth of a circuit, or to check whether two gates causally influence each other. .. code-block:: python import pennylane as qml from pennylane import CircuitGraph dev = qml.device('lightning.qubit', wires=(0,1,2,3)) @qml.qnode(dev) def circuit(): qml.Hadamard(0) qml.CNOT([1, 2]) qml.CNOT([2, 3]) qml.CNOT([3, 1]) return qml.expval(qml.Z(0)) circuit() tape = circuit.qtape ops = tape.operations obs = tape.observables g = CircuitGraph(ops, obs, tape.wires) Internally, the :class:`~pennylane.CircuitGraph` class constructs a ``rustworkx`` graph object. >>> type(g.graph) rustworkx.PyDiGraph There is no edge between the ``Hadamard`` and the first ``CNOT``, but between consecutive ``CNOT`` gates: >>> g.has_path(ops[0], ops[1]) False >>> g.has_path(ops[1], ops[3]) True The Hadamard is connected to the observable, while the ``CNOT`` operators are not. The observable does not follow the Hadamard. >>> g.has_path(ops[0], obs[0]) True >>> g.has_path(ops[1], obs[0]) False >>> g.has_path(obs[0], ops[0]) False Another way to construct the "causal" DAG of a circuit is to use the :func:`~pennylane.qcut.tape_to_graph` function used by the ``qcut`` module. This function takes a quantum tape and creates a ``MultiDiGraph`` instance from the ``networkx`` python package. Using the above example, we get: >>> g2 = qml.qcut.tape_to_graph(tape) >>> type(g2) <class 'networkx.classes.multidigraph.MultiDiGraph'> >>> for k, v in g2.adjacency(): ... print(k, v) Hadamard(wires=[0]) {expval(Z(0)): {0: {'wire': 0}}} CNOT(wires=[1, 2]) {CNOT(wires=[2, 3]): {0: {'wire': 2}}, CNOT(wires=[3, 1]): {0: {'wire': 1}}} CNOT(wires=[2, 3]) {CNOT(wires=[3, 1]): {0: {'wire': 3}}} CNOT(wires=[3, 1]) {} expval(Z(0)) {} DAG of non-commuting ops ~~~~~~~~~~~~~~~~~~~~~~~~ The :func:`~pennylane.commutation_dag` transform can be used to produce an instance of the ``CommutationDAG`` class. In a commutation DAG, each node represents a quantum operation, and edges represent non-commutation between two operations. This transform takes into account that not all operations can be moved next to each other by pairwise commutation: >>> def circuit(x, y, z): ... qml.RX(x, wires=0) ... qml.RX(y, wires=0) ... qml.CNOT(wires=[1, 2]) ... qml.RY(y, wires=1) ... qml.Hadamard(wires=2) ... qml.CRZ(z, wires=[2, 0]) ... qml.RY(-y, wires=1) ... return qml.expval(qml.Z(0)) >>> dag_fn = qml.commutation_dag(circuit) >>> dag = dag_fn(np.pi / 4, np.pi / 3, np.pi / 2) Nodes in the commutation DAG can be accessed via the ``get_nodes()`` method, returning a list of the form ``(ID, CommutationDAGNode)``: >>> nodes = dag.get_nodes() >>> nodes NodeDataView({0: <pennylane.transforms.commutation_dag.CommutationDAGNode object at 0x7f461c4bb580>, ...}, data='node') Specific nodes in the commutation DAG can be accessed via the ``get_node()`` method: >>> second_node = dag.get_node(2) >>> second_node <pennylane.transforms.commutation_dag.CommutationDAGNode object at 0x136f8c4c0> >>> second_node.op CNOT(wires=[1, 2]) >>> second_node.successors [3, 4, 5, 6] >>> second_node.predecessors [] Fourier representation ---------------------- Parametrized quantum circuits often compute functions in the parameters that can be represented by Fourier series of a low degree. The :doc:`../code/qml_fourier` module contains functionality to compute and visualize properties of such Fourier series. .. image:: ../_static/fourier_vis_radial_box.png :align: center :width: 500px :target: javascript:void(0);
pennylane/doc/introduction/inspecting_circuits.rst/0
{ "file_path": "pennylane/doc/introduction/inspecting_circuits.rst", "repo_id": "pennylane", "token_count": 5034 }
43
:orphan: # Release 0.12.0 <h3>New features since last release</h3> <h4>New and improved simulators</h4> * PennyLane now supports a new device, `default.mixed`, designed for simulating mixed-state quantum computations. This enables native support for implementing noisy channels in a circuit, which generally map pure states to mixed states. [(#794)](https://github.com/PennyLaneAI/pennylane/pull/794) [(#807)](https://github.com/PennyLaneAI/pennylane/pull/807) [(#819)](https://github.com/PennyLaneAI/pennylane/pull/819) The device can be initialized as ```pycon >>> dev = qml.device("default.mixed", wires=1) ``` This allows the construction of QNodes that include non-unitary operations, such as noisy channels: ```pycon >>> @qml.qnode(dev) ... def circuit(params): ... qml.RX(params[0], wires=0) ... qml.RY(params[1], wires=0) ... qml.AmplitudeDamping(0.5, wires=0) ... return qml.expval(qml.PauliZ(0)) >>> print(circuit([0.54, 0.12])) 0.9257702929524184 >>> print(circuit([0, np.pi])) 0.0 ``` <h4>New tools for optimizing measurements</h4> * The new `grouping` module provides functionality for grouping simultaneously measurable Pauli word observables. [(#761)](https://github.com/PennyLaneAI/pennylane/pull/761) [(#850)](https://github.com/PennyLaneAI/pennylane/pull/850) [(#852)](https://github.com/PennyLaneAI/pennylane/pull/852) - The `optimize_measurements` function will take as input a list of Pauli word observables and their corresponding coefficients (if any), and will return the partitioned Pauli terms diagonalized in the measurement basis and the corresponding diagonalizing circuits. ```python from pennylane.grouping import optimize_measurements h, nr_qubits = qml.qchem.molecular_hamiltonian("h2", "h2.xyz") rotations, grouped_ops, grouped_coeffs = optimize_measurements(h.ops, h.coeffs, grouping="qwc") ``` The diagonalizing circuits of `rotations` correspond to the diagonalized Pauli word groupings of `grouped_ops`. - Pauli word partitioning utilities are performed by the `PauliGroupingStrategy` class. An input list of Pauli words can be partitioned into mutually commuting, qubit-wise-commuting, or anticommuting groupings. For example, partitioning Pauli words into anticommutative groupings by the Recursive Largest First (RLF) graph colouring heuristic: ```python from pennylane import PauliX, PauliY, PauliZ, Identity from pennylane.grouping import group_observables pauli_words = [ Identity('a') @ Identity('b'), Identity('a') @ PauliX('b'), Identity('a') @ PauliY('b'), PauliZ('a') @ PauliX('b'), PauliZ('a') @ PauliY('b'), PauliZ('a') @ PauliZ('b') ] groupings = group_observables(pauli_words, grouping_type='anticommuting', method='rlf') ``` - Various utility functions are included for obtaining and manipulating Pauli words in the binary symplectic vector space representation. For instance, two Pauli words may be converted to their binary vector representation: ```pycon >>> from pennylane.grouping import pauli_to_binary >>> from pennylane.wires import Wires >>> wire_map = {Wires('a'): 0, Wires('b'): 1} >>> pauli_vec_1 = pauli_to_binary(qml.PauliX('a') @ qml.PauliY('b')) >>> pauli_vec_2 = pauli_to_binary(qml.PauliZ('a') @ qml.PauliZ('b')) >>> pauli_vec_1 [1. 1. 0. 1.] >>> pauli_vec_2 [0. 0. 1. 1.] ``` Their product up to a phase may be computed by taking the sum of their binary vector representations, and returned in the operator representation. ```pycon >>> from pennylane.grouping import binary_to_pauli >>> binary_to_pauli((pauli_vec_1 + pauli_vec_2) % 2, wire_map) Tensor product ['PauliY', 'PauliX']: 0 params, wires ['a', 'b'] ``` For more details on the grouping module, see the [grouping module documentation](https://pennylane.readthedocs.io/en/stable/code/qml_grouping.html) <h4>Returning the quantum state from simulators</h4> * The quantum state of a QNode can now be returned using the `qml.state()` return function. [(#818)](https://github.com/XanaduAI/pennylane/pull/818) ```python import pennylane as qml dev = qml.device("default.qubit", wires=3) qml.enable_tape() @qml.qnode(dev) def qfunc(x, y): qml.RZ(x, wires=0) qml.CNOT(wires=[0, 1]) qml.RY(y, wires=1) qml.CNOT(wires=[0, 2]) return qml.state() >>> qfunc(0.56, 0.1) array([0.95985437-0.27601028j, 0. +0.j , 0.04803275-0.01381203j, 0. +0.j , 0. +0.j , 0. +0.j , 0. +0.j , 0. +0.j ]) ``` Differentiating the state is currently available when using the classical backpropagation differentiation method (`diff_method="backprop"`) with a compatible device, and when using the new tape mode. <h4>New operations and channels</h4> * PennyLane now includes standard channels such as the Amplitude-damping, Phase-damping, and Depolarizing channels, as well as the ability to make custom qubit channels. [(#760)](https://github.com/PennyLaneAI/pennylane/pull/760) [(#766)](https://github.com/PennyLaneAI/pennylane/pull/766) [(#778)](https://github.com/PennyLaneAI/pennylane/pull/778) * The controlled-Y operation is now available via `qml.CY`. For devices that do not natively support the controlled-Y operation, it will be decomposed into `qml.RY`, `qml.CNOT`, and `qml.S` operations. [(#806)](https://github.com/PennyLaneAI/pennylane/pull/806) <h4>Preview the next-generation PennyLane QNode</h4> * The new PennyLane `tape` module provides a re-formulated QNode class, rewritten from the ground-up, that uses a new `QuantumTape` object to represent the QNode's quantum circuit. Tape mode provides several advantages over the standard PennyLane QNode. [(#785)](https://github.com/PennyLaneAI/pennylane/pull/785) [(#792)](https://github.com/PennyLaneAI/pennylane/pull/792) [(#796)](https://github.com/PennyLaneAI/pennylane/pull/796) [(#800)](https://github.com/PennyLaneAI/pennylane/pull/800) [(#803)](https://github.com/PennyLaneAI/pennylane/pull/803) [(#804)](https://github.com/PennyLaneAI/pennylane/pull/804) [(#805)](https://github.com/PennyLaneAI/pennylane/pull/805) [(#808)](https://github.com/PennyLaneAI/pennylane/pull/808) [(#810)](https://github.com/PennyLaneAI/pennylane/pull/810) [(#811)](https://github.com/PennyLaneAI/pennylane/pull/811) [(#815)](https://github.com/PennyLaneAI/pennylane/pull/815) [(#820)](https://github.com/PennyLaneAI/pennylane/pull/820) [(#823)](https://github.com/PennyLaneAI/pennylane/pull/823) [(#824)](https://github.com/PennyLaneAI/pennylane/pull/824) [(#829)](https://github.com/PennyLaneAI/pennylane/pull/829) - Support for in-QNode classical processing: Tape mode allows for differentiable classical processing within the QNode. - No more Variable wrapping: In tape mode, QNode arguments no longer become `Variable` objects within the QNode. - Less restrictive QNode signatures: There is no longer any restriction on the QNode signature; the QNode can be defined and called following the same rules as standard Python functions. - Unifying all QNodes: The tape-mode QNode merges all QNodes (including the `JacobianQNode` and the `PassthruQNode`) into a single unified QNode, with identical behaviour regardless of the differentiation type. - Optimizations: Tape mode provides various performance optimizations, reducing pre- and post-processing overhead, and reduces the number of quantum evaluations in certain cases. Note that tape mode is **experimental**, and does not currently have feature-parity with the existing QNode. [Feedback and bug reports](https://github.com/PennyLaneAI/pennylane/issues) are encouraged and will help improve the new tape mode. Tape mode can be enabled globally via the `qml.enable_tape` function, without changing your PennyLane code: ```python qml.enable_tape() dev = qml.device("default.qubit", wires=1) @qml.qnode(dev, interface="tf") def circuit(p): print("Parameter value:", p) qml.RX(tf.sin(p[0])**2 + p[1], wires=0) return qml.expval(qml.PauliZ(0)) ``` For more details, please see the [tape mode documentation](https://pennylane.readthedocs.io/en/stable/code/qml_tape.html). <h3>Improvements</h3> * QNode caching has been introduced, allowing the QNode to keep track of the results of previous device executions and reuse those results in subsequent calls. Note that QNode caching is only supported in the new and experimental tape-mode. [(#817)](https://github.com/PennyLaneAI/pennylane/pull/817) Caching is available by passing a `caching` argument to the QNode: ```python dev = qml.device("default.qubit", wires=2) qml.enable_tape() @qml.qnode(dev, caching=10) # cache up to 10 evaluations def qfunc(x): qml.RX(x, wires=0) qml.RX(0.3, wires=1) qml.CNOT(wires=[0, 1]) return qml.expval(qml.PauliZ(1)) qfunc(0.1) # first evaluation executes on the device qfunc(0.1) # second evaluation accesses the cached result ``` * Sped up the application of certain gates in `default.qubit` by using array/tensor manipulation tricks. The following gates are affected: `PauliX`, `PauliY`, `PauliZ`, `Hadamard`, `SWAP`, `S`, `T`, `CNOT`, `CZ`. [(#772)](https://github.com/PennyLaneAI/pennylane/pull/772) * The computation of marginal probabilities has been made more efficient for devices with a large number of wires, achieving in some cases a 5x speedup. [(#799)](https://github.com/PennyLaneAI/pennylane/pull/799) * Adds arithmetic operations (addition, tensor product, subtraction, and scalar multiplication) between `Hamiltonian`, `Tensor`, and `Observable` objects, and inline arithmetic operations between Hamiltonians and other observables. [(#765)](https://github.com/PennyLaneAI/pennylane/pull/765) Hamiltonians can now easily be defined as sums of observables: ```pycon3 >>> H = 3 * qml.PauliZ(0) - (qml.PauliX(0) @ qml.PauliX(1)) + qml.Hamiltonian([4], [qml.PauliZ(0)]) >>> print(H) (7.0) [Z0] + (-1.0) [X0 X1] ``` * Adds `compare()` method to `Observable` and `Hamiltonian` classes, which allows for comparison between observable quantities. [(#765)](https://github.com/PennyLaneAI/pennylane/pull/765) ```pycon3 >>> H = qml.Hamiltonian([1], [qml.PauliZ(0)]) >>> obs = qml.PauliZ(0) @ qml.Identity(1) >>> print(H.compare(obs)) True ``` ```pycon3 >>> H = qml.Hamiltonian([2], [qml.PauliZ(0)]) >>> obs = qml.PauliZ(1) @ qml.Identity(0) >>> print(H.compare(obs)) False ``` * Adds `simplify()` method to the `Hamiltonian` class. [(#765)](https://github.com/PennyLaneAI/pennylane/pull/765) ```pycon3 >>> H = qml.Hamiltonian([1, 2], [qml.PauliZ(0), qml.PauliZ(0) @ qml.Identity(1)]) >>> H.simplify() >>> print(H) (3.0) [Z0] ``` * Added a new bit-flip mixer to the `qml.qaoa` module. [(#774)](https://github.com/PennyLaneAI/pennylane/pull/774) * Summation of two `Wires` objects is now supported and will return a `Wires` object containing the set of all wires defined by the terms in the summation. [(#812)](https://github.com/PennyLaneAI/pennylane/pull/812) <h3>Breaking changes</h3> * The PennyLane NumPy module now returns scalar (zero-dimensional) arrays where Python scalars were previously returned. [(#820)](https://github.com/PennyLaneAI/pennylane/pull/820) [(#833)](https://github.com/PennyLaneAI/pennylane/pull/833) For example, this affects array element indexing, and summation: ```pycon >>> x = np.array([1, 2, 3], requires_grad=False) >>> x[0] tensor(1, requires_grad=False) >>> np.sum(x) tensor(6, requires_grad=True) ``` This may require small updates to user code. A convenience method, `np.tensor.unwrap()`, has been added to help ease the transition. This converts PennyLane NumPy tensors to standard NumPy arrays and Python scalars: ```pycon >>> x = np.array(1.543, requires_grad=False) >>> x.unwrap() 1.543 ``` Note, however, that information regarding array differentiability will be lost. * The device capabilities dictionary has been redesigned, for clarity and robustness. In particular, the capabilities dictionary is now inherited from the parent class, various keys have more expressive names, and all keys are now defined in the base device class. For more details, please [refer to the developer documentation](https://pennylane.readthedocs.io/en/stable/development/plugins.html#device-capabilities). [(#781)](https://github.com/PennyLaneAI/pennylane/pull/781/files) <h3>Bug fixes</h3> * Changed to use lists for storing variable values inside `BaseQNode` allowing complex matrices to be passed to `QubitUnitary`. [(#773)](https://github.com/PennyLaneAI/pennylane/pull/773) * Fixed a bug within `default.qubit`, resulting in greater efficiency when applying a state vector to all wires on the device. [(#849)](https://github.com/PennyLaneAI/pennylane/pull/849) <h3>Documentation</h3> * Equations have been added to the `qml.sample` and `qml.probs` docstrings to clarify the mathematical foundation of the performed measurements. [(#843)](https://github.com/PennyLaneAI/pennylane/pull/843) <h3>Contributors</h3> This release contains contributions from (in alphabetical order): Aroosa Ijaz, Juan Miguel Arrazola, Thomas Bromley, Jack Ceroni, Alain Delgado Gran, Josh Izaac, Soran Jahangiri, Nathan Killoran, Robert Lang, Cedric Lin, Olivia Di Matteo, Nicolás Quesada, Maria Schuld, Antal Száva.
pennylane/doc/releases/changelog-0.12.0.md/0
{ "file_path": "pennylane/doc/releases/changelog-0.12.0.md", "repo_id": "pennylane", "token_count": 5076 }
44
:orphan: # Release 0.22.2 <h3>Bug fixes</h3> * Most compilation transforms, and relevant subroutines, have been updated to support just-in-time compilation with jax.jit. This fix was intended to be included in `v0.22.0`, but due to a bug was incomplete. [(#2397)](https://github.com/PennyLaneAI/pennylane/pull/2397) <h3>Documentation</h3> * The documentation run has been updated to require `jinja2==3.0.3` due to an issue that arises with `jinja2` `v3.1.0` and `sphinx` `v3.5.3`. [(#2378)](https://github.com/PennyLaneAI/pennylane/pull/2378) <h3>Contributors</h3> This release contains contributions from (in alphabetical order): Olivia Di Matteo, Christina Lee, Romain Moyard, Antal Száva.
pennylane/doc/releases/changelog-0.22.2.md/0
{ "file_path": "pennylane/doc/releases/changelog-0.22.2.md", "repo_id": "pennylane", "token_count": 263 }
45
:orphan: # Release 0.33.0 <h3>New features since last release</h3> <h4>Postselection and statistics in mid-circuit measurements 📌</h4> * It is now possible to request postselection on a mid-circuit measurement. [(#4604)](https://github.com/PennyLaneAI/pennylane/pull/4604) This can be achieved by specifying the `postselect` keyword argument in `qml.measure` as either `0` or `1`, corresponding to the basis states. ```python import pennylane as qml dev = qml.device("default.qubit") @qml.qnode(dev, interface=None) def circuit(): qml.Hadamard(wires=0) qml.CNOT(wires=[0, 1]) qml.measure(0, postselect=1) return qml.expval(qml.PauliZ(1)), qml.sample(wires=1) ``` This circuit prepares the :math:`| \Phi^{+} \rangle` Bell state and postselects on measuring :math:`|1\rangle` in wire `0`. The output of wire `1` is then also :math:`|1\rangle` at all times: ```pycon >>> circuit(shots=10) (-1.0, array([1, 1, 1, 1, 1, 1])) ``` Note that the number of shots is less than the requested amount because we have thrown away the samples where :math:`|0\rangle` was measured in wire `0`. * Measurement statistics can now be collected for mid-circuit measurements. [(#4544)](https://github.com/PennyLaneAI/pennylane/pull/4544) ```python dev = qml.device("default.qubit") @qml.qnode(dev) def circ(x, y): qml.RX(x, wires=0) qml.RY(y, wires=1) m0 = qml.measure(1) return qml.expval(qml.PauliZ(0)), qml.expval(m0), qml.sample(m0) ``` ```pycon >>> circ(1.0, 2.0, shots=10000) (0.5606, 0.7089, array([0, 1, 1, ..., 1, 1, 1])) ``` Support is provided for both [finite-shot and analytic modes](https://docs.pennylane.ai/en/stable/introduction/circuits.html#shots) and devices default to using the [deferred measurement](https://docs.pennylane.ai/en/stable/code/api/pennylane.defer_measurements.html) principle to enact the mid-circuit measurements. <h4>Exponentiate Hamiltonians with flexible Trotter products 🐖</h4> * Higher-order Trotter-Suzuki methods are now easily accessible through a new operation called `TrotterProduct`. [(#4661)](https://github.com/PennyLaneAI/pennylane/pull/4661) Trotterization techniques are an affective route towards accurate and efficient Hamiltonian simulation. The Suzuki-Trotter product formula allows for the ability to express higher-order approximations to the matrix exponential of a Hamiltonian, and it is now available to use in PennyLane via the `TrotterProduct` operation. Simply specify the `order` of the approximation and the evolution `time`. ```python coeffs = [0.25, 0.75] ops = [qml.PauliX(0), qml.PauliZ(0)] H = qml.dot(coeffs, ops) dev = qml.device("default.qubit", wires=2) @qml.qnode(dev) def circuit(): qml.Hadamard(0) qml.TrotterProduct(H, time=2.4, order=2) return qml.state() ``` ```pycon >>> circuit() [-0.13259524+0.59790098j 0. +0.j -0.13259524-0.77932754j 0. +0.j ] ``` * Approximating matrix exponentiation with random product formulas, qDrift, is now available with the new `QDrift` operation. [(#4671)](https://github.com/PennyLaneAI/pennylane/pull/4671) As shown in [1811.08017](https://arxiv.org/pdf/1811.08017.pdf), qDrift is a Markovian process that can provide a speedup in Hamiltonian simulation. At a high level, qDrift works by randomly sampling from the Hamiltonian terms with a probability that depends on the Hamiltonian coefficients. This method for Hamiltonian simulation is now ready to use in PennyLane with the `QDrift` operator. Simply specify the evolution `time` and the number of samples drawn from the Hamiltonian, `n`: ```python coeffs = [0.25, 0.75] ops = [qml.PauliX(0), qml.PauliZ(0)] H = qml.dot(coeffs, ops) dev = qml.device("default.qubit", wires=2) @qml.qnode(dev) def circuit(): qml.Hadamard(0) qml.QDrift(H, time=1.2, n = 10) return qml.probs() ``` ```pycon >>> circuit() array([0.61814334, 0. , 0.38185666, 0. ]) ``` <h4>Building blocks for quantum phase estimation 🧱</h4> * A new operator called `CosineWindow` has been added to prepare an initial state based on a cosine wave function. [(#4683)](https://github.com/PennyLaneAI/pennylane/pull/4683) As outlined in [2110.09590](https://arxiv.org/pdf/2110.09590.pdf), the cosine tapering window is part of a modification to quantum phase estimation that can provide a cubic improvement to the algorithm's error rate. Using `CosineWindow` will prepare a state whose amplitudes follow a cosinusoidal distribution over the computational basis. ```python import matplotlib.pyplot as plt dev = qml.device('default.qubit', wires=4) @qml.qnode(dev) def example_circuit(): qml.CosineWindow(wires=range(4)) return qml.state() output = example_circuit() plt.style.use("pennylane.drawer.plot") plt.bar(range(len(output)), output) plt.show() ``` <img src="https://docs.pennylane.ai/en/stable/_images/cosine_window.png" width=50%/> * Controlled gate sequences raised to decreasing powers, a sub-block in quantum phase estimation, can now be created with the new `ControlledSequence` operator. [(#4707)](https://github.com/PennyLaneAI/pennylane/pull/4707/) To use `ControlledSequence`, specify the controlled unitary operator and the control wires, `control`: ```python dev = qml.device("default.qubit", wires = 4) @qml.qnode(dev) def circuit(): for i in range(3): qml.Hadamard(wires = i) qml.ControlledSequence(qml.RX(0.25, wires = 3), control = [0, 1, 2]) qml.adjoint(qml.QFT)(wires = range(3)) return qml.probs(wires = range(3)) ``` ```pycon >>> print(circuit()) [0.92059345 0.02637178 0.00729619 0.00423258 0.00360545 0.00423258 0.00729619 0.02637178] ``` <h4>New device capabilities, integration with Catalyst, and more! ⚗️</h4> * `default.qubit` now uses the new `qml.devices.Device` API and functionality in `qml.devices.qubit`. If you experience any issues with the updated `default.qubit`, please let us know by [posting an issue](https://github.com/PennyLaneAI/pennylane/issues/new/choose). The old version of the device is still accessible by the short name `default.qubit.legacy`, or directly via `qml.devices.DefaultQubitLegacy`. [(#4594)](https://github.com/PennyLaneAI/pennylane/pull/4594) [(#4436)](https://github.com/PennyLaneAI/pennylane/pull/4436) [(#4620)](https://github.com/PennyLaneAI/pennylane/pull/4620) [(#4632)](https://github.com/PennyLaneAI/pennylane/pull/4632) This changeover has a number of benefits for `default.qubit`, including: * The number of wires is now optional — simply having `qml.device("default.qubit")` is valid! If wires are not provided at instantiation, the device automatically infers the required number of wires for each circuit provided for execution. ```python dev = qml.device("default.qubit") @qml.qnode(dev) def circuit(): qml.PauliZ(0) qml.RZ(0.1, wires=1) qml.Hadamard(2) return qml.state() ``` ```pycon >>> print(qml.draw(circuit)()) 0: ──Z────────┤ State 1: ──RZ(0.10)─┤ State 2: ──H────────┤ State ``` * `default.qubit` is no longer silently swapped out with an interface-appropriate device when the backpropagation differentiation method is used. For example, consider: ```python import jax dev = qml.device("default.qubit", wires=1) @qml.qnode(dev, diff_method="backprop") def f(x): qml.RX(x, wires=0) return qml.expval(qml.PauliZ(0)) f(jax.numpy.array(0.2)) ``` In previous versions of PennyLane, the device will be swapped for the JAX equivalent: ```pycon >>> f.device <DefaultQubitJax device (wires=1, shots=None) at 0x7f8c8bff50a0> >>> f.device == dev False ``` Now, `default.qubit` can itself dispatch to all the interfaces in a backprop-compatible way and hence does not need to be swapped: ```pycon >>> f.device <default.qubit device (wires=1) at 0x7f20d043b040> >>> f.device == dev True ``` * A QNode that has been decorated with `qjit` from PennyLane's [Catalyst](https://docs.pennylane.ai/projects/catalyst) library for just-in-time hybrid compilation is now compatible with `qml.draw`. [(#4609)](https://github.com/PennyLaneAI/pennylane/pull/4609) ```python import catalyst @catalyst.qjit @qml.qnode(qml.device("lightning.qubit", wires=3)) def circuit(x, y, z, c): """A quantum circuit on three wires.""" @catalyst.for_loop(0, c, 1) def loop(i): qml.Hadamard(wires=i) qml.RX(x, wires=0) loop() qml.RY(y, wires=1) qml.RZ(z, wires=2) return qml.expval(qml.PauliZ(0)) draw = qml.draw(circuit, decimals=None)(1.234, 2.345, 3.456, 1) ``` ```pycon >>> print(draw) 0: ──RX──H──┤ <Z> 1: ──H───RY─┤ 2: ──RZ─────┤ ``` <h3>Improvements 🛠</h3> <h4>More PyTrees!</h4> * `MeasurementProcess` and `QuantumScript` objects are now registered as JAX PyTrees. [(#4607)](https://github.com/PennyLaneAI/pennylane/pull/4607) [(#4608)](https://github.com/PennyLaneAI/pennylane/pull/4608) It is now possible to JIT-compile functions with arguments that are a `MeasurementProcess` or a `QuantumScript`: ```python import jax tape0 = qml.tape.QuantumTape([qml.RX(1.0, 0), qml.RY(0.5, 0)], [qml.expval(qml.PauliZ(0))]) dev = qml.device('lightning.qubit', wires=5) execute_kwargs = {"device": dev, "gradient_fn": qml.gradients.param_shift, "interface":"jax"} jitted_execute = jax.jit(qml.execute, static_argnames=execute_kwargs.keys()) jitted_execute((tape0, ), **execute_kwargs) ``` <h4>Improving QChem and existing algorithms</h4> * Computationally expensive functions in `integrals.py`, `electron_repulsion` and `_hermite_coulomb`, have been modified to replace indexing with slicing for better compatibility with JAX. [(#4685)](https://github.com/PennyLaneAI/pennylane/pull/4685) * `qml.qchem.import_state` has been extended to import more quantum chemistry wavefunctions, from MPS, DMRG and SHCI classical calculations performed with the Block2 and Dice libraries. [#4523](https://github.com/PennyLaneAI/pennylane/pull/4523) [#4524](https://github.com/PennyLaneAI/pennylane/pull/4524) [#4626](https://github.com/PennyLaneAI/pennylane/pull/4626) [#4634](https://github.com/PennyLaneAI/pennylane/pull/4634) Check out our [how-to guide](https://pennylane.ai/qml/demos/tutorial_initial_state_preparation) to learn more about how PennyLane integrates with your favourite quantum chemistry libraries. * The qchem `fermionic_dipole` and `particle_number` functions have been updated to use a `FermiSentence`. The deprecated features for using tuples to represent fermionic operations are removed. [(#4546)](https://github.com/PennyLaneAI/pennylane/pull/4546) [(#4556)](https://github.com/PennyLaneAI/pennylane/pull/4556) * The tensor-network template `qml.MPS` now supports changing the `offset` between subsequent blocks for more flexibility. [(#4531)](https://github.com/PennyLaneAI/pennylane/pull/4531) * Builtin types support with `qml.pauli_decompose` have been improved. [(#4577)](https://github.com/PennyLaneAI/pennylane/pull/4577) * `AmplitudeEmbedding` now inherits from `StatePrep`, allowing for it to not be decomposed when at the beginning of a circuit, thus behaving like `StatePrep`. [(#4583)](https://github.com/PennyLaneAI/pennylane/pull/4583) * `qml.cut_circuit` is now compatible with circuits that compute the expectation values of Hamiltonians with two or more terms. [(#4642)](https://github.com/PennyLaneAI/pennylane/pull/4642) <h4>Next-generation device API</h4> * `default.qubit` now tracks the number of equivalent qpu executions and total shots when the device is sampling. Note that `"simulations"` denotes the number of simulation passes, whereas `"executions"` denotes how many different computational bases need to be sampled in. Additionally, the new `default.qubit` tracks the results of `device.execute`. [(#4628)](https://github.com/PennyLaneAI/pennylane/pull/4628) [(#4649)](https://github.com/PennyLaneAI/pennylane/pull/4649) * `DefaultQubit` can now accept a `jax.random.PRNGKey` as a `seed` to set the key for the JAX pseudo random number generator when using the JAX interface. This corresponds to the `prng_key` on `default.qubit.jax` in the old API. [(#4596)](https://github.com/PennyLaneAI/pennylane/pull/4596) * The `JacobianProductCalculator` abstract base class and implementations `TransformJacobianProducts` `DeviceDerivatives`, and `DeviceJacobianProducts` have been added to `pennylane.interfaces.jacobian_products`. [(#4435)](https://github.com/PennyLaneAI/pennylane/pull/4435) [(#4527)](https://github.com/PennyLaneAI/pennylane/pull/4527) [(#4637)](https://github.com/PennyLaneAI/pennylane/pull/4637) * `DefaultQubit` dispatches to a faster implementation for applying `ParametrizedEvolution` to a state when it is more efficient to evolve the state than the operation matrix. [(#4598)](https://github.com/PennyLaneAI/pennylane/pull/4598) [(#4620)](https://github.com/PennyLaneAI/pennylane/pull/4620) * Wires can be provided to the new device API. [(#4538)](https://github.com/PennyLaneAI/pennylane/pull/4538) [(#4562)](https://github.com/PennyLaneAI/pennylane/pull/4562) * `qml.sample()` in the new device API now returns a `np.int64` array instead of `np.bool8`. [(#4539)](https://github.com/PennyLaneAI/pennylane/pull/4539) * The new device API now has a `repr()` method. [(#4562)](https://github.com/PennyLaneAI/pennylane/pull/4562) * `DefaultQubit` now works as expected with measurement processes that don't specify wires. [(#4580)](https://github.com/PennyLaneAI/pennylane/pull/4580) * Various improvements to measurements have been made for feature parity between `default.qubit.legacy` and the new `DefaultQubit`. This includes not trying to squeeze batched `CountsMP` results and implementing `MutualInfoMP.map_wires`. [(#4574)](https://github.com/PennyLaneAI/pennylane/pull/4574) * `devices.qubit.simulate` now accepts an interface keyword argument. If a QNode with `DefaultQubit` specifies an interface, the result will be computed with that interface. [(#4582)](https://github.com/PennyLaneAI/pennylane/pull/4582) * `ShotAdaptiveOptimizer` has been updated to pass shots to QNode executions instead of overriding device shots before execution. This makes it compatible with the new device API. [(#4599)](https://github.com/PennyLaneAI/pennylane/pull/4599) * `pennylane.devices.preprocess` now offers the transforms `decompose`, `validate_observables`, `validate_measurements`, `validate_device_wires`, `validate_multiprocessing_workers`, `warn_about_trainable_observables`, and `no_sampling` to assist in constructing devices under the new device API. [(#4659)](https://github.com/PennyLaneAI/pennylane/pull/4659) * Updated `qml.device`, `devices.preprocessing` and the `tape_expand.set_decomposition` context manager to bring `DefaultQubit` to feature parity with `default.qubit.legacy` with regards to using custom decompositions. The `DefaultQubit` device can now be included in a `set_decomposition` context or initialized with a `custom_decomps` dictionary, as well as a custom `max_depth` for decomposition. [(#4675)](https://github.com/PennyLaneAI/pennylane/pull/4675) <h4>Other improvements</h4> * The `StateMP` measurement now accepts a wire order (e.g., a device wire order). The `process_state` method will re-order the given state to go from the inputted wire-order to the process's wire-order. If the process's wire-order contains extra wires, it will assume those are in the zero-state. [(#4570)](https://github.com/PennyLaneAI/pennylane/pull/4570) [(#4602)](https://github.com/PennyLaneAI/pennylane/pull/4602) * Methods called `add_transform` and `insert_front_transform` have been added to `TransformProgram`. [(#4559)](https://github.com/PennyLaneAI/pennylane/pull/4559) * Instances of the `TransformProgram` class can now be added together. [(#4549)](https://github.com/PennyLaneAI/pennylane/pull/4549) * Transforms can now be applied to devices following the new device API. [(#4667)](https://github.com/PennyLaneAI/pennylane/pull/4667) * All gradient transforms have been updated to the new transform program system. [(#4595)](https://github.com/PennyLaneAI/pennylane/pull/4595) * Multi-controlled operations with a single-qubit special unitary target can now automatically decompose. [(#4697)](https://github.com/PennyLaneAI/pennylane/pull/4697) * `pennylane.defer_measurements` will now exit early if the input does not contain mid circuit measurements. [(#4659)](https://github.com/PennyLaneAI/pennylane/pull/4659) * The density matrix aspects of `StateMP` have been split into their own measurement process called `DensityMatrixMP`. [(#4558)](https://github.com/PennyLaneAI/pennylane/pull/4558) * `StateMeasurement.process_state` now assumes that the input is flat. `ProbabilityMP.process_state` has been updated to reflect this assumption and avoid redundant reshaping. [(#4602)](https://github.com/PennyLaneAI/pennylane/pull/4602) * `qml.exp` returns a more informative error message when decomposition is unavailable for non-unitary operators. [(#4571)](https://github.com/PennyLaneAI/pennylane/pull/4571) * Added `qml.math.get_deep_interface` to get the interface of a scalar hidden deep in lists or tuples. [(#4603)](https://github.com/PennyLaneAI/pennylane/pull/4603) * Updated `qml.math.ndim` and `qml.math.shape` to work with built-in lists or tuples that contain interface-specific scalar dat (e.g., `[(tf.Variable(1.1), tf.Variable(2.2))]`). [(#4603)](https://github.com/PennyLaneAI/pennylane/pull/4603) * When decomposing a unitary matrix with `one_qubit_decomposition` and opting to include the `GlobalPhase` in the decomposition, the phase is no longer cast to `dtype=complex`. [(#4653)](https://github.com/PennyLaneAI/pennylane/pull/4653) * `_qfunc_output` has been removed from `QuantumScript`, as it is no longer necessary. There is still a `_qfunc_output` property on `QNode` instances. [(#4651)](https://github.com/PennyLaneAI/pennylane/pull/4651) * `qml.data.load` properly handles parameters that come after `'full'` [(#4663)](https://github.com/PennyLaneAI/pennylane/pull/4663) * The `qml.jordan_wigner` function has been modified to optionally remove the imaginary components of the computed qubit operator, if imaginary components are smaller than a threshold. [(#4639)](https://github.com/PennyLaneAI/pennylane/pull/4639) * `qml.data.load` correctly performs a full download of the dataset after a partial download of the same dataset has already been performed. [(#4681)](https://github.com/PennyLaneAI/pennylane/pull/4681) * The performance of `qml.data.load()` has been improved when partially loading a dataset [(#4674)](https://github.com/PennyLaneAI/pennylane/pull/4674) * Plots generated with the `pennylane.drawer.plot` style of `matplotlib.pyplot` now have black axis labels and are generated at a default DPI of 300. [(#4690)](https://github.com/PennyLaneAI/pennylane/pull/4690) * Shallow copies of the `QNode` now also copy the `execute_kwargs` and transform program. When applying a transform to a `QNode`, the new qnode is only a shallow copy of the original and thus keeps the same device. [(#4736)](https://github.com/PennyLaneAI/pennylane/pull/4736) * `QubitDevice` and `CountsMP` are updated to disregard samples containing failed hardware measurements (record as `np.NaN`) when tallying samples, rather than counting failed measurements as ground-state measurements, and to display `qml.counts` coming from these hardware devices correctly. [(#4739)](https://github.com/PennyLaneAI/pennylane/pull/4739) <h3>Breaking changes 💔</h3> * `qml.defer_measurements` now raises an error if a transformed circuit measures `qml.probs`, `qml.sample`, or `qml.counts` without any wires or observable, or if it measures `qml.state`. [(#4701)](https://github.com/PennyLaneAI/pennylane/pull/4701) * The device test suite now converts device keyword arguments to integers or floats if possible. [(#4640)](https://github.com/PennyLaneAI/pennylane/pull/4640) * `MeasurementProcess.eigvals()` now raises an `EigvalsUndefinedError` if the measurement observable does not have eigenvalues. [(#4544)](https://github.com/PennyLaneAI/pennylane/pull/4544) * The `__eq__` and `__hash__` methods of `Operator` and `MeasurementProcess` no longer rely on the object's address in memory. Using `==` with operators and measurement processes will now behave the same as `qml.equal`, and objects of the same type with the same data and hyperparameters will have the same hash. [(#4536)](https://github.com/PennyLaneAI/pennylane/pull/4536) In the following scenario, the second and third code blocks show the previous and current behaviour of operator and measurement process equality, determined by `==`: ```python op1 = qml.PauliX(0) op2 = qml.PauliX(0) op3 = op1 ``` Old behaviour: ```pycon >>> op1 == op2 False >>> op1 == op3 True ``` New behaviour: ```pycon >>> op1 == op2 True >>> op1 == op3 True ``` The `__hash__` dunder method defines the hash of an object. The default hash of an object is determined by the objects memory address. However, the new hash is determined by the properties and attributes of operators and measurement processes. Consider the scenario below. The second and third code blocks show the previous and current behaviour. ```python op1 = qml.PauliX(0) op2 = qml.PauliX(0) ``` Old behaviour: ```pycon >>> print({op1, op2}) {PauliX(wires=[0]), PauliX(wires=[0])} ``` New behaviour: ```pycon >>> print({op1, op2}) {PauliX(wires=[0])} ``` * The old return type and associated functions `qml.enable_return` and `qml.disable_return` have been removed. [(#4503)](https://github.com/PennyLaneAI/pennylane/pull/4503) * The `mode` keyword argument in `QNode` has been removed. Please use `grad_on_execution` instead. [(#4503)](https://github.com/PennyLaneAI/pennylane/pull/4503) * The CV observables `qml.X` and `qml.P` have been removed. Please use `qml.QuadX` and `qml.QuadP` instead. [(#4533)](https://github.com/PennyLaneAI/pennylane/pull/4533) * The `sampler_seed` argument of `qml.gradients.spsa_grad` has been removed. Instead, the `sampler_rng` argument should be set, either to an integer value, which will be used to create a PRNG internally, or to a NumPy pseudo-random number generator (PRNG) created via `np.random.default_rng(seed)`. [(#4550)](https://github.com/PennyLaneAI/pennylane/pull/4550) * The `QuantumScript.set_parameters` method and the `QuantumScript.data` setter have been removed. Please use `QuantumScript.bind_new_parameters` instead. [(#4548)](https://github.com/PennyLaneAI/pennylane/pull/4548) * The method `tape.unwrap()` and corresponding `UnwrapTape` and `Unwrap` classes have been removed. Instead of `tape.unwrap()`, use `qml.transforms.convert_to_numpy_parameters`. [(#4535)](https://github.com/PennyLaneAI/pennylane/pull/4535) * The `RandomLayers.compute_decomposition` keyword argument `ratio_imprivitive` has been changed to `ratio_imprim` to match the call signature of the operation. [(#4552)](https://github.com/PennyLaneAI/pennylane/pull/4552) * The private `TmpPauliRot` operator used for `SpecialUnitary` no longer decomposes to nothing when the theta value is trainable. [(#4585)](https://github.com/PennyLaneAI/pennylane/pull/4585) * `ProbabilityMP.marginal_prob` has been removed. Its contents have been moved into `process_state`, which effectively just called `marginal_prob` with `np.abs(state) ** 2`. [(#4602)](https://github.com/PennyLaneAI/pennylane/pull/4602) <h3>Deprecations 👋</h3> * The following decorator syntax for transforms has been deprecated and will raise a warning: [(#4457)](https://github.com/PennyLaneAI/pennylane/pull/4457/) ```python @transform_fn(**transform_kwargs) @qml.qnode(dev) def circuit(): ... ``` If you are using a transform that has supporting `transform_kwargs`, please call the transform directly using `circuit = transform_fn(circuit, **transform_kwargs)`, or use `functools.partial`: ```python @functools.partial(transform_fn, **transform_kwargs) @qml.qnode(dev) def circuit(): ... ``` * The `prep` keyword argument in `QuantumScript` has been deprecated and will be removed from `QuantumScript`. `StatePrepBase` operations should be placed at the beginning of the `ops` list instead. [(#4554)](https://github.com/PennyLaneAI/pennylane/pull/4554) * `qml.gradients.pulse_generator` has been renamed to `qml.gradients.pulse_odegen` to adhere to paper naming conventions. During v0.33, `pulse_generator` is still available but raises a warning. [(#4633)](https://github.com/PennyLaneAI/pennylane/pull/4633) <h3>Documentation 📝</h3> * A warning section in the docstring for `DefaultQubit` regarding the start method used in multiprocessing has been added. This may help users circumvent issues arising in Jupyter notebooks on macOS for example. [(#4622)](https://github.com/PennyLaneAI/pennylane/pull/4622) * Documentation improvements to the new device API have been made. The documentation now correctly states that interface-specific parameters are only passed to the device for backpropagation derivatives. [(#4542)](https://github.com/PennyLaneAI/pennylane/pull/4542) * Functions for qubit-simulation to the `qml.devices` sub-page of the "Internal" section have been added. Note that these functions are unstable while device upgrades are underway. [(#4555)](https://github.com/PennyLaneAI/pennylane/pull/4555) * A documentation improvement to the usage example in the `qml.QuantumMonteCarlo` page has been made. An integral was missing the differential :math:`dx`. [(#4593)](https://github.com/PennyLaneAI/pennylane/pull/4593) * A documentation improvement for the use of the `pennylane` style of `qml.drawer` and the `pennylane.drawer.plot` style of `matplotlib.pyplot` has been made by clarifying the use of the default font. [(#4690)](https://github.com/PennyLaneAI/pennylane/pull/4690) <h3>Bug fixes 🐛</h3> * Jax jit now works when a probability measurement is broadcasted onto all wires. [(#4742)](https://github.com/PennyLaneAI/pennylane/pull/4742) * Fixed `LocalHilbertSchmidt.compute_decomposition` so that the template can be used in a QNode. [(#4719)](https://github.com/PennyLaneAI/pennylane/pull/4719) * Fixes `transforms.transpile` with arbitrary measurement processes. [(#4732)](https://github.com/PennyLaneAI/pennylane/pull/4732) * Providing `work_wires=None` to `qml.GroverOperator` no longer interprets `None` as a wire. [(#4668)](https://github.com/PennyLaneAI/pennylane/pull/4668) * Fixed an issue where the `__copy__` method of the `qml.Select()` operator attempted to access un-initialized data. [(#4551)](https://github.com/PennyLaneAI/pennylane/pull/4551) * Fixed the `skip_first` option in `expand_tape_state_prep`. [(#4564)](https://github.com/PennyLaneAI/pennylane/pull/4564) * `convert_to_numpy_parameters` now uses `qml.ops.functions.bind_new_parameters`. This reinitializes the operation and makes sure everything references the new NumPy parameters. [(#4540)](https://github.com/PennyLaneAI/pennylane/pull/4540) * `tf.function` no longer breaks `ProbabilityMP.process_state`, which is needed by new devices. [(#4470)](https://github.com/PennyLaneAI/pennylane/pull/4470) * Fixed unit tests for `qml.qchem.mol_data`. [(#4591)](https://github.com/PennyLaneAI/pennylane/pull/4591) * Fixed `ProbabilityMP.process_state` so that it allows for proper Autograph compilation. Without this, decorating a QNode that returns an `expval` with `tf.function` would fail when computing the expectation. [(#4590)](https://github.com/PennyLaneAI/pennylane/pull/4590) * The `torch.nn.Module` properties are now accessible on a `pennylane.qnn.TorchLayer`. [(#4611)](https://github.com/PennyLaneAI/pennylane/pull/4611) * `qml.math.take` with Pytorch now returns `tensor[..., indices]` when the user requests the last axis (`axis=-1`). Without the fix, it would wrongly return `tensor[indices]`. [(#4605)](https://github.com/PennyLaneAI/pennylane/pull/4605) * Ensured the logging `TRACE` level works with gradient-free execution. [(#4669)](https://github.com/PennyLaneAI/pennylane/pull/4669) <h3>Contributors ✍️</h3> This release contains contributions from (in alphabetical order): Guillermo Alonso, Utkarsh Azad, Thomas Bromley, Isaac De Vlugt, Jack Brown, Stepan Fomichev, Joana Fraxanet, Diego Guala, Soran Jahangiri, Edward Jiang, Korbinian Kottmann, Ivana Kurečić Christina Lee, Lillian M. A. Frederiksen, Vincent Michaud-Rioux, Romain Moyard, Daniel F. Nino, Lee James O'Riordan, Mudit Pandey, Matthew Silverman, Jay Soni.
pennylane/doc/releases/changelog-0.33.0.md/0
{ "file_path": "pennylane/doc/releases/changelog-0.33.0.md", "repo_id": "pennylane", "token_count": 10577 }
46
:orphan: # Release 0.39.0-dev (development release) <h3>New features since last release</h3> <h3>Improvements 🛠</h3> * Improve unit testing for capturing of nested control flows. [(#6111)](https://github.com/PennyLaneAI/pennylane/pull/6111) * Some custom primitives for the capture project can now be imported via `from pennylane.capture.primitives import *`. [(#6129)](https://github.com/PennyLaneAI/pennylane/pull/6129) <h3>Breaking changes 💔</h3> <h3>Deprecations 👋</h3> <h3>Documentation 📝</h3> <h3>Bug fixes 🐛</h3> * Fix Pytree serialization of operators with empty shot vectors: [(#6155)](https://github.com/PennyLaneAI/pennylane/pull/6155) <h3>Contributors ✍️</h3> This release contains contributions from (in alphabetical order): Utkarsh Azad Jack Brown Christina Lee
pennylane/doc/releases/changelog-dev.md/0
{ "file_path": "pennylane/doc/releases/changelog-dev.md", "repo_id": "pennylane", "token_count": 302 }
47
# Copyright 2018-2021 Xanadu Quantum Technologies Inc. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. r""" This module contains the :func:`about` function to display all the details of the PennyLane installation, e.g., OS, version, `Numpy` and `Scipy` versions, installation method. """ import platform import sys from importlib import metadata from subprocess import check_output from sys import version_info import numpy import scipy def about(): """ Prints the information for pennylane installation. """ if version_info[:2] == (3, 9): from pkg_resources import iter_entry_points # pylint:disable=import-outside-toplevel plugin_devices = iter_entry_points("pennylane.plugins") dist_name = "project_name" else: # pragma: no cover plugin_devices = metadata.entry_points( # pylint:disable=unexpected-keyword-arg group="pennylane.plugins" ) dist_name = "name" print(check_output([sys.executable, "-m", "pip", "show", "pennylane"]).decode()) print(f"Platform info: {platform.platform(aliased=True)}") print( f"Python version: {sys.version_info[0]}.{sys.version_info[1]}.{sys.version_info[2]}" ) print(f"Numpy version: {numpy.__version__}") print(f"Scipy version: {scipy.__version__}") print("Installed devices:") for d in plugin_devices: print(f"- {d.name} ({getattr(d.dist, dist_name)}-{d.dist.version})") if __name__ == "__main__": about()
pennylane/pennylane/about.py/0
{ "file_path": "pennylane/pennylane/about.py", "repo_id": "pennylane", "token_count": 729 }
48
# Copyright 2018-2023 Xanadu Quantum Technologies Inc. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """The data subpackage provides functionality to access, store and manipulate `quantum datasets <https://pennylane.ai/datasets>`_. .. note:: To start using datasets, please first see the :doc:`quantum datasets quickstart guide </introduction/data>`. Overview -------- Datasets are generally stored and accessed using the :class:`~pennylane.data.Dataset` class. Pre-computed datasets are available for download and can be accessed using the :func:`~pennylane.data.load` or :func:`~pennylane.data.load_interactive` functions. Additionally, users can easily create, write to disk, and read custom datasets using functions within the :class:`~pennylane.data.Dataset` class. .. autosummary:: :toctree: api attribute field Dataset DatasetNotWriteableError load load_interactive list_attributes list_datasets In addition, various dataset types are provided .. autosummary:: :toctree: api AttributeInfo DatasetAttribute DatasetArray DatasetScalar DatasetString DatasetList DatasetDict DatasetOperator DatasetNone DatasetMolecule DatasetSparseArray DatasetJSON DatasetTuple Datasets -------- The :class:`~.Dataset` class provides a portable storage format for information describing a physical system and its evolution. For example, a dataset for an arbitrary quantum system could have a Hamiltonian, its ground state, and an efficient state-preparation circuit for that state. Datasets can contain a range of object types, including: - ``numpy.ndarray`` - any numeric type - :class:`~.qchem.Molecule` - most :class:`~.Operator` types - ``list`` of any supported type - ``dict`` of any supported type, as long as the keys are strings For more details on using datasets, please see the :doc:`quantum datasets quickstart guide </introduction/data>`. Creating a Dataset ------------------ To create a new dataset in-memory, initialize a new :class:`~.Dataset` with the desired attributes: >>> hamiltonian = qml.Hamiltonian([1., 1.], [qml.Z(0), qml.Z(1)]) >>> eigvals, eigvecs = np.linalg.eigh(qml.matrix(hamiltonian)) >>> dataset = qml.data.Dataset( ... hamiltonian = hamiltonian, ... eigen = {"eigvals": eigvals, "eigvecs": eigvecs} ... ) >>> dataset.hamiltonian 1.0 * Z(0) + 1.0 * Z(1) >>> dataset.eigen {'eigvals': array([-2., 0., 0., 2.]), 'eigvecs': array([[0.+0.j, 0.+0.j, 0.+0.j, 1.+0.j], [0.+0.j, 1.+0.j, 0.+0.j, 0.+0.j], [0.+0.j, 0.+0.j, 1.+0.j, 0.+0.j], [1.+0.j, 0.+0.j, 0.+0.j, 0.+0.j]])} Attributes can also be assigned to the instance after creation: >>> dataset.ground_state = np.transpose(eigvecs)[np.argmin(eigvals)] >>> dataset.ground_state array([0.+0.j, 0.+0.j, 0.+0.j, 1.+0.j]) Reading and Writing Datasets ---------------------------- Datasets can be saved to disk for later use. Datasets use the HDF5 format for serialization, which uses the '.h5' file extension. To save a dataset, use the :meth:`Dataset.write()` method: >>> my_dataset = Dataset(...) >>> my_dataset.write("~/datasets/my_dataset.h5") To open a dataset from a file, use :meth:`Dataset.open()` class method: >>> my_dataset = Dataset.open("~/datasets/my_dataset.h5", mode="r") The ``mode`` argument follow the standard library convention --- ``r`` for reading, ``w-`` and ``w`` for create and overwrite, and 'a' for editing. ``open()`` can be used to create a new dataset directly on disk: >>> new_dataset = Dataset.open("~/datasets/new_datasets.h5", mode="w") By default, any changes made to an opened dataset will be committed directly to the file, which will fail if the file is opened read-only. The ``"copy"`` mode can be used to load the dataset into memory and detach it from the file: >>> my_dataset = Dataset.open("~/dataset/my_dataset/h5", mode="copy") >>> my_dataset.new_attribute = "abc" .. important:: Since opened datasets stream data from the disk, it is not possible to simultaneously access the same dataset from separately running scripts or multiple Jupyter notebooks. To get around this, either make a copy of the dataset in the disk or access the dataset using :meth:`Dataset.open()` with ``mode="copy"``. Attribute Metadata ------------------ Dataset attributes can also contain additional metadata, such as docstrings. The :func:`~.data.attribute` function can be used to attach metadata on assignment or initialization. >>> hamiltonian = qml.Hamiltonian([1., 1.], [qml.Z(0), qml.Z(1)]) >>> eigvals, eigvecs = np.linalg.eigh(qml.matrix(hamiltonian)) >>> dataset = qml.data.Dataset(hamiltonian = qml.data.attribute( ... hamiltonian, ... doc="The hamiltonian of the system")) >>> dataset.eigen = qml.data.attribute( ... {"eigvals": eigvals, "eigvecs": eigvecs}, ... doc="Eigenvalues and eigenvectors of the hamiltonain") This metadata can then be accessed using the :meth:`Dataset.attr_info` mapping: >>> dataset.attr_info["eigen"]["doc"] 'Eigenvalues and eigenvectors of the hamiltonain' Declarative API --------------- When creating datasets to model a physical system, it is common to collect the same data for a system under different conditions or assumptions. For example, a collection of datasets describing a quantum oscillator, which contains the first 1000 energy levels for different masses and force constants. The datasets declarative API allows us to create subclasses of :class:`Dataset` that define the required attributes, or 'fields', and their associated type and documentation: .. code-block:: python class QuantumOscillator(qml.data.Dataset, data_name="quantum_oscillator", identifiers=["mass", "force_constant"]): \"""Dataset describing a quantum oscillator.\""" mass: float = qml.data.field(doc = "The mass of the particle") force_constant: float = qml.data.field(doc = "The force constant of the oscillator") hamiltonian: qml.Hamiltonian = qml.data.field(doc = "The hamiltonian of the particle") energy_levels: np.ndarray = qml.data.field(doc = "The first 1000 energy levels of the system") The ``data_name`` keyword specifies a category or descriptive name for the dataset type, and the ``identifiers`` keyword to the class is used to specify fields that function as parameters, i.e they determine the behaviour of the system. When a ``QuantumOscillator`` dataset is created, its attributes will have the documentation from the field definition: >>> dataset = QuantumOscillator( ... mass=1, ... force_constant=0.5, ... hamiltonian=qml.X(0), ... energy_levels=np.array([0.1, 0.2]) ... ) >>> dataset.attr_info["mass"]["doc"] 'The mass of the particle' """ from .attributes import ( DatasetArray, DatasetDict, DatasetJSON, DatasetList, DatasetMolecule, DatasetNone, DatasetOperator, DatasetScalar, DatasetSparseArray, DatasetString, DatasetTuple, DatasetPyTree, ) from .base import DatasetNotWriteableError from .base.attribute import AttributeInfo, DatasetAttribute, attribute from .base.dataset import Dataset, field from .data_manager import DEFAULT, FULL, list_attributes, list_datasets, load, load_interactive __all__ = ( "AttributeInfo", "attribute", "field", "Dataset", "DatasetAttribute", "DatasetNotWriteableError", "DatasetArray", "DatasetPyTree", "DatasetScalar", "DatasetString", "DatasetList", "DatasetDict", "DatasetOperator", "DatasetNone", "DatasetMolecule", "DatasetSparseArray", "DatasetJSON", "DatasetTuple", "load", "load_interactive", "list_attributes", "list_datasets", "DEFAULT", "FULL", )
pennylane/pennylane/data/__init__.py/0
{ "file_path": "pennylane/pennylane/data/__init__.py", "repo_id": "pennylane", "token_count": 2857 }
49
# Copyright 2018-2024 Xanadu Quantum Technologies Inc. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ This file contains the snapshots function which extracts measurements from the qnode. """ import warnings from functools import partial import pennylane as qml from pennylane.tape import QuantumScript, QuantumScriptBatch from pennylane.transforms import transform from pennylane.typing import PostprocessingFn def _is_snapshot_compatible(dev): # The `_debugger` attribute is a good enough proxy for snapshot compatibility if isinstance(dev, qml.devices.LegacyDeviceFacade): return _is_snapshot_compatible(dev.target_device) return hasattr(dev, "_debugger") class _SnapshotDebugger: """A debugging context manager. Without an active debugging context, devices will not save their internal state when encoutering Snapshot operations. The debugger also serves as storage for the device states. Args: dev (Device): device to attach the debugger to """ def __init__(self, dev): self.snapshots = {} self.active = False self.device = dev dev._debugger = self def __enter__(self): self.active = True return self def __exit__(self, exc_type, exc_value, exc_traceback): self.active = False self.device._debugger = None @transform def snapshots(tape: QuantumScript) -> tuple[QuantumScriptBatch, PostprocessingFn]: r"""This transform processes :class:`~pennylane.Snapshot` instances contained in a circuit, depending on the compatibility of the execution device. For supported devices, the snapshots' measurements are computed as the execution progresses. Otherwise, the :func:`QuantumTape <pennylane.tape.QuantumTape>` gets split into several, one for each snapshot, with each aggregating all the operations up to that specific snapshot. Args: tape (QNode or QuantumTape or Callable): a quantum circuit. Returns: dictionary (dict) or qnode (QNode) or quantum function (Callable) or tuple[List[QuantumTape], function]: The transformed circuit as described in :func:`qml.transform <pennylane.transform>`. If tape splitting is carried out, the transform will be conservative about the wires that it includes in each tape. So, if all operations preceding a snapshot in a 3-qubit circuit has been applied to only one wire, the tape would only be looking at this wire. This can be overriden by the configuration of the execution device and its nature. Regardless of the transform's behaviour, the output is a dictionary where each key is either the tag supplied to the snapshot or its index in order of appearance, in addition to an ``"execution_results"`` entry that returns the final output of the quantum circuit. The post-processing function is responsible for aggregating the results into this dictionary. When the transform is applied to a QNode, the ``shots`` configuration is inherited from the device. Therefore, the snapshot measurements must be supported by the device's nature. An exception of this are the :func:`qml.state <pennylane.state>` measurements on finite-shot simulators. .. warning:: For devices that do not support snapshots (e.g QPUs, external plug-in simulators), be mindful of additional costs that you might incur due to the 1 separate execution/snapshot behaviour. **Example** .. code-block:: python3 dev = qml.device("default.qubit", wires=2) @qml.qnode(dev, interface=None) def circuit(): qml.Snapshot(measurement=qml.expval(qml.Z(0))) qml.Hadamard(wires=0) qml.CNOT(wires=[0, 1]) qml.Snapshot() return qml.expval(qml.X(0)) >>> qml.snapshots(circuit)() {0: 1.0, 1: array([0.70710678+0.j, 0. +0.j, 0. +0.j, 0.70710678+0.j]), 'execution_results': 0.0} .. code-block:: python3 dev = qml.device("default.qubit", shots=200, wires=2) @qml.snapshots @qml.qnode(dev, interface=None) def circuit(): qml.Hadamard(wires=0) qml.Snapshot() qml.CNOT(wires=[0, 1]) return qml.counts() >>> circuit() {0: array([0.70710678+0.j, 0. +0.j, 0.70710678+0.j, 0. +0.j]), 'execution_results': {'00': 101, '11': 99}} Here one can see how a device that does not natively support snapshots executes two different circuits. Additionally, a warning is raised along with the results: .. code-block:: python3 dev = qml.device("lightning.qubit", shots=100, wires=2) @qml.snapshots @qml.qnode(dev) def circuit(): qml.Hadamard(wires=0), qml.Snapshot(qml.counts()) qml.CNOT(wires=[0, 1]) return qml.expval(qml.PauliZ(0)) with circuit.device.tracker: out = circuit() >>> circuit.device.tracker.totals UserWarning: Snapshots are not supported for the given device. Therefore, a tape will be created for each snapshot, resulting in a total of n_snapshots + 1 executions. warnings.warn( {'batches': 1, 'simulations': 2, 'executions': 2, 'shots': 200, 'results': -0.16} >>> out {0: {'00': tensor(52, requires_grad=True), '10': tensor(48, requires_grad=True)}, 'execution_results': tensor(-0.1, requires_grad=True)} Here you can see the default behaviour of the transform for unsupported devices and you can see how the amount of wires included in each resulting tape is minimal: .. code-block:: python3 ops = [ qml.Snapshot(), qml.Hadamard(wires=0), qml.Snapshot("very_important_state"), qml.CNOT(wires=[0, 1]), qml.Snapshot(), ] measurements = [qml.expval(qml.PauliX(0))] tape = qml.tape.QuantumTape(ops, measurements) tapes, collect_results_into_dict = qml.snapshots(tape) >>> print(tapes) [<QuantumTape: wires=[], params=0>, <QuantumTape: wires=[0], params=0>, <QuantumTape: wires=[0, 1], params=0>, <QuantumTape: wires=[0, 1], params=0>] """ qml.devices.preprocess.validate_measurements(tape) new_tapes = [] accumulated_ops = [] snapshot_tags = [] for op in tape.operations: if isinstance(op, qml.Snapshot): snapshot_tags.append(op.tag or len(new_tapes)) meas_op = op.hyperparameters["measurement"] new_tapes.append( type(tape)(ops=accumulated_ops, measurements=[meas_op], shots=tape.shots) ) else: accumulated_ops.append(op) # Create an additional final tape if a return measurement exists if tape.measurements: snapshot_tags.append("execution_results") new_tapes.append( type(tape)(ops=accumulated_ops, measurements=tape.measurements, shots=tape.shots) ) def postprocessing_fn(results, snapshot_tags): return dict(zip(snapshot_tags, results)) return new_tapes, partial(postprocessing_fn, snapshot_tags=snapshot_tags) @snapshots.custom_qnode_transform def snapshots_qnode(self, qnode, targs, tkwargs): """A custom QNode wrapper for the snapshot transform :func:`~.snapshots`. Depending on whether the QNode's device supports snapshots, an efficient execution would be used. Otherwise, the QNode's tape would be split into several around the present snapshots and execute each individually. """ def get_snapshots(*args, **kwargs): # Need to construct to generate the tape and be able to validate qnode.construct(args, kwargs) qml.devices.preprocess.validate_measurements(qnode.tape) old_interface = qnode.interface if old_interface == "auto": qnode.interface = qml.math.get_interface(*args, *list(kwargs.values())) with _SnapshotDebugger(qnode.device) as dbg: # pylint: disable=protected-access results = qnode(*args, **kwargs) # Reset interface if old_interface == "auto": qnode.interface = "auto" dbg.snapshots["execution_results"] = results return dbg.snapshots if _is_snapshot_compatible(qnode.device): return get_snapshots warnings.warn( "Snapshots are not supported for the given device. Therefore, a tape will be " "created for each snapshot, resulting in a total of n_snapshots + 1 executions.", UserWarning, ) return self.default_qnode_transform(qnode, targs, tkwargs)
pennylane/pennylane/debugging/snapshot.py/0
{ "file_path": "pennylane/pennylane/debugging/snapshot.py", "repo_id": "pennylane", "token_count": 3439 }
50
# Copyright 2018-2024 Xanadu Quantum Technologies Inc. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ This module contains the default.tensor device to perform tensor network simulations of quantum circuits using ``quimb``. """ # pylint: disable=protected-access import copy import warnings from collections.abc import Callable from dataclasses import replace from functools import singledispatch from numbers import Number from typing import Optional, Union import numpy as np import pennylane as qml from pennylane.devices import DefaultExecutionConfig, Device, ExecutionConfig from pennylane.devices.modifiers import simulator_tracking, single_tape_support from pennylane.devices.preprocess import ( decompose, validate_device_wires, validate_measurements, validate_observables, ) from pennylane.measurements import ( ExpectationMP, MeasurementProcess, StateMeasurement, StateMP, VarianceMP, ) from pennylane.operation import Observable, Operation, Tensor from pennylane.ops import LinearCombination, Prod, SProd, Sum from pennylane.tape import QuantumScript, QuantumScriptOrBatch from pennylane.templates.subroutines.trotter import _recursive_expression from pennylane.transforms.core import TransformProgram from pennylane.typing import Result, ResultBatch, TensorLike from pennylane.wires import WireError has_quimb = True warnings.filterwarnings("ignore", message=".*kahypar") try: import quimb.tensor as qtn except (ModuleNotFoundError, ImportError) as import_error: # pragma: no cover has_quimb = False _operations = frozenset( { "Identity", "QubitUnitary", "ControlledQubitUnitary", "MultiControlledX", "DiagonalQubitUnitary", "PauliX", "PauliY", "PauliZ", "GlobalPhase", "Hadamard", "S", "T", "SX", "CNOT", "SWAP", "ISWAP", "PSWAP", "SISWAP", "SQISW", "CSWAP", "Toffoli", "CY", "CZ", "PhaseShift", "ControlledPhaseShift", "CPhase", "RX", "RY", "RZ", "Rot", "CRX", "CRY", "CRZ", "CRot", "IsingXX", "IsingYY", "IsingZZ", "IsingXY", "SingleExcitation", "SingleExcitationPlus", "SingleExcitationMinus", "DoubleExcitation", "QubitCarry", "QubitSum", "OrbitalRotation", "ECR", "BlockEncode", "PauliRot", "MultiRZ", "TrotterProduct", } ) # The set of supported operations. _observables = frozenset( { "PauliX", "PauliY", "PauliZ", "Hadamard", "Hermitian", "Identity", "Projector", "SparseHamiltonian", "Hamiltonian", "LinearCombination", "Sum", "SProd", "Prod", "Exp", } ) # The set of supported observables. _methods = frozenset({"mps", "tn"}) # The set of supported methods. # The following sets are used to determine if a gate contraction method is supported by the device. # These should be updated if `quimb` adds new options or changes the existing ones. _gate_contract_mps = frozenset({"auto-mps", "swap+split", "nonlocal"}) # The set of supported gate contraction methods for the MPS method. _gate_contract_tn = frozenset( {"auto-split-gate", "split-gate", "reduce-split", "swap-split-gate", "split", True, False} ) # The set of supported gate contraction methods for the TN method. _PAULI_MATRICES = { "I": qml.Identity(0).matrix(), "X": qml.PauliX(0).matrix(), "Y": qml.PauliY(0).matrix(), "Z": qml.PauliZ(0).matrix(), } def accepted_methods(method: str) -> bool: """A function that determines whether or not a method is supported by ``default.tensor``.""" return method in _methods def stopping_condition(op: qml.operation.Operator) -> bool: """A function that determines if an operation is supported by ``default.tensor``.""" return op.name in _operations def accepted_observables(obs: qml.operation.Operator) -> bool: """A function that determines if an observable is supported by ``default.tensor``.""" return obs.name in _observables def _accepted_gate_contract(contract: str, method: str) -> bool: """A function that determines if a gate contraction option is supported by the device.""" if method == "mps": return contract in _gate_contract_mps if method == "tn": return contract in _gate_contract_tn return False # pragma: no cover def _warn_unused_kwarg_tn(max_bond_dim: None, cutoff: None): """A function that warns the user about unused keyword arguments for the TN method.""" if max_bond_dim is not None: warnings.warn("The keyword argument 'max_bond_dim' is not used for the 'tn' method. ") if cutoff is not None: warnings.warn("The keyword argument 'cutoff' is not used for the 'tn' method. ") @simulator_tracking @single_tape_support class DefaultTensor(Device): """A PennyLane device to perform tensor network simulations of quantum circuits using `quimb <https://github.com/jcmgray/quimb/>`_. This device is designed to simulate large-scale quantum circuits using tensor networks. For small circuits, other devices like ``default.qubit`` may be more suitable. The backend uses the ``quimb`` library to perform the tensor network operations, and different methods can be used to simulate the quantum circuit. The supported methods are Matrix Product State (MPS) and Tensor Network (TN). This device does not currently support finite-shots or differentiation. At present, the supported measurement types are expectation values, variances and state measurements. Finally, ``UserWarnings`` from the ``cotengra`` package may appear when using this device. Args: wires (int, Iterable[Number, str]): Number of wires present on the device, or iterable that contains unique labels for the wires as numbers (e.g., ``[-1, 0, 2]``) or strings (e.g., ``['aux_wire', 'q1', 'q2']``). method (str): Supported method. The supported methods are ``"mps"`` (Matrix Product State) and ``"tn"`` (Tensor Network). c_dtype (type): Complex data type for the tensor representation. Must be one of ``numpy.complex64`` or ``numpy.complex128``. **kwargs: Keyword arguments for the device, passed to the ``quimb`` backend. Keyword Args: max_bond_dim (int): Maximum bond dimension for the MPS method. It corresponds to the maximum number of Schmidt coefficients (singular values) retained at the end of the SVD algorithm when applying gates. Default is ``None`` (i.e. unlimited). cutoff (float): Truncation threshold for the Schmidt coefficients in the MPS method. Default is ``None`` (which is equivalent to retaining all coefficients). contract (str): The contraction method for applying gates. The possible options depend on the method chosen. For the MPS method, the options are ``"auto-mps"``, ``"swap+split"`` and ``"nonlocal"``. For a description of these options, see the `quimb's CircuitMPS documentation <https://quimb.readthedocs.io/en/latest/autoapi/quimb/tensor/index.html#quimb.tensor.CircuitMPS>`_. Default is ``"auto-mps"``. For the TN method, the options are ``"auto-split-gate"``, ``"split-gate"``, ``"reduce-split"``, ``"swap-split-gate"``, ``"split"``, ``True``, and ``False``. For details, see the `quimb's tensor_core documentation <https://quimb.readthedocs.io/en/latest/autoapi/quimb/tensor/tensor_core/index.html#quimb.tensor.tensor_core.tensor_network_gate_inds>`_. Default is ``"auto-split-gate"``. contraction_optimizer (str): The contraction path optimizer to use for the computation of local expectation values. For more information on the optimizer options accepted by ``quimb``, see the `quimb's tensor_contract documentation <https://quimb.readthedocs.io/en/latest/autoapi/quimb/tensor/tensor_core/index.html#quimb.tensor.tensor_core.tensor_contract>`_. Default is ``"auto-hq"``. local_simplify (str): The simplification sequence to apply to the tensor network for computing local expectation values. For a complete list of available simplification options, see the `quimb's full_simplify documentation <https://quimb.readthedocs.io/en/latest/autoapi/quimb/tensor/tensor_core/index.html#quimb.tensor.tensor_core.TensorNetwork.full_simplify>`_. Default is ``"ADCRS"``. **Example:** The following code shows how to create a simple short-depth quantum circuit with 100 qubits using the ``default.tensor`` device. Depending on the machine, the execution time for this circuit is around 0.3 seconds: .. code-block:: python import pennylane as qml num_qubits = 100 dev = qml.device("default.tensor", wires=num_qubits) @qml.qnode(dev) def circuit(num_qubits): for qubit in range(0, num_qubits - 1): qml.CZ(wires=[qubit, qubit + 1]) qml.X(wires=[qubit]) qml.Z(wires=[qubit + 1]) return qml.expval(qml.Z(0)) >>> circuit(num_qubits) tensor(-1., requires_grad=True) We can provide additional keyword arguments to the device to customize the simulation. These are passed to the ``quimb`` backend. .. details:: :title: Usage with MPS Method In the following example, we consider a slightly more complex circuit. We use the ``default.tensor`` device with the MPS method, setting the maximum bond dimension to 100 and the cutoff to the machine epsilon. We set ``"auto-mps"`` as the contraction technique to apply gates. With this option, ``quimb`` turns 3-qubit gates and 4-qubit gates into Matrix Product Operators (MPO) and applies them directly to the MPS. On the other hand, qubits involved in 2-qubit gates may be temporarily swapped to adjacent positions before applying the gate and then returned to their original positions. .. code-block:: python import pennylane as qml import numpy as np theta = 0.5 phi = 0.1 num_qubits = 50 device_kwargs_mps = { "max_bond_dim": 100, "cutoff": np.finfo(np.complex128).eps, "contract": "auto-mps", } dev = qml.device("default.tensor", wires=num_qubits, method="mps", **device_kwargs_mps) @qml.qnode(dev) def circuit(theta, phi, num_qubits): for qubit in range(num_qubits - 4): qml.X(wires=qubit) qml.RX(theta, wires=qubit + 1) qml.CNOT(wires=[qubit, qubit + 1]) qml.DoubleExcitation(phi, wires=[qubit, qubit + 1, qubit + 3, qubit + 4]) qml.CSWAP(wires=[qubit + 1, qubit + 3, qubit + 4]) qml.RY(theta, wires=qubit + 1) qml.Toffoli(wires=[qubit + 1, qubit + 3, qubit + 4]) return [ qml.expval(qml.Z(0)), qml.expval(qml.Hamiltonian([np.pi, np.e], [qml.Z(15) @ qml.Y(25), qml.Hadamard(40)])), qml.var(qml.Y(20)), ] >>> circuit(theta, phi, num_qubits) [-0.9953099539219951, 0.0036631029671767208, 0.9999999876072984] After the first execution, the time to run this circuit for 50 qubits is around 0.5 seconds on a standard laptop. Increasing the number of qubits to 500 brings the execution time to approximately 15 seconds, and for 1000 qubits to around 50 seconds. The time complexity and the accuracy of the results also depend on the chosen keyword arguments for the device, such as the maximum bond dimension. The specific structure of the circuit significantly affects how the time complexity and accuracy of the simulation scale with these parameters. .. details:: :title: Usage with TN Method We can also simulate quantum circuits using the Tensor Network (TN) method. This can be particularly useful for circuits that build up entanglement. The following example shows how to execute a quantum circuit with the TN method and configurable depth using ``default.tensor``. We set the contraction technique to ``"auto-split-gate"``. With this option, each gate is lazily added to the tensor network and nothing is initially contracted, but the gate is automatically split if this results in a rank reduction. .. code-block:: python import pennylane as qml phi = 0.1 depth = 10 num_qubits = 100 dev = qml.device("default.tensor", method="tn", contract="auto-split-gate") @qml.qnode(dev) def circuit(phi, depth, num_qubits): for qubit in range(num_qubits): qml.X(wires=qubit) for _ in range(depth): for qubit in range(num_qubits - 1): qml.CNOT(wires=[qubit, qubit + 1]) for qubit in range(num_qubits): qml.RX(phi, wires=qubit) for qubit in range(num_qubits - 1): qml.CNOT(wires=[qubit, qubit + 1]) return qml.expval(qml.Z(0)) >>> circuit(phi, depth, num_qubits) -0.9511499466743283 The execution time for this circuit with the above parameters is around 0.8 seconds on a standard laptop. The tensor network method can be faster than MPS and state vector methods in some cases. As a comparison, the time for the exact calculation (i.e., with ``max_bond_dim = None``) of the same circuit using the ``MPS`` method of the ``default.tensor`` device is approximately three orders of magnitude slower. Similarly, using the ``default.qubit`` device results in a much slower simulation. """ # pylint: disable=too-many-instance-attributes _device_options = ( "contract", "contraction_optimizer", "cutoff", "c_dtype", "local_simplify", "max_bond_dim", "method", ) def __init__( self, wires=None, method="mps", c_dtype=np.complex128, **kwargs, ) -> None: if not has_quimb: raise ImportError( "This feature requires quimb, a library for tensor network manipulations. " "It can be installed with:\n\npip install quimb" ) # pragma: no cover if not accepted_methods(method): raise ValueError( f"Unsupported method: {method}. Supported methods are 'mps' (Matrix Product State) and 'tn' (Exact Tensor Network)." ) if c_dtype not in [np.complex64, np.complex128]: raise TypeError( f"Unsupported type: {c_dtype}. Supported types are numpy.complex64 and numpy.complex128." ) super().__init__(wires=wires, shots=None) self._method = method self._c_dtype = c_dtype # options for MPS self._max_bond_dim = kwargs.get("max_bond_dim", None) self._cutoff = kwargs.get("cutoff", None) # options both for MPS and TN self._local_simplify = kwargs.get("local_simplify", "ADCRS") self._contraction_optimizer = kwargs.get("contraction_optimizer", "auto-hq") self._contract = None if method == "mps": self._contract = kwargs.get("contract", "auto-mps") elif method == "tn": self._contract = kwargs.get("contract", "auto-split-gate") _warn_unused_kwarg_tn(self._max_bond_dim, self._cutoff) else: raise ValueError # pragma: no cover # The `quimb` circuit is a class attribute so that we can implement methods # that access it as soon as the device is created before running a circuit. self._quimb_circuit = self._initial_quimb_circuit(self.wires) for arg in kwargs: if arg not in self._device_options: raise TypeError( f"Unexpected argument: {arg} during initialization of the default.tensor device." ) @property def name(self) -> str: """The name of the device.""" return "default.tensor" @property def method(self) -> str: """Method used by the device.""" return self._method @property def c_dtype(self) -> type: """Tensor complex data type.""" return self._c_dtype def _initial_quimb_circuit( self, wires: qml.wires.Wires, psi0=None ) -> Union["qtn.CircuitMPS", "qtn.Circuit"]: """ Initialize the quimb circuit according to the method chosen. Internally, it uses ``quimb``'s ``CircuitMPS`` or ``Circuit`` class. Args: wires (Wires): The wires to initialize the quimb circuit. Returns: CircuitMPS or Circuit: The initial quimb instance of a circuit. """ if not _accepted_gate_contract(self._contract, self.method): raise ValueError( f"Unsupported gate contraction option: '{self._contract}' for '{self.method}' method. " "Please refer to the documentation for the supported options." ) if psi0 is None: psi0 = self._initial_mps(wires) if self.method == "mps": return qtn.CircuitMPS( psi0=psi0, max_bond=self._max_bond_dim, gate_contract=self._contract, cutoff=self._cutoff, ) if self.method == "tn": return qtn.Circuit( psi0=psi0.column_reduce(), gate_contract=self._contract, tags=[str(l) for l in wires.labels] if wires else None, ) raise NotImplementedError # pragma: no cover def _initial_mps(self, wires: qml.wires.Wires, basis_state=None) -> "qtn.MatrixProductState": r""" Return a MPS object in the :math:`\ket{0}` state. Internally, it uses ``quimb``'s ``MPS_computational_state`` method. Args: wires (Wires): The wires to initialize the MPS. basis_state (str, None): prepares the basis state :math:`\ket{n}`, where ``n`` is a string of integers from the set :math:`\{0, 1\}`, i.e., if ``n = "010"``, prepares the state :math:`|010\rangle`. Returns: MatrixProductState: The initial MPS of a circuit. """ if basis_state is None: basis_state = "0" * (len(wires) if wires else 1) return qtn.MPS_computational_state( binary=basis_state, dtype=self._c_dtype.__name__, tags=[str(l) for l in wires.labels] if wires else None, ) def draw(self, color="auto", **kwargs): """ Draw the current state (wavefunction) associated with the circuit using ``quimb``'s functionality. Internally, it uses ``quimb``'s ``draw`` method. Args: color (str): The color of the tensor network diagram. Default is ``"auto"``. **kwargs: Additional keyword arguments for the ``quimb``'s ``draw`` function. For more information, see the `quimb's draw documentation <https://quimb.readthedocs.io/en/latest/tensor-drawing.html>`_. **Example** Here is a minimal example of how to draw the current state of the circuit: .. code-block:: python import pennylane as qml dev = qml.device("default.tensor", method="mps", wires=15) dev.draw() We can also customize the appearance of the tensor network diagram by passing additional keyword arguments: .. code-block:: python dev = qml.device("default.tensor", method="tn", contract=False) @qml.qnode(dev) def circuit(num_qubits): for i in range(num_qubits): qml.Hadamard(wires=i) for _ in range(1, num_qubits - 1): for i in range(0, num_qubits, 2): qml.CNOT(wires=[i, i + 1]) for i in range(10): qml.RZ(1.234, wires=i) for i in range(1, num_qubits - 1, 2): qml.CZ(wires=[i, i + 1]) for i in range(num_qubits): qml.RX(1.234, wires=i) for i in range(num_qubits): qml.Hadamard(wires=i) return qml.expval(qml.Z(0)) num_qubits = 12 result = circuit(num_qubits) dev.draw(color="auto", show_inds=True) """ color = kwargs.pop("color", [f"I{w}" for w in range(len(self._quimb_circuit.psi.tensors))]) edge_color = kwargs.pop("edge_color", "black") show_tags = kwargs.pop("show_tags", False) show_inds = kwargs.pop("show_inds", False) return self._quimb_circuit.psi.draw( color=color, edge_color=edge_color, show_tags=show_tags, show_inds=show_inds, **kwargs, ) def _setup_execution_config( self, config: Optional[ExecutionConfig] = DefaultExecutionConfig ) -> ExecutionConfig: """ Update the execution config with choices for how the device should be used and the device options. """ # TODO: add options for gradients next quarter updated_values = {} new_device_options = dict(config.device_options) for option in self._device_options: if option not in new_device_options: new_device_options[option] = getattr(self, f"_{option}", None) return replace(config, **updated_values, device_options=new_device_options) def preprocess( self, execution_config: ExecutionConfig = DefaultExecutionConfig, ): """This function defines the device transform program to be applied and an updated device configuration. Args: execution_config (Union[ExecutionConfig, Sequence[ExecutionConfig]]): A data structure describing the parameters needed to fully describe the execution. Returns: TransformProgram, ExecutionConfig: A transform program that when called returns :class:`~.QuantumTape`'s that the device can natively execute as well as a postprocessing function to be called after execution, and a configuration with unset specifications filled in. This device currently: * Does not support finite shots. * Does not support derivatives. * Does not support vector-Jacobian products. """ config = self._setup_execution_config(execution_config) program = TransformProgram() program.add_transform(validate_measurements, name=self.name) program.add_transform(validate_observables, accepted_observables, name=self.name) program.add_transform(validate_device_wires, self._wires, name=self.name) program.add_transform( decompose, stopping_condition=stopping_condition, skip_initial_state_prep=True, name=self.name, ) program.add_transform(qml.transforms.broadcast_expand) return program, config def execute( self, circuits: QuantumScriptOrBatch, execution_config: ExecutionConfig = DefaultExecutionConfig, ) -> Union[Result, ResultBatch]: """Execute a circuit or a batch of circuits and turn it into results. Args: circuits (Union[QuantumTape, Sequence[QuantumTape]]): the quantum circuits to be executed. execution_config (ExecutionConfig): a data structure with additional information required for execution. Returns: TensorLike, tuple[TensorLike], tuple[tuple[TensorLike]]: A numeric result of the computation. """ results = [] for circuit in circuits: if self.wires is not None and not self.wires.contains_wires(circuit.wires): # quimb raises a cryptic error if the circuit has wires that are not in the device, # so we raise a more informative error here raise WireError( "Mismatch between circuit and device wires. " f"Circuit has wires {circuit.wires.tolist()}. " f"Tensor on device has wires {self.wires.tolist()}" ) circuit = circuit.map_to_standard_wires() results.append(self.simulate(circuit)) return tuple(results) def simulate(self, circuit: QuantumScript) -> Result: """Simulate a single quantum script. This function assumes that all operations provide matrices. Args: circuit (QuantumScript): The single circuit to simulate. Returns: Tuple[TensorLike]: The results of the simulation. """ # The state is reset every time a new circuit is executed, and number of wires # is established at runtime to match the circuit if not provided. wires = circuit.wires if self.wires is None else self.wires operations = copy.deepcopy(circuit.operations) if operations and isinstance(operations[0], qml.BasisState): op = operations.pop(0) self._quimb_circuit = self._initial_quimb_circuit( wires, psi0=self._initial_mps( op.wires, basis_state="".join( str(int(b)) for b in op.parameters[0].astype(self._c_dtype) ), ), ) elif operations and isinstance(operations[0], qml.StatePrep): op = operations.pop(0) self._quimb_circuit = self._initial_quimb_circuit( wires, psi0=qtn.MatrixProductState.from_dense( op.state_vector(wire_order=wires).astype(self._c_dtype) ), ) else: self._quimb_circuit = self._initial_quimb_circuit(wires) for op in operations: self._apply_operation(op) if not circuit.shots: if len(circuit.measurements) == 1: return self.measurement(circuit.measurements[0]) return tuple(self.measurement(mp) for mp in circuit.measurements) raise NotImplementedError # pragma: no cover def _apply_operation(self, op: qml.operation.Operator) -> None: """Apply a single operator to the circuit. Internally it uses ``quimb``'s ``apply_gate`` method. This method modifies the tensor state of the device. Args: op (Operator): The operation to apply. """ apply_operation_core(op, self) def measurement(self, measurementprocess: MeasurementProcess) -> TensorLike: """Measure the measurement required by the circuit. Args: measurementprocess (MeasurementProcess): measurement to apply to the state. Returns: TensorLike: the result of the measurement. """ return self._get_measurement_function(measurementprocess)(measurementprocess) def _get_measurement_function( self, measurementprocess: MeasurementProcess ) -> Callable[[MeasurementProcess, TensorLike], TensorLike]: """Get the appropriate method for performing a measurement. Args: measurementprocess (MeasurementProcess): measurement process to apply to the state. Returns: Callable: function that returns the measurement result. """ if isinstance(measurementprocess, StateMeasurement): if isinstance(measurementprocess, ExpectationMP): return self.expval if isinstance(measurementprocess, StateMP): return self.state if isinstance(measurementprocess, VarianceMP): return self.var raise NotImplementedError( f"Measurement process {measurementprocess} currently not supported by default.tensor." ) def expval(self, measurementprocess: MeasurementProcess) -> float: """Expectation value of the supplied observable contained in the MeasurementProcess. Args: measurementprocess (StateMeasurement): measurement to apply. Returns: Expectation value of the observable. """ obs = measurementprocess.obs return expval_core(obs, self) def state(self, measurementprocess: MeasurementProcess): # pylint: disable=unused-argument """Returns the state vector.""" return self._quimb_circuit.psi.to_dense().ravel() def var(self, measurementprocess: MeasurementProcess) -> float: """Variance of the supplied observable contained in the MeasurementProcess. Args: measurementprocess (StateMeasurement): measurement to apply. Returns: Variance of the observable. """ obs = measurementprocess.obs obs_mat = qml.matrix(obs) expect_op = self.expval(measurementprocess) expect_squar_op = self._local_expectation(obs_mat @ obs_mat.conj().T, tuple(obs.wires)) return expect_squar_op - np.square(expect_op) def _local_expectation(self, matrix, wires) -> float: """Compute the local expectation value of a matrix. Internally, it uses ``quimb``'s ``local_expectation`` method. Args: matrix (array): the matrix to compute the expectation value of. wires (tuple[int]): the wires the matrix acts on. Returns: Local expectation value of the matrix. """ # We need to copy the quimb circuit since `local_expectation` modifies it. # If there is only one measurement and we don't want to keep track of the state # after the execution, we could avoid copying the circuit. qc = self._quimb_circuit.copy() exp_val = qc.local_expectation( matrix, wires, dtype=self._c_dtype.__name__, optimize=self._contraction_optimizer, simplify_sequence=self._local_simplify, simplify_atol=0.0, ) return float(np.real(exp_val)) # pylint: disable=unused-argument def supports_derivatives( self, execution_config: Optional[ExecutionConfig] = None, circuit: Optional[qml.tape.QuantumTape] = None, ) -> bool: """Check whether or not derivatives are available for a given configuration and circuit. Args: execution_config (ExecutionConfig): The configuration of the desired derivative calculation. circuit (QuantumTape): An optional circuit to check derivatives support for. Returns: Bool: Whether or not a derivative can be calculated provided the given information. """ return False def compute_derivatives( self, circuits: QuantumScriptOrBatch, execution_config: ExecutionConfig = DefaultExecutionConfig, ): """Calculate the Jacobian of either a single or a batch of circuits on the device. Args: circuits (Union[QuantumTape, Sequence[QuantumTape]]): the circuits to calculate derivatives for. execution_config (ExecutionConfig): a data structure with all additional information required for execution. Returns: Tuple: The Jacobian for each trainable parameter. """ raise NotImplementedError( "The computation of derivatives has yet to be implemented for the default.tensor device." ) def execute_and_compute_derivatives( self, circuits: QuantumScriptOrBatch, execution_config: ExecutionConfig = DefaultExecutionConfig, ): """Compute the results and Jacobians of circuits at the same time. Args: circuits (Union[QuantumTape, Sequence[QuantumTape]]): the circuits or batch of circuits. execution_config (ExecutionConfig): a data structure with all additional information required for execution. Returns: tuple: A numeric result of the computation and the gradient. """ raise NotImplementedError( "The computation of derivatives has yet to be implemented for the default.tensor device." ) # pylint: disable=unused-argument def supports_vjp( self, execution_config: Optional[ExecutionConfig] = None, circuit: Optional[QuantumScript] = None, ) -> bool: """Whether or not this device defines a custom vector-Jacobian product. Args: execution_config (ExecutionConfig): The configuration of the desired derivative calculation. circuit (QuantumTape): An optional circuit to check derivatives support for. Returns: Bool: Whether or not a derivative can be calculated provided the given information. """ return False def compute_vjp( self, circuits: QuantumScriptOrBatch, cotangents: tuple[Number, ...], execution_config: ExecutionConfig = DefaultExecutionConfig, ): r"""The vector-Jacobian product used in reverse-mode differentiation. Args: circuits (Union[QuantumTape, Sequence[QuantumTape]]): the circuit or batch of circuits. cotangents (Tuple[Number, Tuple[Number]]): Gradient-output vector. Must have shape matching the output shape of the corresponding circuit. If the circuit has a single output, ``cotangents`` may be a single number, not an iterable of numbers. execution_config (ExecutionConfig): a data structure with all additional information required for execution. Returns: tensor-like: A numeric result of computing the vector-Jacobian product. """ raise NotImplementedError( "The computation of vector-Jacobian product has yet to be implemented for the default.tensor device." ) def execute_and_compute_vjp( self, circuits: QuantumScriptOrBatch, cotangents: tuple[Number, ...], execution_config: ExecutionConfig = DefaultExecutionConfig, ): """Calculate both the results and the vector-Jacobian product used in reverse-mode differentiation. Args: circuits (Union[QuantumTape, Sequence[QuantumTape]]): the circuit or batch of circuits to be executed. cotangents (Tuple[Number, Tuple[Number]]): Gradient-output vector. Must have shape matching the output shape of the corresponding circuit. execution_config (ExecutionConfig): a data structure with all additional information required for execution. Returns: Tuple, Tuple: the result of executing the scripts and the numeric result of computing the vector-Jacobian product. """ raise NotImplementedError( "The computation of vector-Jacobian product has yet to be implemented for the default.tensor device." ) @singledispatch def apply_operation_core(ops: Operation, device): """Dispatcher for _apply_operation.""" device._quimb_circuit.apply_gate( qml.matrix(ops).astype(device._c_dtype), *ops.wires, parametrize=None ) @apply_operation_core.register def apply_operation_core_multirz(ops: qml.MultiRZ, device): """Dispatcher for _apply_operation.""" apply_operation_core(qml.PauliRot(ops.parameters[0], "Z" * len(ops.wires), ops.wires), device) @apply_operation_core.register def apply_operation_core_paulirot(ops: qml.PauliRot, device): """Dispatcher for _apply_operation.""" theta = ops.parameters[0] pauli_string = ops._hyperparameters["pauli_word"] arrays = [] sites = list(ops.wires) for i, P in enumerate(pauli_string): if i == 0: arr = qml.math.zeros((1, 2, 2, 2), dtype=complex) arr[0, 0] = _PAULI_MATRICES[P] arr[0, 1] = qml.math.eye(2, dtype=complex) elif i == len(sites) - 1: arr = qml.math.zeros((2, 1, 2, 2), dtype=complex) arr[0, 0] = _PAULI_MATRICES[P] * (-1j) * qml.math.sin(theta / 2) arr[1, 0] = qml.math.eye(2, dtype=complex) * qml.math.cos(theta / 2) else: arr = qml.math.zeros((2, 2, 2, 2), dtype=complex) arr[0, 0] = _PAULI_MATRICES[P] arr[1, 1] = qml.math.eye(2, dtype=complex) arrays.append(arr) mpo = qtn.MatrixProductOperator(arrays=arrays, sites=sites) mpo = mpo.fill_empty_sites() device._quimb_circuit._psi = mpo.apply( device._quimb_circuit.psi, max_bond=device._max_bond_dim, cutoff=device._cutoff, ) @apply_operation_core.register def apply_operation_core_trotter_product(ops: qml.TrotterProduct, device): """Dispatcher for _apply_operation.""" time = ops.data[-1] n = ops._hyperparameters["n"] order = ops._hyperparameters["order"] ops = ops._hyperparameters["base"].operands decomp = _recursive_expression(time / n, order, ops)[::-1] * n for o in decomp: device._quimb_circuit.apply_gate( qml.matrix(o).astype(device._c_dtype), *o.wires, parametrize=None ) @singledispatch def expval_core(obs: Observable, device) -> float: """Dispatcher for expval.""" return device._local_expectation(qml.matrix(obs), tuple(obs.wires)) @expval_core.register def expval_core_tensor(obs: Tensor, device) -> float: """Computes the expval of a Tensor.""" return expval_core(Prod(*obs._args), device) @expval_core.register def expval_core_prod(obs: Prod, device) -> float: """Computes the expval of a Prod.""" ket = device._quimb_circuit.copy() for op in obs: ket.apply_gate(qml.matrix(op).astype(device._c_dtype), *op.wires, parametrize=None) return np.real((device._quimb_circuit.psi.H & ket.psi).contract(all, output_inds=())) @expval_core.register def expval_core_sprod(obs: SProd, device) -> float: """Computes the expval of a SProd.""" return obs.scalar * expval_core(obs.base, device) @expval_core.register def expval_core_sum(obs: Sum, device) -> float: """Computes the expval of a Sum.""" return sum(expval_core(m, device) for m in obs) @expval_core.register def expval_core_linear_combination(obs: LinearCombination, device) -> float: """Computes the expval of a LinearCombination.""" return sum(expval_core(m, device) for m in obs)
pennylane/pennylane/devices/default_tensor.py/0
{ "file_path": "pennylane/pennylane/devices/default_tensor.py", "repo_id": "pennylane", "token_count": 16709 }
51
# Copyright 2018-2023 Xanadu Quantum Technologies Inc. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Functions to sample a state.""" from typing import Union import numpy as np import pennylane as qml from pennylane.measurements import ( ClassicalShadowMP, CountsMP, ExpectationMP, SampleMeasurement, ShadowExpvalMP, Shots, ) from pennylane.ops import Hamiltonian, LinearCombination, Prod, SProd, Sum from pennylane.typing import TensorLike from .apply_operation import apply_operation from .measure import flatten_state def jax_random_split(prng_key, num: int = 2): """Get a new key with ``jax.random.split``.""" if prng_key is None: return (None,) * num # pylint: disable=import-outside-toplevel from jax.random import split return split(prng_key, num=num) def _group_measurements(mps: list[Union[SampleMeasurement, ClassicalShadowMP, ShadowExpvalMP]]): """ Group the measurements such that: - measurements with pauli observables pairwise-commute in each group - measurements with observables that are not pauli words are all in different groups - measurements without observables are all in the same group - classical shadow measurements are all in different groups """ if len(mps) == 1: return [mps], [[0]] # measurements with pauli-word observables mp_pauli_obs = [] # measurements with non pauli-word observables mp_other_obs = [] mp_other_obs_indices = [] # measurements with no observables mp_no_obs = [] mp_no_obs_indices = [] for i, mp in enumerate(mps): if isinstance(mp.obs, (Sum, SProd, Prod)): mps[i].obs = qml.simplify(mp.obs) if isinstance(mp, (ClassicalShadowMP, ShadowExpvalMP)): mp_other_obs.append([mp]) mp_other_obs_indices.append([i]) elif mp.obs is None: mp_no_obs.append(mp) mp_no_obs_indices.append(i) elif qml.pauli.is_pauli_word(mp.obs): mp_pauli_obs.append((i, mp)) else: mp_other_obs.append([mp]) mp_other_obs_indices.append([i]) if mp_pauli_obs: i_to_pauli_mp = dict(mp_pauli_obs) _, group_indices = qml.pauli.group_observables( [mp.obs for mp in i_to_pauli_mp.values()], list(i_to_pauli_mp.keys()) ) mp_pauli_groups = [] for indices in group_indices: mp_group = [i_to_pauli_mp[i] for i in indices] mp_pauli_groups.append(mp_group) else: mp_pauli_groups, group_indices = [], [] mp_no_obs_indices = [mp_no_obs_indices] if mp_no_obs else [] mp_no_obs = [mp_no_obs] if mp_no_obs else [] all_mp_groups = mp_pauli_groups + mp_no_obs + mp_other_obs all_indices = group_indices + mp_no_obs_indices + mp_other_obs_indices return all_mp_groups, all_indices def _get_num_executions_for_expval_H(obs): indices = obs.grouping_indices if indices: return len(indices) return _get_num_wire_groups_for_expval_H(obs) def _get_num_wire_groups_for_expval_H(obs): _, obs_list = obs.terms() wires_list = [] added_obs = [] num_groups = 0 for o in obs_list: if o in added_obs: continue if isinstance(o, qml.Identity): continue added = False for wires in wires_list: if len(qml.wires.Wires.shared_wires([wires, o.wires])) == 0: added_obs.append(o) added = True break if not added: added_obs.append(o) wires_list.append(o.wires) num_groups += 1 return num_groups def _get_num_executions_for_sum(obs): if obs.grouping_indices: return len(obs.grouping_indices) if not obs.pauli_rep: return sum(int(not isinstance(o, qml.Identity)) for o in obs.terms()[1]) _, ops = obs.terms() with qml.QueuingManager.stop_recording(): op_groups = qml.pauli.group_observables(ops) return len(op_groups) # pylint: disable=no-member def get_num_shots_and_executions(tape: qml.tape.QuantumScript) -> tuple[int, int]: """Get the total number of qpu executions and shots. Args: tape (qml.tape.QuantumTape): the tape we want to get the number of executions and shots for Returns: int, int: the total number of QPU executions and the total number of shots """ groups, _ = _group_measurements(tape.measurements) num_executions = 0 num_shots = 0 for group in groups: if isinstance(group[0], ExpectationMP) and isinstance( group[0].obs, (qml.ops.Hamiltonian, qml.ops.LinearCombination) ): H_executions = _get_num_executions_for_expval_H(group[0].obs) num_executions += H_executions if tape.shots: num_shots += tape.shots.total_shots * H_executions elif isinstance(group[0], ExpectationMP) and isinstance(group[0].obs, qml.ops.Sum): sum_executions = _get_num_executions_for_sum(group[0].obs) num_executions += sum_executions if tape.shots: num_shots += tape.shots.total_shots * sum_executions elif isinstance(group[0], (ClassicalShadowMP, ShadowExpvalMP)): num_executions += tape.shots.total_shots if tape.shots: num_shots += tape.shots.total_shots else: num_executions += 1 if tape.shots: num_shots += tape.shots.total_shots if tape.batch_size: num_executions *= tape.batch_size if tape.shots: num_shots *= tape.batch_size return num_executions, num_shots def _apply_diagonalizing_gates( mps: list[SampleMeasurement], state: np.ndarray, is_state_batched: bool = False ): if len(mps) == 1: diagonalizing_gates = mps[0].diagonalizing_gates() elif all(mp.obs for mp in mps): diagonalizing_gates = qml.pauli.diagonalize_qwc_pauli_words([mp.obs for mp in mps])[0] else: diagonalizing_gates = [] for op in diagonalizing_gates: state = apply_operation(op, state, is_state_batched=is_state_batched) return state # pylint:disable = too-many-arguments def measure_with_samples( measurements: list[Union[SampleMeasurement, ClassicalShadowMP, ShadowExpvalMP]], state: np.ndarray, shots: Shots, is_state_batched: bool = False, rng=None, prng_key=None, mid_measurements: dict = None, ) -> list[TensorLike]: """ Returns the samples of the measurement process performed on the given state. This function assumes that the user-defined wire labels in the measurement process have already been mapped to integer wires used in the device. Args: measurements (List[Union[SampleMeasurement, ClassicalShadowMP, ShadowExpvalMP]]): The sample measurements to perform state (np.ndarray[complex]): The state vector to sample from shots (Shots): The number of samples to take is_state_batched (bool): whether the state is batched or not rng (Union[None, int, array_like[int], SeedSequence, BitGenerator, Generator]): A seed-like parameter matching that of ``seed`` for ``numpy.random.default_rng``. If no value is provided, a default RNG will be used. prng_key (Optional[jax.random.PRNGKey]): An optional ``jax.random.PRNGKey``. This is the key to the JAX pseudo random number generator. Only for simulation using JAX. mid_measurements (None, dict): Dictionary of mid-circuit measurements Returns: List[TensorLike[Any]]: Sample measurement results """ # last N measurements are sampling MCMs in ``dynamic_one_shot`` execution mode mps = measurements[0 : -len(mid_measurements)] if mid_measurements else measurements groups, indices = _group_measurements(mps) all_res = [] for group in groups: if isinstance(group[0], ExpectationMP) and isinstance( group[0].obs, (Hamiltonian, LinearCombination) ): measure_fn = _measure_hamiltonian_with_samples elif isinstance(group[0], ExpectationMP) and isinstance(group[0].obs, Sum): measure_fn = _measure_sum_with_samples elif isinstance(group[0], (ClassicalShadowMP, ShadowExpvalMP)): measure_fn = _measure_classical_shadow else: # measure with the usual method (rotate into the measurement basis) measure_fn = _measure_with_samples_diagonalizing_gates prng_key, key = jax_random_split(prng_key) all_res.extend( measure_fn( group, state, shots, is_state_batched=is_state_batched, rng=rng, prng_key=key ) ) flat_indices = [_i for i in indices for _i in i] # reorder results sorted_res = tuple( res for _, res in sorted(list(enumerate(all_res)), key=lambda r: flat_indices[r[0]]) ) # append MCM samples if mid_measurements: sorted_res += tuple(mid_measurements.values()) # put the shot vector axis before the measurement axis if shots.has_partitioned_shots: sorted_res = tuple(zip(*sorted_res)) return sorted_res def _measure_with_samples_diagonalizing_gates( mps: list[SampleMeasurement], state: np.ndarray, shots: Shots, is_state_batched: bool = False, rng=None, prng_key=None, ) -> TensorLike: """ Returns the samples of the measurement process performed on the given state, by rotating the state into the measurement basis using the diagonalizing gates given by the measurement process. Args: mp (~.measurements.SampleMeasurement): The sample measurement to perform state (np.ndarray[complex]): The state vector to sample from shots (~.measurements.Shots): The number of samples to take is_state_batched (bool): whether the state is batched or not rng (Union[None, int, array_like[int], SeedSequence, BitGenerator, Generator]): A seed-like parameter matching that of ``seed`` for ``numpy.random.default_rng``. If no value is provided, a default RNG will be used. prng_key (Optional[jax.random.PRNGKey]): An optional ``jax.random.PRNGKey``. This is the key to the JAX pseudo random number generator. Only for simulation using JAX. Returns: TensorLike[Any]: Sample measurement results """ # apply diagonalizing gates state = _apply_diagonalizing_gates(mps, state, is_state_batched) total_indices = len(state.shape) - is_state_batched wires = qml.wires.Wires(range(total_indices)) def _process_single_shot(samples): processed = [] for mp in mps: res = mp.process_samples(samples, wires) if not isinstance(mp, CountsMP): res = qml.math.squeeze(res) processed.append(res) return tuple(processed) try: prng_key, _ = jax_random_split(prng_key) samples = sample_state( state, shots=shots.total_shots, is_state_batched=is_state_batched, wires=wires, rng=rng, prng_key=prng_key, ) except ValueError as e: if str(e) != "probabilities contain NaN": raise e samples = qml.math.full((shots.total_shots, len(wires)), 0) processed_samples = [] for lower, upper in shots.bins(): shot = _process_single_shot(samples[..., lower:upper, :]) processed_samples.append(shot) if shots.has_partitioned_shots: return tuple(zip(*processed_samples)) return processed_samples[0] def _measure_classical_shadow( mp: list[Union[ClassicalShadowMP, ShadowExpvalMP]], state: np.ndarray, shots: Shots, is_state_batched: bool = False, rng=None, prng_key=None, ): """ Returns the result of a classical shadow measurement on the given state. A classical shadow measurement doesn't fit neatly into the current measurement API since different diagonalizing gates are used for each shot. Here it's treated as a state measurement with shots instead of a sample measurement. Args: mp (~.measurements.SampleMeasurement): The sample measurement to perform state (np.ndarray[complex]): The state vector to sample from shots (~.measurements.Shots): The number of samples to take rng (Union[None, int, array_like[int], SeedSequence, BitGenerator, Generator]): A seed-like parameter matching that of ``seed`` for ``numpy.random.default_rng``. If no value is provided, a default RNG will be used. Returns: TensorLike[Any]: Sample measurement results """ # pylint: disable=unused-argument # the list contains only one element based on how we group measurements mp = mp[0] wires = qml.wires.Wires(range(len(state.shape))) if shots.has_partitioned_shots: return [tuple(mp.process_state_with_shots(state, wires, s, rng=rng) for s in shots)] return [mp.process_state_with_shots(state, wires, shots.total_shots, rng=rng)] def _measure_hamiltonian_with_samples( mp: list[SampleMeasurement], state: np.ndarray, shots: Shots, is_state_batched: bool = False, rng=None, prng_key=None, ): # the list contains only one element based on how we group measurements mp = mp[0] # if the measurement process involves a Hamiltonian, measure each # of the terms separately and sum def _sum_for_single_shot(s, prng_key=None): results = measure_with_samples( [ExpectationMP(t) for t in mp.obs.terms()[1]], state, s, is_state_batched=is_state_batched, rng=rng, prng_key=prng_key, ) return sum(c * res for c, res in zip(mp.obs.terms()[0], results)) keys = jax_random_split(prng_key, num=shots.num_copies) unsqueezed_results = tuple( _sum_for_single_shot(type(shots)(s), key) for s, key in zip(shots, keys) ) return [unsqueezed_results] if shots.has_partitioned_shots else [unsqueezed_results[0]] def _measure_sum_with_samples( mp: list[SampleMeasurement], state: np.ndarray, shots: Shots, is_state_batched: bool = False, rng=None, prng_key=None, ): # the list contains only one element based on how we group measurements mp = mp[0] # if the measurement process involves a Sum, measure each # of the terms separately and sum def _sum_for_single_shot(s, prng_key=None): results = measure_with_samples( [ExpectationMP(t) for t in mp.obs], state, s, is_state_batched=is_state_batched, rng=rng, prng_key=prng_key, ) return sum(results) keys = jax_random_split(prng_key, num=shots.num_copies) unsqueezed_results = tuple( _sum_for_single_shot(type(shots)(s), key) for s, key in zip(shots, keys) ) return [unsqueezed_results] if shots.has_partitioned_shots else [unsqueezed_results[0]] def sample_state( state, shots: int, is_state_batched: bool = False, wires=None, rng=None, prng_key=None, ) -> np.ndarray: """ Returns a series of samples of a state. Args: state (array[complex]): A state vector to be sampled shots (int): The number of samples to take is_state_batched (bool): whether the state is batched or not wires (Sequence[int]): The wires to sample rng (Union[None, int, array_like[int], SeedSequence, BitGenerator, Generator]): A seed-like parameter matching that of ``seed`` for ``numpy.random.default_rng``. If no value is provided, a default RNG will be used prng_key (Optional[jax.random.PRNGKey]): An optional ``jax.random.PRNGKey``. This is the key to the JAX pseudo random number generator. Only for simulation using JAX. Returns: ndarray[int]: Sample values of the shape (shots, num_wires) """ if prng_key is not None: return _sample_state_jax( state, shots, prng_key, is_state_batched=is_state_batched, wires=wires ) rng = np.random.default_rng(rng) total_indices = len(state.shape) - is_state_batched state_wires = qml.wires.Wires(range(total_indices)) wires_to_sample = wires or state_wires num_wires = len(wires_to_sample) basis_states = np.arange(2**num_wires) flat_state = flatten_state(state, total_indices) with qml.queuing.QueuingManager.stop_recording(): probs = qml.probs(wires=wires_to_sample).process_state(flat_state, state_wires) # when using the torch interface with float32 as default dtype, # probabilities must be renormalized as they may not sum to one # see https://github.com/PennyLaneAI/pennylane/issues/5444 norm = qml.math.sum(probs, axis=-1) abs_diff = qml.math.abs(norm - 1.0) cutoff = 1e-07 if is_state_batched: normalize_condition = False for s in abs_diff: if s != 0: normalize_condition = True if s > cutoff: normalize_condition = False break if normalize_condition: probs = probs / norm[:, np.newaxis] if norm.shape else probs / norm # rng.choice doesn't support broadcasting samples = np.stack([rng.choice(basis_states, shots, p=p) for p in probs]) else: if not 0 < abs_diff < cutoff: norm = 1.0 probs = probs / norm samples = rng.choice(basis_states, shots, p=probs) powers_of_two = 1 << np.arange(num_wires, dtype=np.int64)[::-1] states_sampled_base_ten = samples[..., None] & powers_of_two return (states_sampled_base_ten > 0).astype(np.int64) # pylint:disable = unused-argument def _sample_state_jax( state, shots: int, prng_key, is_state_batched: bool = False, wires=None, ) -> np.ndarray: """ Returns a series of samples of a state for the JAX interface based on the PRNG. Args: state (array[complex]): A state vector to be sampled shots (int): The number of samples to take prng_key (jax.random.PRNGKey): A``jax.random.PRNGKey``. This is the key to the JAX pseudo random number generator. is_state_batched (bool): whether the state is batched or not wires (Sequence[int]): The wires to sample Returns: ndarray[int]: Sample values of the shape (shots, num_wires) """ # pylint: disable=import-outside-toplevel import jax import jax.numpy as jnp key = prng_key total_indices = len(state.shape) - is_state_batched state_wires = qml.wires.Wires(range(total_indices)) wires_to_sample = wires or state_wires num_wires = len(wires_to_sample) basis_states = np.arange(2**num_wires) flat_state = flatten_state(state, total_indices) with qml.queuing.QueuingManager.stop_recording(): probs = qml.probs(wires=wires_to_sample).process_state(flat_state, state_wires) if is_state_batched: keys = jax_random_split(prng_key, num=len(state)) samples = jnp.array( [ jax.random.choice(_key, basis_states, shape=(shots,), p=prob) for _key, prob in zip(keys, probs) ] ) else: _, key = jax_random_split(prng_key) samples = jax.random.choice(key, basis_states, shape=(shots,), p=probs) powers_of_two = 1 << np.arange(num_wires, dtype=np.int64)[::-1] states_sampled_base_ten = samples[..., None] & powers_of_two return (states_sampled_base_ten > 0).astype(np.int64)
pennylane/pennylane/devices/qubit/sampling.py/0
{ "file_path": "pennylane/pennylane/devices/qubit/sampling.py", "repo_id": "pennylane", "token_count": 8572 }
52
# Copyright 2024 Xanadu Quantum Technologies Inc. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests trainable circuits using the JAX interface.""" import numpy as np # pylint:disable=no-self-use import pytest import pennylane as qml jax = pytest.importorskip("jax") jnp = pytest.importorskip("jax.numpy") @pytest.mark.usefixtures("validate_diff_method") @pytest.mark.parametrize("diff_method", ["backprop", "parameter-shift", "hadamard"]) class TestGradients: """Test various gradient computations.""" def test_basic_grad(self, diff_method, device, tol): """Test a basic function with one RX and one expectation.""" wires = 2 if diff_method == "hadamard" else 1 dev = device(wires=wires) tol = tol(dev.shots) if diff_method == "hadamard": tol += 0.01 @qml.qnode(dev, diff_method=diff_method) def circuit(x): qml.RX(x, 0) return qml.expval(qml.Z(0)) x = jnp.array(0.5) res = jax.grad(circuit)(x) assert np.isclose(res, -jnp.sin(x), atol=tol, rtol=0) def test_backprop_state(self, diff_method, device, tol): """Test the trainability of parameters in a circuit returning the state.""" if diff_method != "backprop": pytest.skip(reason="test only works with backprop") dev = device(2) if dev.shots: pytest.skip("test uses backprop, must be in analytic mode") if "mixed" in dev.name: pytest.skip("mixed-state simulator will wrongly use grad on non-scalar results") tol = tol(dev.shots) x = jnp.array(0.543) y = jnp.array(-0.654) @qml.qnode(dev, diff_method="backprop", grad_on_execution=True) def circuit(x, y): qml.RX(x, wires=[0]) qml.RY(y, wires=[1]) qml.CNOT(wires=[0, 1]) return qml.state() def cost_fn(x, y): res = circuit(x, y) probs = jnp.abs(res) ** 2 return probs[0] + probs[2] res = jax.grad(cost_fn, argnums=[0, 1])(x, y) expected = np.array([-np.sin(x) * np.cos(y) / 2, -np.cos(x) * np.sin(y) / 2]) assert np.allclose(res, expected, atol=tol, rtol=0) res = jax.grad(cost_fn, argnums=[0])(x, y) assert np.allclose(res, expected[0], atol=tol, rtol=0) def test_parameter_shift(self, diff_method, device, tol): """Test a multi-parameter circuit with parameter-shift.""" if diff_method != "parameter-shift": pytest.skip(reason="test only works with parameter-shift") a = jnp.array(0.1) b = jnp.array(0.2) dev = device(2) tol = tol(dev.shots) @qml.qnode(dev, diff_method="parameter-shift", grad_on_execution=False) def circuit(a, b): qml.RY(a, wires=0) qml.RX(b, wires=1) qml.CNOT(wires=[0, 1]) return qml.expval(qml.Hamiltonian([1, 1], [qml.Z(0), qml.Y(1)])) res = jax.grad(circuit, argnums=[0, 1])(a, b) expected = [-np.sin(a) + np.sin(a) * np.sin(b), -np.cos(a) * np.cos(b)] assert np.allclose(res, expected, atol=tol, rtol=0) # make the second QNode argument a constant res = jax.grad(circuit, argnums=[0])(a, b) assert np.allclose(res, expected[0], atol=tol, rtol=0) def test_probs(self, diff_method, device, tol): """Test differentiation of a circuit returning probs().""" wires = 3 if diff_method == "hadamard" else 2 dev = device(wires=wires) tol = tol(dev.shots) x = jnp.array(0.543) y = jnp.array(-0.654) @qml.qnode(dev, diff_method=diff_method) def circuit(x, y): qml.RX(x, wires=[0]) qml.RY(y, wires=[1]) qml.CNOT(wires=[0, 1]) return qml.probs(wires=[1]) res = jax.jacobian(circuit, argnums=[0, 1])(x, y) expected = np.array( [ [-np.sin(x) * np.cos(y) / 2, -np.cos(x) * np.sin(y) / 2], [np.cos(y) * np.sin(x) / 2, np.cos(x) * np.sin(y) / 2], ] ) assert isinstance(res, tuple) assert len(res) == 2 assert isinstance(res[0], jnp.ndarray) assert res[0].shape == (2,) assert isinstance(res[1], jnp.ndarray) assert res[1].shape == (2,) if diff_method == "hadamard" and "raket" in dev.name: pytest.xfail(reason="braket gets wrong results for hadamard here") assert np.allclose(res[0], expected.T[0], atol=tol, rtol=0) assert np.allclose(res[1], expected.T[1], atol=tol, rtol=0) def test_multi_meas(self, diff_method, device, tol): """Test differentiation of a circuit with both scalar and array-like returns.""" wires = 3 if diff_method == "hadamard" else 2 dev = device(wires=wires) tol = tol(dev.shots) x = jnp.array(0.543) y = jnp.array(-0.654) @qml.qnode(dev, diff_method=diff_method) def circuit(x, y): qml.RX(x, wires=[0]) qml.RY(y, wires=[1]) qml.CNOT(wires=[0, 1]) return qml.expval(qml.Z(0)), qml.probs(wires=[1]) jac = jax.jacobian(circuit, argnums=[0])(x, y) expected = [ [-np.sin(x), 0], [ [-np.sin(x) * np.cos(y) / 2, np.cos(y) * np.sin(x) / 2], [-np.cos(x) * np.sin(y) / 2, np.cos(x) * np.sin(y) / 2], ], ] assert isinstance(jac, tuple) assert len(jac) == 2 assert isinstance(jac[0], tuple) assert len(jac[0]) == 1 assert isinstance(jac[0][0], jnp.ndarray) assert jac[0][0].shape == () assert np.allclose(jac[0][0], expected[0][0], atol=tol, rtol=0) assert isinstance(jac[1], tuple) assert len(jac[1]) == 1 assert isinstance(jac[1][0], jnp.ndarray) assert jac[1][0].shape == (2,) assert np.allclose(jac[1][0], expected[1][0], atol=tol, rtol=0) def test_hessian(self, diff_method, device, tol): """Test hessian computation.""" wires = 3 if diff_method == "hadamard" else 1 dev = device(wires=wires) tol = tol(dev.shots) @qml.qnode(dev, diff_method=diff_method, max_diff=2) def circuit(x): qml.RY(x[0], wires=0) qml.RX(x[1], wires=0) return qml.expval(qml.Z(0)) x = jnp.array([1.0, 2.0]) res = circuit(x) a, b = x expected_res = np.cos(a) * np.cos(b) assert np.allclose(res, expected_res, atol=tol, rtol=0) grad_fn = jax.grad(circuit) g = grad_fn(x) expected_g = [-np.sin(a) * np.cos(b), -np.cos(a) * np.sin(b)] assert np.allclose(g, expected_g, atol=tol, rtol=0) hess = jax.jacobian(grad_fn)(x) expected_hess = [ [-np.cos(a) * np.cos(b), np.sin(a) * np.sin(b)], [np.sin(a) * np.sin(b), -np.cos(a) * np.cos(b)], ] assert np.allclose(hess, expected_hess, atol=tol, rtol=0)
pennylane/pennylane/devices/tests/test_gradients_jax.py/0
{ "file_path": "pennylane/pennylane/devices/tests/test_gradients_jax.py", "repo_id": "pennylane", "token_count": 3805 }
53
# Copyright 2018-2021 Xanadu Quantum Technologies Inc. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ This module contains logic for the text based circuit drawer through the ``tape_text`` function. """ # TODO: Fix the latter two pylint warnings # pylint: disable=too-many-arguments, too-many-branches, too-many-statements from dataclasses import dataclass from typing import Optional import pennylane as qml from pennylane.measurements import ( Counts, Expectation, MidMeasureMP, Probability, Sample, State, Variance, ) from .drawable_layers import drawable_layers from .utils import ( convert_wire_order, cwire_connections, default_bit_map, transform_deferred_measurements_tape, unwrap_controls, ) @dataclass class _Config: """Dataclass containing attributes needed for updating the strings to be drawn for each layer""" wire_map: dict """Map between wire labels and their place in order""" bit_map: dict """Map between mid-circuit measurements and their corresponding bit in order""" cur_layer: Optional[int] = None """Current layer index that is being updated""" cwire_layers: Optional[list] = None """A list of layers used (mid measure or conditional) for each classical wire.""" decimals: Optional[int] = None """Specifies how to round the parameters of operators""" cache: Optional[dict] = None """dictionary that carries information between label calls in the same drawing""" def _add_grouping_symbols(op, layer_str, config): # pylint: disable=unused-argument """Adds symbols indicating the extent of a given object.""" if len(op.wires) > 1: mapped_wires = [config.wire_map[w] for w in op.wires] min_w, max_w = min(mapped_wires), max(mapped_wires) layer_str[min_w] = "╭" layer_str[max_w] = "╰" for w in range(min_w + 1, max_w): layer_str[w] = "├" if w in mapped_wires else "│" return layer_str def _add_cond_grouping_symbols(op, layer_str, config): """Adds symbols indicating the extent of a given object for conditional operators""" n_wires = len(config.wire_map) mapped_wires = [config.wire_map[w] for w in op.wires] mapped_bits = [config.bit_map[m] for m in op.meas_val.measurements] max_w = max(mapped_wires) max_b = max(mapped_bits) + n_wires ctrl_symbol = "╩" if config.cur_layer != config.cwire_layers[max(mapped_bits)][-1] else "╝" layer_str[max_b] = f"═{ctrl_symbol}" for w in range(max_w + 1, max(config.wire_map.values()) + 1): layer_str[w] = "─║" for b in range(n_wires, max_b): if b - n_wires in mapped_bits: intersection = "╣" if config.cur_layer == config.cwire_layers[b - n_wires][-1] else "╬" layer_str[b] = f"═{intersection}" else: filler = " " if layer_str[b][-1] == " " else "═" layer_str[b] = f"{filler}║" return layer_str def _add_mid_measure_grouping_symbols(op, layer_str, config): """Adds symbols indicating the extent of a given object for mid-measure operators""" if op not in config.bit_map: return layer_str n_wires = len(config.wire_map) mapped_wire = config.wire_map[op.wires[0]] bit = config.bit_map[op] + n_wires layer_str[bit] += " ╚" for w in range(mapped_wire + 1, n_wires): layer_str[w] += "─║" for b in range(n_wires, bit): filler = " " if layer_str[b][-1] == " " else "═" layer_str[b] += f"{filler}║" return layer_str def _add_op(op, layer_str, config): """Updates ``layer_str`` with ``op`` operation.""" if isinstance(op, qml.ops.Conditional): # pylint: disable=no-member layer_str = _add_cond_grouping_symbols(op, layer_str, config) return _add_op(op.base, layer_str, config) if isinstance(op, MidMeasureMP): return _add_mid_measure_op(op, layer_str, config) layer_str = _add_grouping_symbols(op, layer_str, config) control_wires, control_values = unwrap_controls(op) if control_values: for w, val in zip(control_wires, control_values): layer_str[config.wire_map[w]] += "●" if val else "○" else: for w in control_wires: layer_str[config.wire_map[w]] += "●" label = op.label(decimals=config.decimals, cache=config.cache).replace("\n", "") if len(op.wires) == 0: # operation (e.g. barrier, snapshot) across all wires n_wires = len(config.wire_map) for i, s in enumerate(layer_str[:n_wires]): layer_str[i] = s + label else: for w in op.wires: if w not in control_wires: layer_str[config.wire_map[w]] += label return layer_str def _add_mid_measure_op(op, layer_str, config): """Updates ``layer_str`` with ``op`` operation when ``op`` is a ``qml.measurements.MidMeasureMP``.""" layer_str = _add_mid_measure_grouping_symbols(op, layer_str, config) label = op.label(decimals=config.decimals, cache=config.cache).replace("\n", "") for w in op.wires: layer_str[config.wire_map[w]] += label return layer_str measurement_label_map = { Expectation: lambda label: f"<{label}>", Probability: lambda label: f"Probs[{label}]" if label else "Probs", Sample: lambda label: f"Sample[{label}]" if label else "Sample", Counts: lambda label: f"Counts[{label}]" if label else "Counts", Variance: lambda label: f"Var[{label}]", State: lambda label: "State", } def _add_cwire_measurement_grouping_symbols(mcms, layer_str, config): """Adds symbols indicating the extent of a given object for mid-circuit measurement statistics.""" if len(mcms) > 1: n_wires = len(config.wire_map) mapped_bits = [config.bit_map[m] for m in mcms] min_b, max_b = min(mapped_bits) + n_wires, max(mapped_bits) + n_wires layer_str[min_b] = "╭" layer_str[max_b] = "╰" for b in range(min_b + 1, max_b): layer_str[b] = "├" if b - n_wires in mapped_bits else "│" return layer_str def _add_cwire_measurement(m, layer_str, config): """Updates ``layer_str`` with the ``m`` measurement when it is used for collecting mid-circuit measurement statistics.""" mcms = [v.measurements[0] for v in m.mv] if isinstance(m.mv, list) else m.mv.measurements layer_str = _add_cwire_measurement_grouping_symbols(mcms, layer_str, config) mv_label = "MCM" meas_label = measurement_label_map[m.return_type](mv_label) n_wires = len(config.wire_map) for mcm in mcms: ind = config.bit_map[mcm] + n_wires layer_str[ind] += meas_label return layer_str def _add_measurement(m, layer_str, config): """Updates ``layer_str`` with the ``m`` measurement.""" if m.mv is not None: return _add_cwire_measurement(m, layer_str, config) layer_str = _add_grouping_symbols(m, layer_str, config) if m.obs is None: obs_label = None else: obs_label = m.obs.label(decimals=config.decimals, cache=config.cache).replace("\n", "") if m.return_type in measurement_label_map: meas_label = measurement_label_map[m.return_type](obs_label) else: meas_label = m.return_type.value if len(m.wires) == 0: # state or probability across all wires n_wires = len(config.wire_map) for i, s in enumerate(layer_str[:n_wires]): layer_str[i] = s + meas_label for w in m.wires: layer_str[config.wire_map[w]] += meas_label return layer_str # pylint: disable=too-many-arguments def tape_text( tape, wire_order=None, show_all_wires=False, decimals=None, max_length=100, show_matrices=True, cache=None, ): """Text based diagram for a Quantum Tape. Args: tape (QuantumTape): the operations and measurements to draw Keyword Args: wire_order (Sequence[Any]): the order (from top to bottom) to print the wires of the circuit show_all_wires (bool): If True, all wires, including empty wires, are printed. decimals (int): How many decimal points to include when formatting operation parameters. Default ``None`` will omit parameters from operation labels. max_length (Int) : Maximum length of a individual line. After this length, the diagram will begin anew beneath the previous lines. show_matrices=True (bool): show matrix valued parameters below all circuit diagrams cache (dict): Used to store information between recursive calls. Necessary keys are ``'tape_offset'`` and ``'matrices'``. Returns: str : String based graphic of the circuit. **Example:** .. code-block:: python ops = [ qml.QFT(wires=(0, 1, 2)), qml.RX(1.234, wires=0), qml.RY(1.234, wires=1), qml.RZ(1.234, wires=2), qml.Toffoli(wires=(0, 1, "aux")) ] measurements = [ qml.expval(qml.Z("aux")), qml.var(qml.Z(0) @ qml.Z(1)), qml.probs(wires=(0, 1, 2, "aux")) ] tape = qml.tape.QuantumTape(ops, measurements) >>> print(qml.drawer.tape_text(tape)) 0: ─╭QFT──RX─╭●─┤ ╭Var[Z@Z] ╭Probs 1: ─├QFT──RY─├●─┤ ╰Var[Z@Z] ├Probs 2: ─╰QFT──RZ─│──┤ ├Probs aux: ──────────╰X─┤ <Z> ╰Probs .. details:: :title: Usage Details By default, parameters are omitted. By specifying the ``decimals`` keyword, parameters are displayed to the specified precision. Matrix-valued parameters are never displayed. >>> print(qml.drawer.tape_text(tape, decimals=2)) 0: ─╭QFT──RX(1.23)─╭●─┤ ╭Var[Z@Z] ╭Probs 1: ─├QFT──RY(1.23)─├●─┤ ╰Var[Z@Z] ├Probs 2: ─╰QFT──RZ(1.23)─│──┤ ├Probs aux: ────────────────╰X─┤ <Z> ╰Probs The ``max_length`` keyword wraps long circuits: .. code-block:: python rng = np.random.default_rng(seed=42) shape = qml.StronglyEntanglingLayers.shape(n_wires=5, n_layers=5) params = rng.random(shape) tape2 = qml.StronglyEntanglingLayers(params, wires=range(5)).expand() print(qml.drawer.tape_text(tape2, max_length=60)) .. code-block:: none 0: ──Rot─╭●──────────╭X──Rot─╭●───────╭X──Rot──────╭●────╭X 1: ──Rot─╰X─╭●───────│───Rot─│──╭●────│──╭X────Rot─│──╭●─│─ 2: ──Rot────╰X─╭●────│───Rot─╰X─│──╭●─│──│─────Rot─│──│──╰● 3: ──Rot───────╰X─╭●─│───Rot────╰X─│──╰●─│─────Rot─╰X─│──── 4: ──Rot──────────╰X─╰●──Rot───────╰X────╰●────Rot────╰X─── ───Rot───────────╭●─╭X──Rot──────╭●──────────────╭X─┤ ──╭X────Rot──────│──╰●─╭X────Rot─╰X───╭●─────────│──┤ ──│────╭X────Rot─│─────╰●───╭X────Rot─╰X───╭●────│──┤ ──╰●───│─────Rot─│──────────╰●───╭X────Rot─╰X─╭●─│──┤ ───────╰●────Rot─╰X──────────────╰●────Rot────╰X─╰●─┤ The ``wire_order`` keyword specifies the order of the wires from top to bottom: >>> print(qml.drawer.tape_text(tape, wire_order=["aux", 2, 1, 0])) aux: ──────────╭X─┤ <Z> ╭Probs 2: ─╭QFT──RZ─│──┤ ├Probs 1: ─├QFT──RY─├●─┤ ╭Var[Z@Z] ├Probs 0: ─╰QFT──RX─╰●─┤ ╰Var[Z@Z] ╰Probs If the wire order contains empty wires, they are only shown if the ``show_all_wires=True``. >>> print(qml.drawer.tape_text(tape, wire_order=["a", "b", "aux", 0, 1, 2], show_all_wires=True)) a: ─────────────┤ b: ─────────────┤ aux: ──────────╭X─┤ <Z> ╭Probs 0: ─╭QFT──RX─├●─┤ ╭Var[Z@Z] ├Probs 1: ─├QFT──RY─╰●─┤ ╰Var[Z@Z] ├Probs 2: ─╰QFT──RZ────┤ ╰Probs Matrix valued parameters are always denoted by ``M`` followed by an integer corresponding to unique matrices. The list of unique matrices can be printed at the end of the diagram by selecting ``show_matrices=True`` (the default): .. code-block:: python ops = [ qml.QubitUnitary(np.eye(2), wires=0), qml.QubitUnitary(np.eye(2), wires=1) ] measurements = [qml.expval(qml.Hermitian(np.eye(4), wires=(0,1)))] tape = qml.tape.QuantumTape(ops, measurements) >>> print(qml.drawer.tape_text(tape)) 0: ──U(M0)─┤ ╭<𝓗(M1)> 1: ──U(M0)─┤ ╰<𝓗(M1)> M0 = [[1. 0.] [0. 1.]] M1 = [[1. 0. 0. 0.] [0. 1. 0. 0.] [0. 0. 1. 0.] [0. 0. 0. 1.]] An existing matrix cache can be passed via the ``cache`` keyword. Note that the dictionary passed to ``cache`` will be modified during execution to contain any new matrices and the tape offset. >>> cache = {'matrices': [-np.eye(3)]} >>> print(qml.drawer.tape_text(tape, cache=cache)) 0: ──U(M1)─┤ ╭<𝓗(M2)> 1: ──U(M1)─┤ ╰<𝓗(M2)> M0 = [[-1. -0. -0.] [-0. -1. -0.] [-0. -0. -1.]] M1 = [[1. 0.] [0. 1.]] M2 = [[1. 0. 0. 0.] [0. 1. 0. 0.] [0. 0. 1. 0.] [0. 0. 0. 1.]] >>> cache {'matrices': [tensor([[-1., -0., -0.], [-0., -1., -0.], [-0., -0., -1.]], requires_grad=True), tensor([[1., 0.], [0., 1.]], requires_grad=True), tensor([[1., 0., 0., 0.], [0., 1., 0., 0.], [0., 0., 1., 0.], [0., 0., 0., 1.]], requires_grad=True)], 'tape_offset': 0} When the provided tape has nested tapes inside, this function is called recursively. To maintain numbering of tapes to arbitrary levels of nesting, the ``cache`` keyword uses the ``"tape_offset"`` value to determine numbering. Note that the value is updated during the call. .. code-block:: python with qml.tape.QuantumTape() as tape: with qml.tape.QuantumTape() as tape_inner: qml.X(0) cache = {'tape_offset': 3} print(qml.drawer.tape_text(tape, cache=cache)) print("New tape offset: ", cache['tape_offset']) .. code-block:: none 0: ──Tape:3─┤ Tape:3 0: ──X─┤ New tape offset: 4 """ tape = transform_deferred_measurements_tape(tape) cache = cache or {} cache.setdefault("tape_offset", 0) cache.setdefault("matrices", []) tape_cache = [] wire_map = convert_wire_order(tape, wire_order=wire_order, show_all_wires=show_all_wires) bit_map = default_bit_map(tape) n_wires = len(wire_map) n_bits = len(bit_map) if n_wires == 0: return "" # Used to store lines that are hitting the maximum length finished_lines = [] layers = drawable_layers(tape.operations, wire_map=wire_map, bit_map=bit_map) final_operations_layer = len(layers) - 1 layers += drawable_layers(tape.measurements, wire_map=wire_map, bit_map=bit_map) # Update bit map and collect information about connections between mid-circuit measurements, # classical conditions, and terminal measurements for processing mid-circuit measurements. cwire_layers, _ = cwire_connections(layers, bit_map) wire_totals = [f"{wire}: " for wire in wire_map] bit_totals = ["" for _ in range(n_bits)] line_length = max(len(s) for s in wire_totals) wire_totals = [s.rjust(line_length, " ") for s in wire_totals] bit_totals = [s.rjust(line_length, " ") for s in bit_totals] # Collect information needed for drawing layers config = _Config( wire_map=wire_map, bit_map=bit_map, cur_layer=-1, cwire_layers=cwire_layers, decimals=decimals, cache=cache, ) for i, layer in enumerate(layers): # Update fillers and helper function w_filler = "─" if i <= final_operations_layer else " " b_filler = "═" if i <= final_operations_layer else " " add_fn = _add_op if i <= final_operations_layer else _add_measurement # Create initial strings for the current layer using wire and cwire fillers layer_str = [w_filler] * n_wires + [" "] * n_bits for b in bit_map.values(): cur_b_filler = b_filler if min(cwire_layers[b]) < i < max(cwire_layers[b]) else " " layer_str[b + n_wires] = cur_b_filler config.cur_layer = i ########################################## # Update current layer strings with labels ########################################## for op in layer: if isinstance(op, qml.tape.QuantumScript): layer_str = _add_grouping_symbols(op, layer_str, config) label = f"Tape:{cache['tape_offset']+len(tape_cache)}" for w in op.wires: layer_str[wire_map[w]] += label tape_cache.append(op) else: layer_str = add_fn(op, layer_str, config) ################################################# # Left justify layer strings and pad on the right ################################################# # Adjust width for wire filler on unused wires max_label_len = max(len(s) for s in layer_str) for w in range(n_wires): layer_str[w] = layer_str[w].ljust(max_label_len, w_filler) # Adjust width for bit filler on unused bits for b in range(n_bits): cur_b_filler = b_filler if cwire_layers[b][0] <= i < cwire_layers[b][-1] else " " layer_str[b + n_wires] = layer_str[b + n_wires].ljust(max_label_len, cur_b_filler) line_length += max_label_len + 1 # one for the filler character ################## # Create new lines ################## if line_length > max_length: # move totals into finished_lines and reset totals finished_lines += wire_totals + bit_totals finished_lines[-1] += "\n" wire_totals = [w_filler] * n_wires # Bit totals for new lines for warped drawings need to be consistent with the # current bit filler bit_totals = [] for b in range(n_bits): cur_b_filler = b_filler if cwire_layers[b][0] < i <= cwire_layers[b][-1] else " " bit_totals.append(cur_b_filler) line_length = 2 + max_label_len ################################################### # Join current layer with lines for previous layers ################################################### # Joining is done by adding a filler at the end of the previous layer wire_totals = [w_filler.join([t, s]) for t, s in zip(wire_totals, layer_str[:n_wires])] for j, (bt, s) in enumerate(zip(bit_totals, layer_str[n_wires : n_wires + n_bits])): cur_b_filler = b_filler if cwire_layers[j][0] < i <= cwire_layers[j][-1] else " " bit_totals[j] = cur_b_filler.join([bt, s]) ################################################ # Add ender characters to final operations layer ################################################ if i == final_operations_layer: wire_totals = [f"{s}─┤" for s in wire_totals] for b in range(n_bits): if cwire_layers[b][-1] > final_operations_layer: bit_totals[b] += "═╡" else: bit_totals[b] += " " line_length += 2 # Recursively handle nested tapes # tape_totals = "\n".join(finished_lines + wire_totals + bit_totals) current_tape_offset = cache["tape_offset"] cache["tape_offset"] += len(tape_cache) for i, nested_tape in enumerate(tape_cache): label = f"\nTape:{i+current_tape_offset}" tape_str = tape_text( nested_tape, wire_order, show_all_wires, decimals, max_length, show_matrices=False, cache=cache, ) tape_totals = "\n".join([tape_totals, label, tape_str]) if show_matrices: mat_str = "" for i, mat in enumerate(cache["matrices"]): mat_str += f"\nM{i} = \n{mat}" return tape_totals + mat_str return tape_totals
pennylane/pennylane/drawer/tape_text.py/0
{ "file_path": "pennylane/pennylane/drawer/tape_text.py", "repo_id": "pennylane", "token_count": 9401 }
54
# Copyright 2018-2024 Xanadu Quantum Technologies Inc. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Contains functions for computing classical and quantum fisher information matrices.""" # pylint: disable=import-outside-toplevel, not-callable from functools import partial import pennylane as qml from pennylane import transform from pennylane.devices import DefaultQubit, DefaultQubitLegacy from pennylane.gradients import adjoint_metric_tensor from pennylane.typing import PostprocessingFn # TODO: create qml.math.jacobian and replace it here def _torch_jac(circ): """Torch jacobian as a callable function""" import torch def wrapper(*args, **kwargs): loss = partial(circ, **kwargs) if len(args) > 1: return torch.autograd.functional.jacobian(loss, args, create_graph=True) return torch.autograd.functional.jacobian(loss, *args, create_graph=True) return wrapper # TODO: create qml.math.jacobian and replace it here def _tf_jac(circ): """TF jacobian as a callable function""" import tensorflow as tf def wrapper(*args, **kwargs): with tf.GradientTape() as tape: loss = circ(*args, **kwargs) return tape.jacobian(loss, args) return wrapper def _compute_cfim(p, dp): r"""Computes the (num_params, num_params) classical fisher information matrix from the probabilities and its derivatives I.e. it computes :math:`classical_fisher_{ij} = \sum_\ell (\partial_i p_\ell) (\partial_i p_\ell) / p_\ell` """ # Exclude values where p=0 and calculate 1/p nonzeros_p = qml.math.where(p > 0, p, qml.math.ones_like(p)) one_over_p = qml.math.where(p > 0, qml.math.ones_like(p), qml.math.zeros_like(p)) one_over_p = one_over_p / nonzeros_p # Multiply dp and p # Note that casting and being careful about dtypes is necessary as interfaces # typically treat derivatives (dp) with float32, while standard execution (p) comes in float64 dp = qml.math.cast_like(dp, p) dp = qml.math.reshape( dp, (len(p), -1) ) # Squeeze does not work, as you could have shape (num_probs, num_params) with num_params = 1 dp_over_p = qml.math.transpose(dp) * one_over_p # creates (n_params, n_probs) array # (n_params, n_probs) @ (n_probs, n_params) = (n_params, n_params) return dp_over_p @ dp @transform def _make_probs( tape: qml.tape.QuantumScript, ) -> tuple[qml.tape.QuantumScriptBatch, PostprocessingFn]: """Ignores the return types of the provided circuit and creates a new one that outputs probabilities""" qscript = qml.tape.QuantumScript(tape.operations, [qml.probs(tape.wires)], shots=tape.shots) def post_processing_fn(res): # only a single probs measurement, so no stacking needed return res[0] return [qscript], post_processing_fn def classical_fisher(qnode, argnums=0): r"""Returns a function that computes the classical fisher information matrix (CFIM) of a given :class:`.QNode` or quantum tape. Given a parametrized (classical) probability distribution :math:`p(\bm{\theta})`, the classical fisher information matrix quantifies how changes to the parameters :math:`\bm{\theta}` are reflected in the probability distribution. For a parametrized quantum state, we apply the concept of classical fisher information to the computational basis measurement. More explicitly, this function implements eq. (15) in `arxiv:2103.15191 <https://arxiv.org/abs/2103.15191>`_: .. math:: \text{CFIM}_{i, j} = \sum_{\ell=0}^{2^N-1} \frac{1}{p_\ell(\bm{\theta})} \frac{\partial p_\ell(\bm{\theta})}{ \partial \theta_i} \frac{\partial p_\ell(\bm{\theta})}{\partial \theta_j} for :math:`N` qubits. Args: tape (:class:`.QNode` or qml.QuantumTape): A :class:`.QNode` or quantum tape that may have arbitrary return types. argnums (Optional[int or List[int]]): Arguments to be differentiated in case interface ``jax`` is used. Returns: func: The function that computes the classical fisher information matrix. This function accepts the same signature as the :class:`.QNode`. If the signature contains one differentiable variable ``params``, the function returns a matrix of size ``(len(params), len(params))``. For multiple differentiable arguments ``x, y, z``, it returns a list of sizes ``[(len(x), len(x)), (len(y), len(y)), (len(z), len(z))]``. .. seealso:: :func:`~.pennylane.metric_tensor`, :func:`~.pennylane.gradient.transforms.quantum_fisher` **Example** First, let us define a parametrized quantum state and return its (classical) probability distribution for all computational basis elements: .. code-block:: python import pennylane.numpy as pnp dev = qml.device("default.qubit") @qml.qnode(dev) def circ(params): qml.RX(params[0], wires=0) qml.CNOT([0, 1]) qml.CRY(params[1], wires=[1, 0]) qml.Hadamard(1) return qml.probs(wires=[0, 1]) Executing this circuit yields the ``2**2=4`` elements of :math:`p_\ell(\bm{\theta})` >>> pnp.random.seed(25) >>> params = pnp.random.random(2) >>> circ(params) tensor([0.41850088, 0.41850088, 0.08149912, 0.08149912], requires_grad=True) We can obtain its ``(2, 2)`` classical fisher information matrix (CFIM) by simply calling the function returned by ``classical_fisher()``: >>> cfim_func = qml.gradients.classical_fisher(circ) >>> cfim_func(params) tensor([[ 0.90156094, -0.12555804], [-0.12555804, 0.01748614]], requires_grad=True) This function has the same signature as the :class:`.QNode`. Here is a small example with multiple arguments: .. code-block:: python @qml.qnode(dev) def circ(x, y): qml.RX(x, wires=0) qml.RY(y, wires=0) return qml.probs(wires=range(1)) >>> x, y = pnp.array([0.5, 0.6], requires_grad=True) >>> circ(x, y) tensor([0.86215007, 0.13784993], requires_grad=True) >>> qml.gradients.classical_fisher(circ)(x, y) [tensor([[0.32934729]], requires_grad=True), tensor([[0.51650396]], requires_grad=True)] Note how in the case of multiple variables we get a list of matrices with sizes ``[(n_params0, n_params0), (n_params1, n_params1)]``, which in this case is simply two ``(1, 1)`` matrices. A typical setting where the classical fisher information matrix is used is in variational quantum algorithms. Closely related to the `quantum natural gradient <https://arxiv.org/abs/1909.02108>`_, which employs the `quantum` fisher information matrix, we can compute a rescaled gradient using the CFIM. In this scenario, typically a Hamiltonian objective function :math:`\langle H \rangle` is minimized: .. code-block:: python H = qml.Hamiltonian(coeffs=[0.5, 0.5], observables=[qml.Z(0), qml.Z(1)]) @qml.qnode(dev) def circ(params): qml.RX(params[0], wires=0) qml.RY(params[1], wires=0) qml.RX(params[2], wires=1) qml.RY(params[3], wires=1) qml.CNOT(wires=(0,1)) return qml.expval(H) params = pnp.random.random(4) We can compute both the gradient of :math:`\langle H \rangle` and the CFIM with the same :class:`.QNode` ``circ`` in this example since ``classical_fisher()`` ignores the return types and assumes ``qml.probs()`` for all wires. >>> grad = qml.grad(circ)(params) >>> cfim = qml.gradients.classical_fisher(circ)(params) >>> print(grad.shape, cfim.shape) (4,) (4, 4) Combined together, we can get a rescaled gradient to be employed for optimization schemes like natural gradient descent. >>> rescaled_grad = cfim @ grad >>> print(rescaled_grad) [-0.66772533 -0.16618756 -0.05865127 -0.06696078] The ``classical_fisher`` matrix itself is again differentiable: .. code-block:: python @qml.qnode(dev) def circ(params): qml.RX(qml.math.cos(params[0]), wires=0) qml.RX(qml.math.cos(params[0]), wires=1) qml.RX(qml.math.cos(params[1]), wires=0) qml.RX(qml.math.cos(params[1]), wires=1) return qml.probs(wires=range(2)) params = pnp.random.random(2) >>> qml.gradients.classical_fisher(circ)(params) tensor([[0.86929514, 0.76134441], [0.76134441, 0.6667992 ]], requires_grad=True) >>> qml.jacobian(qml.gradients.classical_fisher(circ))(params) array([[[ 1.98284265e+00, -1.60461922e-16], [ 8.68304725e-01, 1.07654307e+00]], [[ 8.68304725e-01, 1.07654307e+00], [ 7.30752264e-17, 1.88571178e+00]]]) """ new_qnode = _make_probs(qnode) def wrapper(*args, **kwargs): old_interface = qnode.interface if old_interface == "auto": qnode.interface = qml.math.get_interface(*args, *list(kwargs.values())) interface = qnode.interface if interface in ("jax", "jax-jit"): import jax jac = jax.jacobian(new_qnode, argnums=argnums) if interface == "torch": jac = _torch_jac(new_qnode) if interface == "autograd": jac = qml.jacobian(new_qnode) if interface == "tf": jac = _tf_jac(new_qnode) j = jac(*args, **kwargs) p = new_qnode(*args, **kwargs) if old_interface == "auto": qnode.interface = "auto" # In case multiple variables are used, we create a list of cfi matrices if isinstance(j, tuple): res = [] for j_i in j: res.append(_compute_cfim(p, j_i)) if len(j) == 1: return res[0] return res return _compute_cfim(p, j) return wrapper @partial(transform, is_informative=True) def quantum_fisher( tape: qml.tape.QuantumScript, device, *args, **kwargs ) -> tuple[qml.tape.QuantumScriptBatch, PostprocessingFn]: r"""Returns a function that computes the quantum fisher information matrix (QFIM) of a given :class:`.QNode`. Given a parametrized quantum state :math:`|\psi(\bm{\theta})\rangle`, the quantum fisher information matrix (QFIM) quantifies how changes to the parameters :math:`\bm{\theta}` are reflected in the quantum state. The metric used to induce the QFIM is the fidelity :math:`f = |\langle \psi | \psi' \rangle|^2` between two (pure) quantum states. This leads to the following definition of the QFIM (see eq. (27) in `arxiv:2103.15191 <https://arxiv.org/abs/2103.15191>`_): .. math:: \text{QFIM}_{i, j} = 4 \text{Re}\left[ \langle \partial_i \psi(\bm{\theta}) | \partial_j \psi(\bm{\theta}) \rangle - \langle \partial_i \psi(\bm{\theta}) | \psi(\bm{\theta}) \rangle \langle \psi(\bm{\theta}) | \partial_j \psi(\bm{\theta}) \rangle \right] with short notation :math:`| \partial_j \psi(\bm{\theta}) \rangle := \frac{\partial}{\partial \theta_j}| \psi(\bm{\theta}) \rangle`. .. seealso:: :func:`~.pennylane.metric_tensor`, :func:`~.pennylane.adjoint_metric_tensor`, :func:`~.pennylane.gradient.transforms.classical_fisher` Args: tape (QNode or QuantumTape or Callable): A quantum circuit that may have arbitrary return types. *args: In case finite shots are used, further arguments according to :func:`~.pennylane.metric_tensor` may be passed. Returns: qnode (QNode) or quantum function (Callable) or tuple[List[QuantumTape], function]: The transformed circuit as described in :func:`qml.transform <pennylane.transform>`. Executing this circuit will provide the quantum Fisher information in the form of a tensor. .. note:: ``quantum_fisher`` coincides with the ``metric_tensor`` with a prefactor of :math:`4`. Internally, :func:`~.pennylane.adjoint_metric_tensor` is used when executing on ``"default.qubit"`` with exact expectations (``shots=None``). In all other cases, e.g. if a device with finite shots is used, the hardware-compatible transform :func:`~.pennylane.metric_tensor` is used, which may require an additional wire on the device. Please refer to the respective documentations for details. **Example** The quantum Fisher information matrix (QIFM) can be used to compute the `natural` gradient for `Quantum Natural Gradient Descent <https://arxiv.org/abs/1909.02108>`_. A typical scenario is optimizing the expectation value of a Hamiltonian: .. code-block:: python n_wires = 2 dev = qml.device("default.qubit", wires=n_wires) H = 1.*qml.X(0) @ qml.X(1) - 0.5 * qml.Z(1) @qml.qnode(dev) def circ(params): qml.RY(params[0], wires=1) qml.CNOT(wires=(1,0)) qml.RY(params[1], wires=1) qml.RZ(params[2], wires=1) return qml.expval(H) params = pnp.array([0.5, 1., 0.2], requires_grad=True) The natural gradient is then simply the QFIM multiplied by the gradient: >>> grad = qml.grad(circ)(params) >>> grad array([ 0.59422561, -0.02615095, -0.05146226]) >>> qfim = qml.gradients.quantum_fisher(circ)(params) >>> qfim tensor([[1. , 0. , 0. ], [0. , 1. , 0. ], [0. , 0. , 0.77517241]], requires_grad=True) >>> qfim @ grad tensor([ 0.59422561, -0.02615095, -0.03989212], requires_grad=True) When using real hardware or finite shots, ``quantum_fisher`` is internally calling :func:`~.pennylane.metric_tensor`. To obtain the full QFIM, we need an auxilary wire to perform the Hadamard test. >>> dev = qml.device("default.qubit", wires=n_wires+1, shots=1000) >>> @qml.qnode(dev) ... def circ(params): ... qml.RY(params[0], wires=1) ... qml.CNOT(wires=(1,0)) ... qml.RY(params[1], wires=1) ... qml.RZ(params[2], wires=1) ... return qml.expval(H) >>> qfim = qml.gradients.quantum_fisher(circ)(params) Alternatively, we can fall back on the block-diagonal QFIM without the additional wire. >>> qfim = qml.gradients.quantum_fisher(circ, approx="block-diag")(params) """ if device.shots or not isinstance(device, (DefaultQubitLegacy, DefaultQubit)): tapes, processing_fn = qml.gradients.metric_tensor(tape, *args, **kwargs) def processing_fn_multiply(res): res = qml.execute(res, device=device) return 4 * processing_fn(res) return tapes, processing_fn_multiply res = adjoint_metric_tensor(tape, *args, **kwargs) def processing_fn_multiply(r): # pylint: disable=function-redefined r = qml.math.stack(r) return 4 * r return res, processing_fn_multiply @quantum_fisher.custom_qnode_transform def qnode_execution_wrapper(self, qnode, targs, tkwargs): """Here, we overwrite the QNode execution wrapper in order to take into account that classical processing may be present inside the QNode.""" tkwargs["device"] = qnode.device return self.default_qnode_transform(qnode, targs, tkwargs)
pennylane/pennylane/gradients/fisher.py/0
{ "file_path": "pennylane/pennylane/gradients/fisher.py", "repo_id": "pennylane", "token_count": 6478 }
55
# Copyright 2018-2021 Xanadu Quantum Technologies Inc. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ This file contains functionalities for kernel related costs. See `here <https://www.doi.org/10.1007/s10462-012-9369-4>`_ for a review. """ import numpy as np from ..math import frobenius_inner_product from .utils import square_kernel_matrix def polarity( X, Y, kernel, assume_normalized_kernel=False, rescale_class_labels=True, normalize=False, ): r"""Polarity of a given kernel function. For a dataset with feature vectors :math:`\{x_i\}` and associated labels :math:`\{y_i\}`, the polarity of the kernel function :math:`k` is given by .. math :: \operatorname{P}(k) = \sum_{i,j=1}^n y_i y_j k(x_i, x_j) If the dataset is unbalanced, that is if the numbers of datapoints in the two classes :math:`n_+` and :math:`n_-` differ, ``rescale_class_labels=True`` will apply a rescaling according to :math:`\tilde{y}_i = \frac{y_i}{n_{y_i}}`. This is activated by default and only results in a prefactor that depends on the size of the dataset for balanced datasets. The keyword argument ``assume_normalized_kernel`` is passed to :func:`~.kernels.square_kernel_matrix`, for the computation :func:`~.utils.frobenius_inner_product` is used. Args: X (list[datapoint]): List of datapoints. Y (list[float]): List of class labels of datapoints, assumed to be either -1 or 1. kernel ((datapoint, datapoint) -> float): Kernel function that maps datapoints to kernel value. assume_normalized_kernel (bool, optional): Assume that the kernel is normalized, i.e. the kernel evaluates to 1 when both arguments are the same datapoint. rescale_class_labels (bool, optional): Rescale the class labels. This is important to take care of unbalanced datasets. normalize (bool): If True, rescale the polarity to the target_alignment. Returns: float: The kernel polarity. **Example:** Consider a simple kernel function based on :class:`~.templates.embeddings.AngleEmbedding`: .. code-block :: python dev = qml.device('default.qubit', wires=2) @qml.qnode(dev) def circuit(x1, x2): qml.templates.AngleEmbedding(x1, wires=dev.wires) qml.adjoint(qml.templates.AngleEmbedding)(x2, wires=dev.wires) return qml.probs(wires=dev.wires) kernel = lambda x1, x2: circuit(x1, x2)[0] We can then compute the polarity on a set of 4 (random) feature vectors ``X`` with labels ``Y`` via >>> X = np.random.random((4, 2)) >>> Y = np.array([-1, -1, 1, 1]) >>> qml.kernels.polarity(X, Y, kernel) tensor(0.04361349, requires_grad=True) """ # pylint: disable=too-many-arguments K = square_kernel_matrix(X, kernel, assume_normalized_kernel=assume_normalized_kernel) if rescale_class_labels: nplus = np.count_nonzero(np.array(Y) == 1) nminus = len(Y) - nplus _Y = np.array([y / nplus if y == 1 else y / nminus for y in Y]) else: _Y = np.array(Y) T = np.outer(_Y, _Y) return frobenius_inner_product(K, T, normalize=normalize) def target_alignment( X, Y, kernel, assume_normalized_kernel=False, rescale_class_labels=True, ): r"""Target alignment of a given kernel function. This function is an alias for :func:`~.kernels.polarity` with ``normalize=True``. For a dataset with feature vectors :math:`\{x_i\}` and associated labels :math:`\{y_i\}`, the target alignment of the kernel function :math:`k` is given by .. math :: \operatorname{TA}(k) = \frac{\sum_{i,j=1}^n y_i y_j k(x_i, x_j)} {\sqrt{\sum_{i,j=1}^n y_i y_j} \sqrt{\sum_{i,j=1}^n k(x_i, x_j)^2}} If the dataset is unbalanced, that is if the numbers of datapoints in the two classes :math:`n_+` and :math:`n_-` differ, ``rescale_class_labels=True`` will apply a rescaling according to :math:`\tilde{y}_i = \frac{y_i}{n_{y_i}}`. This is activated by default and only results in a prefactor that depends on the size of the dataset for balanced datasets. Args: X (list[datapoint]): List of datapoints Y (list[float]): List of class labels of datapoints, assumed to be either -1 or 1. kernel ((datapoint, datapoint) -> float): Kernel function that maps datapoints to kernel value. assume_normalized_kernel (bool, optional): Assume that the kernel is normalized, i.e. the kernel evaluates to 1 when both arguments are the same datapoint. rescale_class_labels (bool, optional): Rescale the class labels. This is important to take care of unbalanced datasets. Returns: float: The kernel-target alignment. **Example:** Consider a simple kernel function based on :class:`~.templates.embeddings.AngleEmbedding`: .. code-block :: python dev = qml.device('default.qubit', wires=2) @qml.qnode(dev) def circuit(x1, x2): qml.templates.AngleEmbedding(x1, wires=dev.wires) qml.adjoint(qml.templates.AngleEmbedding)(x2, wires=dev.wires) return qml.probs(wires=dev.wires) kernel = lambda x1, x2: circuit(x1, x2)[0] We can then compute the kernel-target alignment on a set of 4 (random) feature vectors ``X`` with labels ``Y`` via >>> X = np.random.random((4, 2)) >>> Y = np.array([-1, -1, 1, 1]) >>> qml.kernels.target_alignment(X, Y, kernel) tensor(0.01124802, requires_grad=True) We can see that this is equivalent to using ``normalize=True`` in ``polarity``: >>> target_alignment = qml.kernels.target_alignment(X, Y, kernel) >>> normalized_polarity = qml.kernels.polarity(X, Y, kernel, normalize=True) >>> np.isclose(target_alignment, normalized_polarity) tensor(True, requires_grad=True) """ return polarity( X, Y, kernel, assume_normalized_kernel=assume_normalized_kernel, rescale_class_labels=rescale_class_labels, normalize=True, )
pennylane/pennylane/kernels/cost_functions.py/0
{ "file_path": "pennylane/pennylane/kernels/cost_functions.py", "repo_id": "pennylane", "token_count": 2636 }
56
# Copyright 2018-2021 Xanadu Quantum Technologies Inc. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Multiple dispatch functions""" # pylint: disable=import-outside-toplevel,too-many-return-statements import functools from collections.abc import Sequence # pylint: disable=wrong-import-order import autoray as ar import numpy as onp from autograd.numpy.numpy_boxes import ArrayBox from autoray import numpy as np from numpy import ndarray from . import single_dispatch # pylint:disable=unused-import from .utils import cast, cast_like, get_interface, requires_grad # pylint:disable=redefined-outer-name def array(*args, like=None, **kwargs): """Creates an array or tensor object of the target framework. If the PyTorch interface is specified, this method preserves the Torch device used. If the JAX interface is specified, this method uses JAX numpy arrays, which do not cause issues with jit tracers. Returns: tensor_like: the tensor_like object of the framework """ res = np.array(*args, like=like, **kwargs) if like is not None and get_interface(like) == "torch": res = res.to(device=like.device) return res def eye(*args, like=None, **kwargs): """Creates an identity array or tensor object of the target framework. This method preserves the Torch device used. Returns: tensor_like: the tensor_like object of the framework """ res = np.eye(*args, like=like, **kwargs) if like is not None and get_interface(like) == "torch": res = res.to(device=like.device) return res def multi_dispatch(argnum=None, tensor_list=None): r"""Decorater to dispatch arguments handled by the interface. This helps simplify definitions of new functions inside PennyLane. We can decorate the function, indicating the arguments that are tensors handled by the interface: >>> @qml.math.multi_dispatch(argnum=[0, 1]) ... def some_function(tensor1, tensor2, option, like): ... # the interface string is stored in `like`. ... ... Args: argnum (list[int]): A list of integers indicating the indices to dispatch (i.e., the arguments that are tensors handled by an interface). If ``None``, dispatch over all arguments. tensor_lists (list[int]): a list of integers indicating which indices in ``argnum`` are expected to be lists of tensors. If an argument marked as tensor list is not a ``tuple`` or ``list``, it is treated as if it was not marked as tensor list. If ``None``, this option is ignored. Returns: func: A wrapped version of the function, which will automatically attempt to dispatch to the correct autodifferentiation framework for the requested arguments. Note that the ``like`` argument will be optional, but can be provided if an explicit override is needed. .. seealso:: :func:`pennylane.math.multi_dispatch._multi_dispatch` .. note:: This decorator makes the interface argument "like" optional as it utilizes the utility function `_multi_dispatch` to automatically detect the appropriate interface based on the tensor types. **Examples** We can redefine external functions to be suitable for PennyLane. Here, we redefine Autoray's ``stack`` function. >>> stack = multi_dispatch(argnum=0, tensor_list=0)(autoray.numpy.stack) We can also use the ``multi_dispatch`` decorator to dispatch arguments of more more elaborate custom functions. Here is an example of a ``custom_function`` that computes :math:`c \\sum_i (v_i)^T v_i`, where :math:`v_i` are vectors in ``values`` and :math:`c` is a fixed ``coefficient``. Note how ``argnum=0`` only points to the first argument ``values``, how ``tensor_list=0`` indicates that said first argument is a list of vectors, and that ``coefficient`` is not dispatched. >>> @math.multi_dispatch(argnum=0, tensor_list=0) >>> def custom_function(values, like, coefficient=10): >>> # values is a list of vectors >>> # like can force the interface (optional) >>> if like == "tensorflow": >>> # add interface-specific handling if necessary >>> return coefficient * np.sum([math.dot(v,v) for v in values]) We can then run >>> values = [np.array([1, 2, 3]) for _ in range(5)] >>> custom_function(values) 700 """ def decorator(fn): @functools.wraps(fn) def wrapper(*args, **kwargs): argnums = argnum if argnum is not None else list(range(len(args))) tensor_lists = tensor_list if tensor_list is not None else [] if not isinstance(argnums, Sequence): argnums = [argnums] if not isinstance(tensor_lists, Sequence): tensor_lists = [tensor_lists] dispatch_args = [] for a in argnums: # Only use extend if the marked argument really # is a (native) python Sequence if a in tensor_lists and isinstance(args[a], (list, tuple)): dispatch_args.extend(args[a]) else: dispatch_args.append(args[a]) interface = kwargs.pop("like", None) interface = interface or get_interface(*dispatch_args) kwargs["like"] = interface return fn(*args, **kwargs) return wrapper return decorator @multi_dispatch(argnum=[0, 1]) def kron(*args, like=None, **kwargs): """The kronecker/tensor product of args.""" if like == "scipy": return onp.kron(*args, **kwargs) # Dispatch scipy kron to numpy backed specifically. if like == "torch": mats = [ ar.numpy.asarray(arg, like="torch") if isinstance(arg, onp.ndarray) else arg for arg in args ] return ar.numpy.kron(*mats) return ar.numpy.kron(*args, like=like, **kwargs) @multi_dispatch(argnum=[0], tensor_list=[0]) def block_diag(values, like=None): """Combine a sequence of 2D tensors to form a block diagonal tensor. Args: values (Sequence[tensor_like]): Sequence of 2D arrays/tensors to form the block diagonal tensor. Returns: tensor_like: the block diagonal tensor **Example** >>> t = [ ... np.array([[1, 2], [3, 4]]), ... torch.tensor([[1, 2, 3], [-1, -6, -3]]), ... torch.tensor([[5]]) ... ] >>> qml.math.block_diag(t) tensor([[ 1, 2, 0, 0, 0, 0], [ 3, 4, 0, 0, 0, 0], [ 0, 0, 1, 2, 3, 0], [ 0, 0, -1, -6, -3, 0], [ 0, 0, 0, 0, 0, 5]]) """ values = np.coerce(values, like=like) return np.block_diag(values, like=like) @multi_dispatch(argnum=[0], tensor_list=[0]) def concatenate(values, axis=0, like=None): """Concatenate a sequence of tensors along the specified axis. .. warning:: Tensors that are incompatible (such as Torch and TensorFlow tensors) cannot both be present. Args: values (Sequence[tensor_like]): Sequence of tensor-like objects to concatenate. The objects must have the same shape, except in the dimension corresponding to axis (the first, by default). axis (int): The axis along which the input tensors are concatenated. If axis is None, tensors are flattened before use. Default is 0. Returns: tensor_like: The concatenated tensor. **Example** >>> x = tf.constant([0.6, 0.1, 0.6]) >>> y = tf.Variable([0.1, 0.2, 0.3]) >>> z = np.array([5., 8., 101.]) >>> concatenate([x, y, z]) <tf.Tensor: shape=(9,), dtype=float32, numpy= array([6.00e-01, 1.00e-01, 6.00e-01, 1.00e-01, 2.00e-01, 3.00e-01, 5.00e+00, 8.00e+00, 1.01e+02], dtype=float32)> """ if like == "torch": import torch device = ( "cuda" if any(t.device.type == "cuda" for t in values if isinstance(t, torch.Tensor)) else "cpu" ) if axis is None: # flatten and then concatenate zero'th dimension # to reproduce numpy's behaviour values = [ np.flatten(torch.as_tensor(t, device=torch.device(device))) # pragma: no cover for t in values ] axis = 0 else: values = [ torch.as_tensor(t, device=torch.device(device)) for t in values # pragma: no cover ] if like == "tensorflow" and axis is None: # flatten and then concatenate zero'th dimension # to reproduce numpy's behaviour values = [np.flatten(np.array(t)) for t in values] axis = 0 return np.concatenate(values, axis=axis, like=like) @multi_dispatch(argnum=[0], tensor_list=[0]) def diag(values, k=0, like=None): """Construct a diagonal tensor from a list of scalars. Args: values (tensor_like or Sequence[scalar]): sequence of numeric values that make up the diagonal k (int): The diagonal in question. ``k=0`` corresponds to the main diagonal. Use ``k>0`` for diagonals above the main diagonal, and ``k<0`` for diagonals below the main diagonal. Returns: tensor_like: the 2D diagonal tensor **Example** >>> x = [1., 2., tf.Variable(3.)] >>> qml.math.diag(x) <tf.Tensor: shape=(3, 3), dtype=float32, numpy= array([[1., 0., 0.], [0., 2., 0.], [0., 0., 3.]], dtype=float32)> >>> y = tf.Variable([0.65, 0.2, 0.1]) >>> qml.math.diag(y, k=-1) <tf.Tensor: shape=(4, 4), dtype=float32, numpy= array([[0. , 0. , 0. , 0. ], [0.65, 0. , 0. , 0. ], [0. , 0.2 , 0. , 0. ], [0. , 0. , 0.1 , 0. ]], dtype=float32)> >>> z = torch.tensor([0.1, 0.2]) >>> qml.math.diag(z, k=1) tensor([[0.0000, 0.1000, 0.0000], [0.0000, 0.0000, 0.2000], [0.0000, 0.0000, 0.0000]]) """ if isinstance(values, (list, tuple)): values = np.stack(np.coerce(values, like=like), like=like) return np.diag(values, k=k, like=like) @multi_dispatch(argnum=[0, 1]) def matmul(tensor1, tensor2, like=None): """Returns the matrix product of two tensors.""" if like == "torch": if get_interface(tensor1) != "torch": tensor1 = ar.numpy.asarray(tensor1, like="torch") if get_interface(tensor2) != "torch": tensor2 = ar.numpy.asarray(tensor2, like="torch") tensor2 = cast_like(tensor2, tensor1) # pylint: disable=arguments-out-of-order return ar.numpy.matmul(tensor1, tensor2, like=like) @multi_dispatch(argnum=[0, 1]) def dot(tensor1, tensor2, like=None): """Returns the matrix or dot product of two tensors. * If either tensor is 0-dimensional, elementwise multiplication is performed and a 0-dimensional scalar or a tensor with the same dimensions as the other tensor is returned. * If both tensors are 1-dimensional, the dot product is returned. * If the first array is 2-dimensional and the second array 1-dimensional, the matrix-vector product is returned. * If both tensors are 2-dimensional, the matrix product is returned. * Finally, if the first array is N-dimensional and the second array M-dimensional, a sum product over the last dimension of the first array, and the second-to-last dimension of the second array is returned. Args: tensor1 (tensor_like): input tensor tensor2 (tensor_like): input tensor Returns: tensor_like: the matrix or dot product of two tensors """ x, y = np.coerce([tensor1, tensor2], like=like) if like == "torch": if x.ndim == 0 or y.ndim == 0: return x * y if x.ndim <= 2 and y.ndim <= 2: return x @ y return np.tensordot(x, y, axes=[[-1], [-2]], like=like) if like in {"tensorflow", "autograd"}: ndim_y = len(np.shape(y)) ndim_x = len(np.shape(x)) if ndim_x == 0 or ndim_y == 0: return x * y if ndim_y == 1: return np.tensordot(x, y, axes=[[-1], [0]], like=like) if ndim_x == 2 and ndim_y == 2: return x @ y return np.tensordot(x, y, axes=[[-1], [-2]], like=like) return np.dot(x, y, like=like) @multi_dispatch(argnum=[0, 1]) def tensordot(tensor1, tensor2, axes=None, like=None): """Returns the tensor product of two tensors. In general ``axes`` specifies either the set of axes for both tensors that are contracted (with the first/second entry of ``axes`` giving all axis indices for the first/second tensor) or --- if it is an integer --- the number of last/first axes of the first/second tensor to contract over. There are some non-obvious special cases: * If both tensors are 0-dimensional, ``axes`` must be 0. and a 0-dimensional scalar is returned containing the simple product. * If both tensors are 1-dimensional and ``axes=0``, the outer product is returned. * Products between a non-0-dimensional and a 0-dimensional tensor are not supported in all interfaces. Args: tensor1 (tensor_like): input tensor tensor2 (tensor_like): input tensor axes (int or list[list[int]]): Axes to contract over, see detail description. Returns: tensor_like: the tensor product of the two input tensors """ tensor1, tensor2 = np.coerce([tensor1, tensor2], like=like) return np.tensordot(tensor1, tensor2, axes=axes, like=like) @multi_dispatch(argnum=[0], tensor_list=[0]) def get_trainable_indices(values, like=None): """Returns a set containing the trainable indices of a sequence of values. Args: values (Iterable[tensor_like]): Sequence of tensor-like objects to inspect Returns: set[int]: Set containing the indices of the trainable tensor-like objects within the input sequence. **Example** >>> from pennylane import numpy as pnp >>> def cost_fn(params): ... print("Trainable:", qml.math.get_trainable_indices(params)) ... return np.sum(np.sin(params[0] * params[1])) >>> values = [pnp.array([0.1, 0.2], requires_grad=True), ... pnp.array([0.5, 0.2], requires_grad=False)] >>> cost_fn(values) Trainable: {0} tensor(0.0899685, requires_grad=True) """ trainable_params = set() for idx, p in enumerate(values): if requires_grad(p, interface=like): trainable_params.add(idx) return trainable_params def ones_like(tensor, dtype=None): """Returns a tensor of all ones with the same shape and dtype as the input tensor. Args: tensor (tensor_like): input tensor dtype (str, np.dtype, None): The desired output datatype of the array. If not provided, the dtype of ``tensor`` is used. This argument can be any supported NumPy dtype representation, including a string (``"float64"``), a ``np.dtype`` object (``np.dtype("float64")``), or a dtype class (``np.float64``). If ``tensor`` is not a NumPy array, the **equivalent** dtype in the dispatched framework is used. Returns: tensor_like: an all-ones tensor with the same shape and size as ``tensor`` **Example** >>> x = torch.tensor([1., 2.]) >>> ones_like(x) tensor([1., 1.]) >>> y = tf.Variable([[0], [5]]) >>> ones_like(y, dtype=np.complex128) <tf.Tensor: shape=(2, 1), dtype=complex128, numpy= array([[1.+0.j], [1.+0.j]])> """ if dtype is not None: return cast(np.ones_like(tensor), dtype) return np.ones_like(tensor) @multi_dispatch(argnum=[0], tensor_list=[0]) def stack(values, axis=0, like=None): """Stack a sequence of tensors along the specified axis. .. warning:: Tensors that are incompatible (such as Torch and TensorFlow tensors) cannot both be present. Args: values (Sequence[tensor_like]): Sequence of tensor-like objects to stack. Each object in the sequence must have the same size in the given axis. axis (int): The axis along which the input tensors are stacked. ``axis=0`` corresponds to vertical stacking. Returns: tensor_like: The stacked array. The stacked array will have one additional dimension compared to the unstacked tensors. **Example** >>> x = tf.constant([0.6, 0.1, 0.6]) >>> y = tf.Variable([0.1, 0.2, 0.3]) >>> z = np.array([5., 8., 101.]) >>> stack([x, y, z]) <tf.Tensor: shape=(3, 3), dtype=float32, numpy= array([[6.00e-01, 1.00e-01, 6.00e-01], [1.00e-01, 2.00e-01, 3.00e-01], [5.00e+00, 8.00e+00, 1.01e+02]], dtype=float32)> """ values = np.coerce(values, like=like) return np.stack(values, axis=axis, like=like) def einsum(indices, *operands, like=None, optimize=None): """Evaluates the Einstein summation convention on the operands. Args: indices (str): Specifies the subscripts for summation as comma separated list of subscript labels. An implicit (classical Einstein summation) calculation is performed unless the explicit indicator ‘->’ is included as well as subscript labels of the precise output form. *operands (tuple[tensor_like]): The tensors for the operation. Returns: tensor_like: The calculation based on the Einstein summation convention. **Examples** >>> a = np.arange(25).reshape(5,5) >>> b = np.arange(5) >>> c = np.arange(6).reshape(2,3) Trace of a matrix: >>> qml.math.einsum('ii', a) 60 Extract the diagonal (requires explicit form): >>> qml.math.einsum('ii->i', a) array([ 0, 6, 12, 18, 24]) Sum over an axis (requires explicit form): >>> qml.math.einsum('ij->i', a) array([ 10, 35, 60, 85, 110]) Compute a matrix transpose, or reorder any number of axes: >>> np.einsum('ij->ji', c) array([[0, 3], [1, 4], [2, 5]]) Matrix vector multiplication: >>> np.einsum('ij,j', a, b) array([ 30, 80, 130, 180, 230]) """ if like is None: like = get_interface(*operands) operands = np.coerce(operands, like=like) if optimize is None or like == "torch": # torch einsum doesn't support the optimize keyword argument return np.einsum(indices, *operands, like=like) if like == "tensorflow": # Unpacking and casting necessary for higher order derivatives, # and avoiding implicit fp32 down-conversions. op1, op2 = operands op1 = array(op1, like=op1[0], dtype=op1[0].dtype) op2 = array(op2, like=op2[0], dtype=op2[0].dtype) return np.einsum(indices, op1, op2, like=like) return np.einsum(indices, *operands, like=like, optimize=optimize) def where(condition, x=None, y=None): r"""Returns elements chosen from x or y depending on a boolean tensor condition, or the indices of entries satisfying the condition. The input tensors ``condition``, ``x``, and ``y`` must all be broadcastable to the same shape. Args: condition (tensor_like[bool]): A boolean tensor. Where ``True`` , elements from ``x`` will be chosen, otherwise ``y``. If ``x`` and ``y`` are ``None`` the indices where ``condition==True`` holds will be returned. x (tensor_like): values from which to choose if the condition evaluates to ``True`` y (tensor_like): values from which to choose if the condition evaluates to ``False`` Returns: tensor_like or tuple[tensor_like]: If ``x is None`` and ``y is None``, a tensor or tuple of tensors with the indices where ``condition`` is ``True`` . Else, a tensor with elements from ``x`` where the ``condition`` is ``True``, and ``y`` otherwise. In this case, the output tensor has the same shape as the input tensors. **Example with three arguments** >>> a = torch.tensor([0.6, 0.23, 0.7, 1.5, 1.7], requires_grad=True) >>> b = torch.tensor([-1., -2., -3., -4., -5.], requires_grad=True) >>> math.where(a < 1, a, b) tensor([ 0.6000, 0.2300, 0.7000, -4.0000, -5.0000], grad_fn=<SWhereBackward>) .. warning:: The output format for ``x=None`` and ``y=None`` follows the respective interface and differs between TensorFlow and all other interfaces: For TensorFlow, the output is a tensor with shape ``(len(condition.shape), num_true)`` where ``num_true`` is the number of entries in ``condition`` that are ``True`` . For all other interfaces, the output is a tuple of tensor-like objects, with the ``j``\ th object indicating the ``j``\ th entries of all indices. Also see the examples below. **Example with single argument** For Torch, Autograd, JAX and NumPy, the output formatting is as follows: >>> a = [[0.6, 0.23, 1.7],[1.5, 0.7, -0.2]] >>> math.where(torch.tensor(a) < 1) (tensor([0, 0, 1, 1]), tensor([0, 1, 1, 2])) This is not a single tensor-like object but corresponds to the shape ``(2, 4)`` . For TensorFlow, on the other hand: >>> math.where(tf.constant(a) < 1) <tf.Tensor: shape=(2, 4), dtype=int64, numpy= array([[0, 0, 1, 1], [0, 1, 1, 2]])> Note that the number of dimensions of the output does *not* depend on the input shape, it is always two-dimensional. """ if x is None and y is None: interface = get_interface(condition) res = np.where(condition, like=interface) if interface == "tensorflow": return np.transpose(np.stack(res)) return res interface = get_interface(condition, x, y) res = np.where(condition, x, y, like=interface) return res @multi_dispatch(argnum=[0, 1]) def frobenius_inner_product(A, B, normalize=False, like=None): r"""Frobenius inner product between two matrices. .. math:: \langle A, B \rangle_F = \sum_{i,j=1}^n A_{ij} B_{ij} = \operatorname{tr} (A^T B) The Frobenius inner product is equivalent to the Hilbert-Schmidt inner product for matrices with real-valued entries. Args: A (tensor_like[float]): First matrix, assumed to be a square array. B (tensor_like[float]): Second matrix, assumed to be a square array. normalize (bool): If True, divide the inner product by the Frobenius norms of A and B. Returns: float: Frobenius inner product of A and B **Example** >>> A = np.random.random((3,3)) >>> B = np.random.random((3,3)) >>> qml.math.frobenius_inner_product(A, B) 3.091948202943376 """ A, B = np.coerce([A, B], like=like) inner_product = np.sum(A * B) if normalize: norm = np.sqrt(np.sum(A * A) * np.sum(B * B)) inner_product = inner_product / norm return inner_product @multi_dispatch(argnum=[1]) def scatter(indices, array, new_dims, like=None): """Scatters an array into a tensor of shape new_dims according to indices. This operation is similar to scatter_element_add, except that the tensor is zero-initialized. Calling scatter(indices, array, new_dims) is identical to calling scatter_element_add(np.zeros(new_dims), indices, array) Args: indices (tensor_like[int]): Indices to update array (tensor_like[float]): Values to assign to the new tensor new_dims (int or tuple[int]): The shape of the new tensor like (str): Manually chosen interface to dispatch to. Returns: tensor_like[float]: The tensor with the values modified the given indices. **Example** >>> indices = np.array([4, 3, 1, 7]) >>> updates = np.array([9, 10, 11, 12]) >>> shape = 8 >>> qml.math.scatter(indices, updates, shape) array([ 0, 11, 0, 10, 9, 0, 0, 12]) """ return np.scatter(indices, array, new_dims, like=like) @multi_dispatch(argnum=[0, 2]) def scatter_element_add(tensor, index, value, like=None): """In-place addition of a multidimensional value over various indices of a tensor. Args: tensor (tensor_like[float]): Tensor to add the value to index (tuple or list[tuple]): Indices to which to add the value value (float or tensor_like[float]): Value to add to ``tensor`` like (str): Manually chosen interface to dispatch to. Returns: tensor_like[float]: The tensor with the value added at the given indices. **Example** >>> tensor = torch.tensor([[0.1, 0.2, 0.3], [0.4, 0.5, 0.6]]) >>> index = (1, 2) >>> value = -3.1 >>> qml.math.scatter_element_add(tensor, index, value) tensor([[ 0.1000, 0.2000, 0.3000], [ 0.4000, 0.5000, -2.5000]]) If multiple indices are given, in the form of a list of tuples, the ``k`` th tuple is interpreted to contain the ``k`` th entry of all indices: >>> indices = [(1, 0), (2, 1)] # This will modify the entries (1, 2) and (0, 1) >>> values = torch.tensor([10, 20]) >>> qml.math.scatter_element_add(tensor, indices, values) tensor([[ 0.1000, 20.2000, 0.3000], [ 0.4000, 0.5000, 10.6000]]) """ if len(np.shape(tensor)) == 0 and index == (): return tensor + value return np.scatter_element_add(tensor, index, value, like=like) def unwrap(values, max_depth=None): """Unwrap a sequence of objects to NumPy arrays. Note that tensors on GPUs will automatically be copied to the CPU. Args: values (Sequence[tensor_like]): sequence of tensor-like objects to unwrap max_depth (int): Positive integer indicating the depth of unwrapping to perform for nested tensor-objects. This argument only applies when unwrapping Autograd ``ArrayBox`` objects. **Example** >>> values = [np.array([0.1, 0.2]), torch.tensor(0.1, dtype=torch.float64), torch.tensor([0.5, 0.2])] >>> math.unwrap(values) [array([0.1, 0.2]), 0.1, array([0.5, 0.2], dtype=float32)] This function will continue to work during backpropagation: >>> def cost_fn(params): ... unwrapped_params = math.unwrap(params) ... print("Unwrapped:", [(i, type(i)) for i in unwrapped_params]) ... return np.sum(np.sin(params)) >>> params = np.array([0.1, 0.2, 0.3]) >>> grad = autograd.grad(cost_fn)(params) Unwrapped: [(0.1, <class 'numpy.float64'>), (0.2, <class 'numpy.float64'>), (0.3, <class 'numpy.float64'>)] >>> print(grad) [0.99500417 0.98006658 0.95533649] """ def convert(val): if isinstance(val, (tuple, list)): return unwrap(val) new_val = ( np.to_numpy(val, max_depth=max_depth) if isinstance(val, ArrayBox) else np.to_numpy(val) ) return new_val.tolist() if isinstance(new_val, ndarray) and not new_val.shape else new_val if isinstance(values, (tuple, list)): return type(values)(convert(val) for val in values) return ( np.to_numpy(values, max_depth=max_depth) if isinstance(values, ArrayBox) else np.to_numpy(values) ) @multi_dispatch(argnum=[0, 1]) def add(*args, like=None, **kwargs): """Add arguments element-wise.""" if like == "scipy": return onp.add(*args, **kwargs) # Dispatch scipy add to numpy backed specifically. arg_interfaces = {get_interface(args[0]), get_interface(args[1])} # case of one torch tensor and one vanilla numpy array if like == "torch" and len(arg_interfaces) == 2: # In autoray 0.6.5, np.add dispatches to torch instead of # numpy if one parameter is a torch tensor and the other is # a numpy array. torch.add raises an Exception if one of the # arguments is a numpy array, so here we cast both arguments # to be tensors. dev = getattr(args[0], "device", None) or getattr(args[1], "device") arg0 = np.asarray(args[0], device=dev, like=like) arg1 = np.asarray(args[1], device=dev, like=like) return np.add(arg0, arg1, *args[2:], **kwargs) return np.add(*args, **kwargs, like=like) @multi_dispatch() def iscomplex(tensor, like=None): """Return True if the tensor has a non-zero complex component.""" if like == "tensorflow": import tensorflow as tf imag_tensor = tf.math.imag(tensor) return tf.math.count_nonzero(imag_tensor) > 0 if like == "torch": import torch if torch.is_complex(tensor): imag_tensor = torch.imag(tensor) return torch.count_nonzero(imag_tensor) > 0 return False return np.iscomplex(tensor) @multi_dispatch() def expm(tensor, like=None): """Compute the matrix exponential of an array :math:`e^{X}`. ..note:: This function is not differentiable with Autograd, as it relies on the scipy implementation. """ if like == "torch": return tensor.matrix_exp() if like == "jax": from jax.scipy.linalg import expm as jax_expm return jax_expm(tensor) if like == "tensorflow": import tensorflow as tf return tf.linalg.expm(tensor) from scipy.linalg import expm as scipy_expm return scipy_expm(tensor) @multi_dispatch() def norm(tensor, like=None, **kwargs): """Compute the norm of a tensor in each interface.""" if like == "jax": from jax.numpy.linalg import norm elif like == "tensorflow": from tensorflow import norm elif like == "torch": from torch.linalg import norm if "axis" in kwargs: axis_val = kwargs.pop("axis") kwargs["dim"] = axis_val elif ( like == "autograd" and kwargs.get("ord", None) is None and kwargs.get("axis", None) is None ): norm = _flat_autograd_norm else: from scipy.linalg import norm return norm(tensor, **kwargs) @multi_dispatch(argnum=[0]) def svd(tensor, like=None, **kwargs): r"""Compute the singular value decomposition of a tensor in each interface. The singular value decomposition for a matrix :math:`A` consist of three matrices :math:`S`, :math:`U` and :math:`V_h`, such that: .. math:: A = U \cdot Diag(S) \cdot V_h Args: tensor (tensor_like): input tensor compute_uv (bool): if ``True``, the full decomposition is returned Returns: :math:`S`, :math:`U` and :math:`V_h` or :math:`S`: full decomposition if ``compute_uv`` is ``True`` or ``None``, or only the singular values if ``compute_uv`` is ``False`` """ if like == "tensorflow": from tensorflow.linalg import adjoint, svd # Tensorflow results need some post-processing to keep it similar to other frameworks. if kwargs.get("compute_uv", True): S, U, V = svd(tensor, **kwargs) return U, S, adjoint(V) return svd(tensor, **kwargs) if like == "jax": from jax.numpy.linalg import svd elif like == "torch": # Torch is deprecating torch.svd() in favour of torch.linalg.svd(). # The new UI is slightly different and breaks the logic for the multi dispatching. # This small workaround restores the compute_uv control argument. if kwargs.get("compute_uv", True) is False: from torch.linalg import svdvals as svd else: from torch.linalg import svd if kwargs.get("compute_uv", None) is not None: kwargs.pop("compute_uv") else: from numpy.linalg import svd return svd(tensor, **kwargs) def _flat_autograd_norm(tensor, **kwargs): # pylint: disable=unused-argument """Helper function for computing the norm of an autograd tensor when the order or axes are not specified. This is used for differentiability.""" x = np.ravel(tensor) sq_norm = np.dot(x, np.conj(x)) return np.real(np.sqrt(sq_norm)) @multi_dispatch(argnum=[1]) def gammainc(m, t, like=None): r"""Return the lower incomplete Gamma function. The lower incomplete Gamma function is defined in scipy as .. math:: \gamma(m, t) = \frac{1}{\Gamma(m)} \int_{0}^{t} x^{m-1} e^{-x} dx, where :math:`\Gamma` denotes the Gamma function. Args: m (float): exponent of the incomplete Gamma function t (array[float]): upper limit of the incomplete Gamma function Returns: (array[float]): value of the incomplete Gamma function """ if like == "jax": from jax.scipy.special import gammainc return gammainc(m, t) if like == "autograd": from autograd.scipy.special import gammainc return gammainc(m, t) import scipy return scipy.special.gammainc(m, t) @multi_dispatch() def detach(tensor, like=None): """Detach a tensor from its trace and return just its numerical values. Args: tensor (tensor_like): Tensor to detach like (str): Manually chosen interface to dispatch to. Returns: tensor_like: A tensor in the same interface as the input tensor but with a stopped gradient. """ if like == "jax": import jax return jax.lax.stop_gradient(tensor) if like == "torch": return tensor.detach() if like == "tensorflow": import tensorflow as tf return tf.stop_gradient(tensor) if like == "autograd": return np.to_numpy(tensor) return tensor def jax_argnums_to_tape_trainable(qnode, argnums, program, args, kwargs): """This functions gets the tape parameters from the QNode construction given some argnums (only for Jax). The tape parameters are transformed to JVPTracer if they are from argnums. This function imitates the behaviour of Jax in order to mark trainable parameters. Args: qnode(qml.QNode): the quantum node. argnums(int, list[int]): the parameters that we want to set as trainable (on the QNode level). program(qml.transforms.core.TransformProgram): the transform program to be applied on the tape. Return: list[float, jax.JVPTracer]: List of parameters where the trainable one are `JVPTracer`. """ import jax with jax.core.new_main(jax.interpreters.ad.JVPTrace) as main: trace = jax.interpreters.ad.JVPTrace(main, 0) args_jvp = [ ( jax.interpreters.ad.JVPTracer(trace, arg, jax.numpy.zeros(arg.shape)) if i in argnums else arg ) for i, arg in enumerate(args) ] qnode.construct(args_jvp, kwargs) tape = qnode.qtape tapes, _ = program((tape,)) del trace return tuple(tape.get_parameters(trainable_only=False) for tape in tapes) @multi_dispatch(tensor_list=[1]) def set_index(array, idx, val, like=None): """Set the value at a specified index in an array. Calls ``array[idx]=val`` and returns the updated array unless JAX. Args: array (tensor_like): array to be modified idx (int, tuple): index to modify val (int, float): value to set Returns: a new copy of the array with the specified index updated to ``val``. Whether the original array is modified is interface-dependent. .. note:: TensorFlow EagerTensor does not support item assignment """ if like == "jax": from jax import numpy as jnp # ensure array is jax array (interface may be jax because of idx or val and not array) jax_array = jnp.array(array) return jax_array.at[idx].set(val) array[idx] = val return array
pennylane/pennylane/math/multi_dispatch.py/0
{ "file_path": "pennylane/pennylane/math/multi_dispatch.py", "repo_id": "pennylane", "token_count": 14818 }
57
# Copyright 2018-2021 Xanadu Quantum Technologies Inc. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # pylint: disable=protected-access """ This module contains the qml.var measurement. """ from collections.abc import Sequence from typing import Optional, Union import pennylane as qml from pennylane.operation import Operator from pennylane.wires import Wires from .measurements import SampleMeasurement, StateMeasurement, Variance from .mid_measure import MeasurementValue from .sample import SampleMP def var(op: Union[Operator, MeasurementValue]) -> "VarianceMP": r"""Variance of the supplied observable. Args: op (Union[Operator, MeasurementValue]): a quantum observable object. To get variances for mid-circuit measurements, ``op`` should be a ``MeasurementValue``. Returns: VarianceMP: Measurement process instance **Example:** .. code-block:: python3 dev = qml.device("default.qubit", wires=2) @qml.qnode(dev) def circuit(x): qml.RX(x, wires=0) qml.Hadamard(wires=1) qml.CNOT(wires=[0, 1]) return qml.var(qml.Y(0)) Executing this QNode: >>> circuit(0.5) 0.7701511529340698 """ if isinstance(op, MeasurementValue): return VarianceMP(obs=op) if isinstance(op, Sequence): raise ValueError( "qml.var does not support measuring sequences of measurements or observables" ) return VarianceMP(obs=op) class VarianceMP(SampleMeasurement, StateMeasurement): """Measurement process that computes the variance of the supplied observable. Please refer to :func:`pennylane.var` for detailed documentation. Args: obs (Union[.Operator, .MeasurementValue]): The observable that is to be measured as part of the measurement process. Not all measurement processes require observables (for example ``Probability``); this argument is optional. wires (.Wires): The wires the measurement process applies to. This can only be specified if an observable was not provided. eigvals (array): A flat array representing the eigenvalues of the measurement. This can only be specified if an observable was not provided. id (str): custom label given to a measurement instance, can be useful for some applications where the instance has to be identified """ return_type = Variance @property def numeric_type(self): return float def shape(self, shots: Optional[int] = None, num_device_wires: int = 0) -> tuple: return () def process_samples( self, samples: Sequence[complex], wire_order: Wires, shot_range: Optional[tuple[int, ...]] = None, bin_size: Optional[int] = None, ): # estimate the variance op = self.mv if self.mv is not None else self.obs with qml.queuing.QueuingManager.stop_recording(): samples = SampleMP( obs=op, eigvals=self._eigvals, wires=self.wires if self._eigvals is not None else None, ).process_samples( samples=samples, wire_order=wire_order, shot_range=shot_range, bin_size=bin_size ) # With broadcasting, we want to take the variance over axis 1, which is the -1st/-2nd with/ # without bin_size. Without broadcasting, axis 0 is the -1st/-2nd with/without bin_size axis = -1 if bin_size is None else -2 # TODO: do we need to squeeze here? Maybe remove with new return types return qml.math.squeeze(qml.math.var(samples, axis=axis)) def process_state(self, state: Sequence[complex], wire_order: Wires): # This also covers statistics for mid-circuit measurements manipulated using # arithmetic operators # we use ``wires`` instead of ``op`` because the observable was # already applied to the state with qml.queuing.QueuingManager.stop_recording(): prob = qml.probs(wires=self.wires).process_state(state=state, wire_order=wire_order) # In case of broadcasting, `prob` has two axes and these are a matrix-vector products return self._calculate_variance(prob) def process_counts(self, counts: dict, wire_order: Wires): with qml.QueuingManager.stop_recording(): probs = qml.probs(wires=self.wires).process_counts(counts=counts, wire_order=wire_order) return self._calculate_variance(probs) def _calculate_variance(self, probabilities): """ Calculate the variance of a set of probabilities. Args: probabilities (array): the probabilities of collapsing to eigen states """ eigvals = qml.math.asarray(self.eigvals(), dtype="float64") return qml.math.dot(probabilities, (eigvals**2)) - qml.math.dot(probabilities, eigvals) ** 2
pennylane/pennylane/measurements/var.py/0
{ "file_path": "pennylane/pennylane/measurements/var.py", "repo_id": "pennylane", "token_count": 2040 }
58
# Copyright 2018-2023 Xanadu Quantum Technologies Inc. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ This module contains the qml.ops.functions.check_validity function for determining whether or not an Operator class is correctly defined. """ import copy import pickle from string import ascii_lowercase import numpy as np import pennylane as qml from pennylane.operation import EigvalsUndefinedError def _assert_error_raised(func, error, failure_comment): def inner_func(*args, **kwargs): error_raised = False try: func(*args, **kwargs) except error: error_raised = True assert error_raised, failure_comment return inner_func def _check_decomposition(op, skip_wire_mapping): """Checks involving the decomposition.""" if op.has_decomposition: decomp = op.decomposition() try: compute_decomp = type(op).compute_decomposition( *op.data, wires=op.wires, **op.hyperparameters ) except (qml.operation.DecompositionUndefinedError, TypeError): # sometimes decomposition is defined but not compute_decomposition # Also sometimes compute_decomposition can have a different signature compute_decomp = decomp with qml.queuing.AnnotatedQueue() as queued_decomp: op.decomposition() processed_queue = qml.tape.QuantumTape.from_queue(queued_decomp) assert isinstance(decomp, list), "decomposition must be a list" assert isinstance(compute_decomp, list), "decomposition must be a list" assert op.__class__ not in [ decomp_op.__class__ for decomp_op in decomp ], "an operator should not be included in its own decomposition" for o1, o2, o3 in zip(decomp, compute_decomp, processed_queue): assert o1 == o2, "decomposition must match compute_decomposition" assert o1 == o3, "decomposition must match queued operations" assert isinstance(o1, qml.operation.Operator), "decomposition must contain operators" if skip_wire_mapping: return # Check that mapping wires transitions to the decomposition wire_map = {w: ascii_lowercase[i] for i, w in enumerate(op.wires)} mapped_op = op.map_wires(wire_map) # calling `map_wires` on a Controlled operator generates a new `op` from the controls and # base, so may return a different class of operator. We only compare decomps of `op` and # `mapped_op` if `mapped_op` **has** a decomposition. # see MultiControlledX([0, 1]) and CNOT([0, 1]) as an example if mapped_op.has_decomposition: mapped_decomp = mapped_op.decomposition() orig_decomp = op.decomposition() for mapped_op, orig_op in zip(mapped_decomp, orig_decomp): assert ( mapped_op.wires == qml.map_wires(orig_op, wire_map).wires ), "Operators in decomposition of wire-mapped operator must have mapped wires." else: failure_comment = "If has_decomposition is False, then decomposition must raise a ``DecompositionUndefinedError``." _assert_error_raised( op.decomposition, qml.operation.DecompositionUndefinedError, failure_comment=failure_comment, )() _assert_error_raised( op.compute_decomposition, qml.operation.DecompositionUndefinedError, failure_comment=failure_comment, )(*op.data, wires=op.wires, **op.hyperparameters) def _check_matrix(op): """Check that if the operation says it has a matrix, it does. Otherwise a ``MatrixUndefinedError`` should be raised.""" if op.has_matrix: mat = op.matrix() assert isinstance(mat, qml.typing.TensorLike), "matrix must be a TensorLike" l = 2 ** len(op.wires) failure_comment = f"matrix must be two dimensional with shape ({l}, {l})" assert qml.math.shape(mat) == (l, l), failure_comment else: failure_comment = ( "If has_matrix is False, the matrix method must raise a ``MatrixUndefinedError``." ) _assert_error_raised( op.matrix, qml.operation.MatrixUndefinedError, failure_comment=failure_comment )() def _check_matrix_matches_decomp(op): """Check that if both the matrix and decomposition are defined, they match.""" if op.has_matrix and op.has_decomposition: mat = op.matrix() decomp_mat = qml.matrix(qml.tape.QuantumScript(op.decomposition()), wire_order=op.wires) failure_comment = ( f"matrix and matrix from decomposition must match. Got \n{mat}\n\n {decomp_mat}" ) assert qml.math.allclose(mat, decomp_mat), failure_comment def _check_eigendecomposition(op): """Checks involving diagonalizing gates and eigenvalues.""" if op.has_diagonalizing_gates: dg = op.diagonalizing_gates() try: compute_dg = type(op).compute_diagonalizing_gates( *op.data, wires=op.wires, **op.hyperparameters ) except (qml.operation.DiagGatesUndefinedError, TypeError): # sometimes diagonalizing gates is defined but not compute_diagonalizing_gates # compute_diagonalizing_gates might also have a different call signature compute_dg = dg for op1, op2 in zip(dg, compute_dg): assert op1 == op2, "diagonalizing_gates and compute_diagonalizing_gates must match" else: failure_comment = "If has_diagonalizing_gates is False, diagonalizing_gates must raise a DiagGatesUndefinedError" _assert_error_raised( op.diagonalizing_gates, qml.operation.DiagGatesUndefinedError, failure_comment )() try: eg = op.eigvals() except EigvalsUndefinedError: eg = None has_eigvals = True try: compute_eg = type(op).compute_eigvals(*op.data, **op.hyperparameters) except EigvalsUndefinedError: compute_eg = eg has_eigvals = False if has_eigvals: assert qml.math.allclose(eg, compute_eg), "eigvals and compute_eigvals must match" if has_eigvals and op.has_diagonalizing_gates: dg = qml.prod(*dg[::-1]) if len(dg) > 0 else qml.Identity(op.wires) eg = qml.QubitUnitary(np.diag(eg), wires=op.wires) decomp = qml.prod(qml.adjoint(dg), eg, dg) decomp_mat = qml.matrix(decomp) original_mat = qml.matrix(op) failure_comment = f"eigenvalues and diagonalizing gates must be able to reproduce the original operator. Got \n{decomp_mat}\n\n{original_mat}" assert qml.math.allclose(decomp_mat, original_mat), failure_comment def _check_copy(op): """Check that copies and deep copies give identical objects.""" copied_op = copy.copy(op) assert qml.equal(copied_op, op), "copied op must be equal with qml.equal" assert copied_op == op, "copied op must be equivalent to original operation" assert copied_op is not op, "copied op must be a separate instance from original operaiton" assert qml.equal(copy.deepcopy(op), op), "deep copied op must also be equal" # pylint: disable=import-outside-toplevel, protected-access def _check_pytree(op): """Check that the operator is a pytree.""" data, metadata = op._flatten() try: assert hash(metadata), "metadata must be hashable" except Exception as e: raise AssertionError( f"metadata output from _flatten must be hashable. Got metadata {metadata}" ) from e try: new_op = type(op)._unflatten(data, metadata) except Exception as e: message = ( f"{type(op).__name__}._unflatten must be able to reproduce the original operation from " f"{data} and {metadata}. You may need to override either the _unflatten or _flatten method. " f"\nFor local testing, try type(op)._unflatten(*op._flatten())" ) raise AssertionError(message) from e assert op == new_op, "metadata and data must be able to reproduce the original operation" try: import jax except ImportError: return leaves, struct = jax.tree_util.tree_flatten(op) unflattened_op = jax.tree_util.tree_unflatten(struct, leaves) assert unflattened_op == op, f"op must be a valid pytree. Got {unflattened_op} instead of {op}." for d1, d2 in zip(op.data, leaves): assert qml.math.allclose( d1, d2 ), f"data must be the terminal leaves of the pytree. Got {d1}, {d2}" def _check_capture(op): try: import jax except ImportError: return if not all(isinstance(w, int) for w in op.wires): return qml.capture.enable() try: jaxpr = jax.make_jaxpr(lambda obj: obj)(op) data, _ = jax.tree_util.tree_flatten(op) new_op = jax.core.eval_jaxpr(jaxpr.jaxpr, jaxpr.consts, *data)[0] assert op == new_op except Exception as e: raise ValueError( ( "The capture of the operation into jaxpr failed somehow." " This capture mechanism is currently experimental and not a core" " requirement, but will be necessary in the future." " Please see the capture module documentation for more information." ) ) from e finally: qml.capture.disable() def _check_pickle(op): """Check that an operation can be dumped and reloaded with pickle.""" pickled = pickle.dumps(op) unpickled = pickle.loads(pickled) assert unpickled == op, "operation must be able to be pickled and unpickled" # pylint: disable=no-member def _check_bind_new_parameters(op): """Check that bind new parameters can create a new op with different data.""" new_data = [d * 0.0 for d in op.data] new_data_op = qml.ops.functions.bind_new_parameters(op, new_data) failure_comment = "bind_new_parameters must be able to update the operator with new data." for d1, d2 in zip(new_data_op.data, new_data): assert qml.math.allclose(d1, d2), failure_comment def _check_wires(op, skip_wire_mapping): """Check that wires are a ``Wires`` class and can be mapped.""" assert isinstance(op.wires, qml.wires.Wires), "wires must be a wires instance" if skip_wire_mapping: return wire_map = {w: ascii_lowercase[i] for i, w in enumerate(op.wires)} mapped_op = op.map_wires(wire_map) new_wires = qml.wires.Wires(list(ascii_lowercase[: len(op.wires)])) assert mapped_op.wires == new_wires, "wires must be mappable with map_wires" def assert_valid(op: qml.operation.Operator, skip_pickle=False, skip_wire_mapping=False) -> None: """Runs basic validation checks on an :class:`~.operation.Operator` to make sure it has been correctly defined. Args: op (.Operator): an operator instance to validate Keyword Args: skip_pickle=False : If ``True``, pickling tests are not run. Set to ``True`` when testing a locally defined operator, as pickle cannot handle local objects **Examples:** .. code-block:: python class MyOp(qml.operation.Operator): def __init__(self, data, wires): self.data = data super().__init__(wires=wires) op = MyOp(qml.numpy.array(0.5), wires=0) .. code-block:: >>> assert_valid(op) AssertionError: op.data must be a tuple .. code-block:: python class MyOp(qml.operation.Operator): def __init__(self, wires): self.hyperparameters["unhashable_list"] = [] super().__init__(wires=wires) op = MyOp(wires = 0) assert_valid(op) .. code-block:: ValueError: metadata output from _flatten must be hashable. This also applies to hyperparameters """ assert isinstance(op.data, tuple), "op.data must be a tuple" assert isinstance(op.parameters, list), "op.parameters must be a list" for d, p in zip(op.data, op.parameters): assert isinstance(d, qml.typing.TensorLike), "each data element must be tensorlike" assert qml.math.allclose(d, p), "data and parameters must match." if len(op.wires) <= 26: _check_wires(op, skip_wire_mapping) _check_copy(op) _check_pytree(op) if not skip_pickle: _check_pickle(op) _check_bind_new_parameters(op) _check_decomposition(op, skip_wire_mapping) _check_matrix(op) _check_matrix_matches_decomp(op) _check_eigendecomposition(op) _check_capture(op)
pennylane/pennylane/ops/functions/assert_valid.py/0
{ "file_path": "pennylane/pennylane/ops/functions/assert_valid.py", "repo_id": "pennylane", "token_count": 5383 }
59
# Copyright 2018-2021 Xanadu Quantum Technologies Inc. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ This submodule contains the discrete-variable quantum operations that do not depend on any parameters. """ # pylint:disable=abstract-method,arguments-differ,protected-access,invalid-overridden-method, no-member from copy import copy from typing import Optional import pennylane as qml from pennylane.operation import AnyWires, Operation from pennylane.wires import Wires # pylint: disable=unused-import class Barrier(Operation): r"""Barrier(wires) The Barrier operator, used to separate the compilation process into blocks or as a visual tool. **Details:** * Number of wires: AnyWires * Number of parameters: 0 Args: only_visual (bool): True if we do not want it to have an impact on the compilation process. Default is False. wires (Sequence[int] or int): the wires the operation acts on """ num_params = 0 """int: Number of trainable parameters that the operator depends on.""" num_wires = AnyWires par_domain = None def __init__(self, wires=Wires([]), only_visual=False, id=None): self.only_visual = only_visual self.hyperparameters["only_visual"] = only_visual super().__init__(wires=wires, id=id) @staticmethod def compute_decomposition(wires, only_visual=False): # pylint: disable=unused-argument r"""Representation of the operator as a product of other operators (static method). .. math:: O = O_1 O_2 \dots O_n. .. seealso:: :meth:`~.Barrier.decomposition`. ``Barrier`` decomposes into an empty list for all arguments. Args: wires (Iterable, Wires): wires that the operator acts on only_visual (Bool): True if we do not want it to have an impact on the compilation process. Default is False. Returns: list: decomposition of the operator **Example:** >>> print(qml.Barrier.compute_decomposition(0)) [] """ return [] def label(self, decimals=None, base_label=None, cache=None): return "||" def _controlled(self, _): return copy(self).queue() def adjoint(self): return copy(self) def pow(self, z): return [copy(self)] def simplify(self): if self.only_visual: if len(self.wires) == 1: return qml.Identity(self.wires[0]) return qml.prod(*(qml.Identity(w) for w in self.wires)) return self class WireCut(Operation): r"""WireCut(wires) The wire cut operation, used to manually mark locations for wire cuts. .. note:: This operation is designed for use as part of the circuit cutting workflow. Check out the :func:`qml.cut_circuit() <pennylane.cut_circuit>` transform for more details. **Details:** * Number of wires: AnyWires * Number of parameters: 0 Args: wires (Sequence[int] or int): the wires the operation acts on """ num_params = 0 num_wires = AnyWires grad_method = None def __init__(self, *params, wires=None, id=None): if wires == []: raise ValueError( f"{self.__class__.__name__}: wrong number of wires. " f"At least one wire has to be given." ) super().__init__(*params, wires=wires, id=id) @staticmethod def compute_decomposition(wires): # pylint: disable=unused-argument r"""Representation of the operator as a product of other operators (static method). Since this operator is a placeholder inside a circuit, it decomposes into an empty list. Args: wires (Any, Wires): Wire that the operator acts on. Returns: list[Operator]: decomposition of the operator **Example:** >>> print(qml.WireCut.compute_decomposition(0)) [] """ return [] def label(self, decimals=None, base_label=None, cache=None): return "//" def adjoint(self): return WireCut(wires=self.wires) def pow(self, z): return [copy(self)] class Snapshot(Operation): r""" The Snapshot operation saves the internal execution state of the quantum function at a specific point in the execution pipeline. As such, it is a pseudo operation with no effect on the quantum state. Arbitrary measurements are supported in snapshots via the keyword argument ``measurement``. **Details:** * Number of wires: AnyWires * Number of parameters: 0 Args: tag (str or None): An optional custom tag for the snapshot, used to index it in the snapshots dictionary. measurement (MeasurementProcess or None): An optional argument to record arbitrary measurements during execution. If None, the measurement defaults to `qml.state` on the available wires. **Example** .. code-block:: python3 dev = qml.device("default.qubit", wires=2) @qml.qnode(dev, interface=None) def circuit(): qml.Snapshot(measurement=qml.expval(qml.Z(0))) qml.Hadamard(wires=0) qml.Snapshot("very_important_state") qml.CNOT(wires=[0, 1]) qml.Snapshot() return qml.expval(qml.X(0)) >>> qml.snapshots(circuit)() {0: 1.0, 'very_important_state': array([0.70710678+0.j, 0. +0.j, 0.70710678+0.j, 0. +0.j]), 2: array([0.70710678+0.j, 0. +0.j, 0. +0.j, 0.70710678+0.j]), 'execution_results': 0.0} .. seealso:: :func:`~.snapshots` """ num_wires = AnyWires num_params = 0 grad_method = None @classmethod def _primitive_bind_call(cls, tag=None, measurement=None): if measurement is None: return cls._primitive.bind(measurement=measurement, tag=tag) return cls._primitive.bind(measurement, tag=tag) def __init__(self, tag: Optional[str] = None, measurement=None): if tag and not isinstance(tag, str): raise ValueError("Snapshot tags can only be of type 'str'") self.tag = tag if measurement is None: measurement = qml.state() if isinstance(measurement, qml.measurements.MeasurementProcess): if isinstance(measurement, qml.measurements.MidMeasureMP): raise ValueError("Mid-circuit measurements can not be used in snapshots.") qml.queuing.QueuingManager.remove(measurement) else: raise ValueError( f"The measurement {measurement.__class__.__name__} is not supported as it is not " f"an instance of {qml.measurements.MeasurementProcess}" ) self.hyperparameters["measurement"] = measurement super().__init__(wires=[]) def label(self, decimals=None, base_label=None, cache=None): return "|Snap|" def _flatten(self): return (self.hyperparameters["measurement"],), (self.tag,) @classmethod def _unflatten(cls, data, metadata): return cls(tag=metadata[0], measurement=data[0]) # pylint: disable=W0613 @staticmethod def compute_decomposition(*params, wires=None, **hyperparameters): return [] def _controlled(self, _): return Snapshot(tag=self.tag, measurement=self.hyperparameters["measurement"]) def adjoint(self): return Snapshot(tag=self.tag, measurement=self.hyperparameters["measurement"]) # Since measurements are captured as variables in plxpr with the capture module, # the measurement is treated as a traceable argument. # This step is mandatory for fixing the order of arguments overwritten by ``Snapshot._primitive_bind_call``. if Snapshot._primitive: # pylint: disable=protected-access @Snapshot._primitive.def_impl # pylint: disable=protected-access def _(measurement, tag=None): return type.__call__(Snapshot, tag=tag, measurement=measurement)
pennylane/pennylane/ops/meta.py/0
{ "file_path": "pennylane/pennylane/ops/meta.py", "repo_id": "pennylane", "token_count": 3316 }
60
# Copyright 2018-2022 Xanadu Quantum Technologies Inc. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ This file contains the implementation of the Prod class which contains logic for computing the product between operations. """ import itertools import warnings from copy import copy from functools import reduce, wraps from itertools import combinations from typing import Union from scipy.sparse import kron as sparse_kron import pennylane as qml from pennylane import math from pennylane.operation import Operator, convert_to_opmath from pennylane.ops.op_math.pow import Pow from pennylane.ops.op_math.sprod import SProd from pennylane.ops.op_math.sum import Sum from pennylane.ops.qubit.non_parametric_ops import PauliX, PauliY, PauliZ from pennylane.queuing import QueuingManager from pennylane.typing import TensorLike from .composite import CompositeOp MAX_NUM_WIRES_KRON_PRODUCT = 9 """The maximum number of wires up to which using ``math.kron`` is faster than ``math.dot`` for computing the sparse matrix representation.""" def prod(*ops, id=None, lazy=True): """Construct an operator which represents the generalized product of the operators provided. The generalized product operation represents both the tensor product as well as matrix composition. This can be resolved naturally from the wires that the given operators act on. Args: *ops (Union[tuple[~.operation.Operator], Callable]): The operators we would like to multiply. Alternatively, a single qfunc that queues operators can be passed to this function. Keyword Args: id (str or None): id for the product operator. Default is None. lazy=True (bool): If ``lazy=False``, a simplification will be performed such that when any of the operators is already a product operator, its operands will be used instead. Returns: ~ops.op_math.Prod: the operator representing the product. .. note:: This operator supports batched operands: >>> op = qml.prod(qml.RX(np.array([1, 2, 3]), wires=0), qml.X(1)) >>> op.matrix().shape (3, 4, 4) But it doesn't support batching of operators: >>> op = qml.prod(np.array([qml.RX(0.5, 0), qml.RZ(0.3, 0)]), qml.Z(0)) AttributeError: 'numpy.ndarray' object has no attribute 'wires' .. seealso:: :class:`~.ops.op_math.Prod` **Example** >>> prod_op = prod(qml.X(0), qml.Z(0)) >>> prod_op X(0) @ Z(0) >>> prod_op.matrix() array([[ 0, -1], [ 1, 0]]) >>> prod_op.simplify() -1j * Y(0) >>> prod_op.terms() ([-1j], [Y(0)]) You can also create a prod operator by passing a qfunc to prod, like the following: >>> def qfunc(x): ... qml.RX(x, 0) ... qml.CNOT([0, 1]) >>> prod_op = prod(qfunc)(1.1) >>> prod_op CNOT(wires=[0, 1]) @ RX(1.1, wires=[0]) """ ops = tuple(convert_to_opmath(op) for op in ops) if len(ops) == 1: if isinstance(ops[0], qml.operation.Operator): return ops[0] fn = ops[0] if not callable(fn): raise TypeError(f"Unexpected argument of type {type(fn).__name__} passed to qml.prod") @wraps(fn) def wrapper(*args, **kwargs): qs = qml.tape.make_qscript(fn)(*args, **kwargs) if len(qs.operations) == 1: if qml.QueuingManager.recording(): qml.apply(qs[0]) return qs[0] return prod(*qs.operations[::-1], id=id, lazy=lazy) return wrapper if lazy: return Prod(*ops, id=id) ops_simp = Prod( *itertools.chain.from_iterable([op if isinstance(op, Prod) else [op] for op in ops]), id=id, ) for op in ops: QueuingManager.remove(op) return ops_simp class Prod(CompositeOp): r"""Symbolic operator representing the product of operators. Args: *factors (tuple[~.operation.Operator]): a tuple of operators which will be multiplied together. Keyword Args: id (str or None): id for the product operator. Default is None. .. seealso:: :func:`~.ops.op_math.prod` **Example** >>> prod_op = Prod(qml.X(0), qml.PauliZ(1)) >>> prod_op X(0) @ Z(1) >>> qml.matrix(prod_op, wire_order=prod_op.wires) array([[ 0, 0, 1, 0], [ 0, 0, 0, -1], [ 1, 0, 0, 0], [ 0, -1, 0, 0]]) >>> prod_op.terms() ([1.0], [Z(1) @ X(0)]) .. note:: When a Prod operator is applied in a circuit, its factors are applied in the reverse order. (i.e ``Prod(op1, op2)`` corresponds to :math:`\hat{op}_{1}\cdot\hat{op}_{2}` which indicates first applying :math:`\hat{op}_{2}` then :math:`\hat{op}_{1}` in the circuit). We can see this in the decomposition of the operator. >>> op = Prod(qml.X(0), qml.Z(1)) >>> op.decomposition() [Z(1), X(0)] .. details:: :title: Usage Details The Prod operator represents both matrix composition and tensor products between operators. >>> prod_op = Prod(qml.RZ(1.23, wires=0), qml.X(0), qml.Z(1)) >>> prod_op.matrix() array([[ 0. +0.j , 0. +0.j , 0.81677345-0.57695852j, 0. +0.j ], [ 0. +0.j , 0. +0.j , 0. +0.j , -0.81677345+0.57695852j], [ 0.81677345+0.57695852j, 0. +0.j , 0. +0.j , 0. +0.j ], [ 0. +0.j , -0.81677345-0.57695852j, 0. +0.j , 0. +0.j ]]) The Prod operation can be used inside a `qnode` as an operation which, if parameterized, can be differentiated. .. code-block:: python dev = qml.device("default.qubit", wires=3) @qml.qnode(dev) def circuit(theta): qml.prod(qml.Z(0), qml.RX(theta, 1)) return qml.expval(qml.Z(1)) >>> par = np.array(1.23, requires_grad=True) >>> circuit(par) tensor(0.33423773, requires_grad=True) >>> qml.grad(circuit)(par) tensor(-0.9424888, requires_grad=True) The Prod operation can also be measured as an observable. If the circuit is parameterized, then we can also differentiate through the product observable. .. code-block:: python prod_op = Prod(qml.Z(0), qml.Hadamard(wires=1)) dev = qml.device("default.qubit", wires=2) @qml.qnode(dev) def circuit(weights): qml.RX(weights[0], wires=0) return qml.expval(prod_op) >>> weights = np.array([0.1], requires_grad=True) >>> qml.grad(circuit)(weights) array([-0.07059289]) Note that the :meth:`~Prod.terms` method always simplifies and flattens the operands. >>> op = qml.ops.Prod(qml.X(0), qml.sum(qml.Y(0), qml.Z(1))) >>> op.terms() ([1j, 1.0], [Z(0), Z(1) @ X(0)]) """ _op_symbol = "@" _math_op = math.prod @property def is_hermitian(self): """Check if the product operator is hermitian. Note, this check is not exhaustive. There can be hermitian operators for which this check yields false, which ARE hermitian. So a false result only implies a more explicit check must be performed. """ for o1, o2 in combinations(self.operands, r=2): if qml.wires.Wires.shared_wires([o1.wires, o2.wires]): return False return all(op.is_hermitian for op in self) # pylint: disable=arguments-renamed, invalid-overridden-method @property def has_decomposition(self): return True @property def obs(self): r"""Access the operands of a ``Prod`` instance""" # This is temporary property to smoothen the transition to the new operator arithmetic system. # In particular, the __matmul__ (@ python operator) method between operators now generates Prod instead of Tensor instances. warnings.warn( "Accessing the terms of a tensor product operator via op.obs is deprecated, please use op.operands instead.", qml.PennyLaneDeprecationWarning, ) return self.operands def decomposition(self): r"""Decomposition of the product operator is given by each factor applied in succession. Note that the decomposition is the list of factors returned in reversed order. This is to support the intuition that when we write :math:`\hat{O} = \hat{A} \cdot \hat{B}` it is implied that :math:`\hat{B}` is applied to the state before :math:`\hat{A}` in the quantum circuit. """ if qml.queuing.QueuingManager.recording(): return [qml.apply(op) for op in self[::-1]] return list(self[::-1]) def matrix(self, wire_order=None): """Representation of the operator as a matrix in the computational basis.""" if self.pauli_rep: return self.pauli_rep.to_mat(wire_order=wire_order or self.wires) mats: list[TensorLike] = [] batched: list[bool] = [] # batched[i] tells if mats[i] is batched or not for ops in self.overlapping_ops: gen = ( ( (qml.matrix(op) if isinstance(op, qml.ops.Hamiltonian) else op.matrix()), op.wires, ) for op in ops ) reduced_mat, _ = math.reduce_matrices(gen, reduce_func=math.matmul) if self.batch_size is not None: batched.append(any(op.batch_size is not None for op in ops)) else: batched.append(False) mats.append(reduced_mat) if self.batch_size is None: full_mat = reduce(math.kron, mats) else: full_mat = qml.math.stack( [ reduce(math.kron, [m[i] if b else m for m, b in zip(mats, batched)]) for i in range(self.batch_size) ] ) return math.expand_matrix(full_mat, self.wires, wire_order=wire_order) def sparse_matrix(self, wire_order=None): if self.pauli_rep: # Get the sparse matrix from the PauliSentence representation return self.pauli_rep.to_mat(wire_order=wire_order or self.wires, format="csr") if self.has_overlapping_wires or self.num_wires > MAX_NUM_WIRES_KRON_PRODUCT: gen = ((op.sparse_matrix(), op.wires) for op in self) reduced_mat, prod_wires = math.reduce_matrices(gen, reduce_func=math.dot) wire_order = wire_order or self.wires return math.expand_matrix(reduced_mat, prod_wires, wire_order=wire_order) mats = (op.sparse_matrix() for op in self) full_mat = reduce(sparse_kron, mats) return math.expand_matrix(full_mat, self.wires, wire_order=wire_order) # pylint: disable=protected-access @property def _queue_category(self): """Used for sorting objects into their respective lists in `QuantumTape` objects. This property is a temporary solution that should not exist long-term and should not be used outside of ``QuantumTape._process_queue``. Options are: * `"_ops"` * `"_measurements"` * `None` Returns (str or None): "_ops" if the _queue_catagory of all factors is "_ops", else None. """ return "_ops" if all(op._queue_category == "_ops" for op in self) else None # pylint: disable=arguments-renamed, invalid-overridden-method @property def has_adjoint(self): return True def adjoint(self): return Prod(*(qml.adjoint(factor) for factor in self[::-1])) @property def arithmetic_depth(self) -> int: return 1 + max(factor.arithmetic_depth for factor in self) def _build_pauli_rep(self): """PauliSentence representation of the Product of operations.""" if all(operand_pauli_reps := [op.pauli_rep for op in self.operands]): return reduce(lambda a, b: a @ b, operand_pauli_reps) return None def _simplify_factors(self, factors: tuple[Operator]) -> tuple[complex, Operator]: """Reduces the depth of nested factors and groups identical factors. Returns: Tuple[complex, List[~.operation.Operator]: tuple containing the global phase and a list of the simplified factors """ new_factors = _ProductFactorsGrouping() for factor in factors: simplified_factor = factor.simplify() new_factors.add(factor=simplified_factor) new_factors.remove_factors(wires=self.wires) return new_factors.global_phase, new_factors.factors def simplify(self) -> Union["Prod", Sum]: r""" Transforms any nested Prod instance into the form :math:`\sum c_i O_i` where :math:`c_i` is a scalar coefficient and :math:`O_i` is a single PL operator or pure product of single PL operators. """ # try using pauli_rep: if pr := self.pauli_rep: pr.simplify() return pr.operation(wire_order=self.wires) global_phase, factors = self._simplify_factors(factors=self.operands) factors = list(itertools.product(*factors)) if len(factors) == 1: factor = factors[0] if len(factor) == 0: op = qml.Identity(self.wires) else: op = factor[0] if len(factor) == 1 else Prod(*factor) return op if global_phase == 1 else qml.s_prod(global_phase, op) factors = [Prod(*factor).simplify() if len(factor) > 1 else factor[0] for factor in factors] op = Sum(*factors).simplify() return op if global_phase == 1 else qml.s_prod(global_phase, op).simplify() @classmethod def _sort(cls, op_list, wire_map: dict = None) -> list[Operator]: """Insertion sort algorithm that sorts a list of product factors by their wire indices, taking into account the operator commutivity. Args: op_list (List[.Operator]): list of operators to be sorted wire_map (dict): Dictionary containing the wire values as keys and its indexes as values. Defaults to None. Returns: List[.Operator]: sorted list of operators """ if isinstance(op_list, tuple): op_list = list(op_list) for i in range(1, len(op_list)): key_op = op_list[i] j = i - 1 while j >= 0 and _swappable_ops(op1=op_list[j], op2=key_op, wire_map=wire_map): op_list[j + 1] = op_list[j] j -= 1 op_list[j + 1] = key_op return op_list def terms(self): r"""Representation of the operator as a linear combination of other operators. .. math:: O = \sum_i c_i O_i A ``TermsUndefinedError`` is raised if no representation by terms is defined. Returns: tuple[list[tensor_like or float], list[.Operation]]: list of coefficients :math:`c_i` and list of operations :math:`O_i` **Example** >>> op = X(0) @ (0.5 * X(1) + X(2)) >>> op.terms() ([0.5, 1.0], [X(1) @ X(0), X(2) @ X(0)]) """ # try using pauli_rep: if pr := self.pauli_rep: with qml.QueuingManager.stop_recording(): ops = [pauli.operation() for pauli in pr.keys()] return list(pr.values()), ops with qml.QueuingManager.stop_recording(): global_phase, factors = self._simplify_factors(factors=self.operands) factors = list(itertools.product(*factors)) factors = [ Prod(*factor).simplify() if len(factor) > 1 else factor[0] for factor in factors ] # harvest coeffs and ops coeffs = [] ops = [] for factor in factors: if isinstance(factor, SProd): coeffs.append(global_phase * factor.scalar) ops.append(factor.base) else: coeffs.append(global_phase) ops.append(factor) return coeffs, ops @property def coeffs(self): r""" Scalar coefficients of the operator when flattened out. This is a deprecated attribute, please use :meth:`~Prod.terms` instead. .. seealso:: :attr:`~Prod.ops`, :class:`~Prod.pauli_rep`""" warnings.warn( "Prod.coeffs is deprecated and will be removed in future releases. You can access both (coeffs, ops) via op.terms(). Also consider op.operands.", qml.PennyLaneDeprecationWarning, ) coeffs, _ = self.terms() return coeffs @property def ops(self): r""" Operator terms without scalar coefficients of the operator when flattened out. This is a deprecated attribute, please use :meth:`~Prod.terms` instead. .. seealso:: :attr:`~Prod.coeffs`, :class:`~Prod.pauli_rep`""" warnings.warn( "Prod.ops is deprecated and will be removed in future releases. You can access both (coeffs, ops) via op.terms() Also consider op.operands.", qml.PennyLaneDeprecationWarning, ) _, ops = self.terms() return ops def _swappable_ops(op1, op2, wire_map: dict = None) -> bool: """Boolean expression that indicates if op1 and op2 don't have intersecting wires and if they should be swapped when sorting them by wire values. Args: op1 (.Operator): First operator. op2 (.Operator): Second operator. wire_map (dict): Dictionary containing the wire values as keys and its indexes as values. Defaults to None. Returns: bool: True if operators should be swapped, False otherwise. """ # one is broadcasted onto all wires. if not op1.wires: return True if not op2.wires: return False wires1 = op1.wires wires2 = op2.wires if wire_map is not None: wires1 = wires1.map(wire_map) wires2 = wires2.map(wire_map) wires1 = set(wires1) wires2 = set(wires2) # compare strings of wire labels so that we can compare arbitrary wire labels like 0 and "a" return False if wires1 & wires2 else str(wires1.pop()) > str(wires2.pop()) class _ProductFactorsGrouping: """Utils class used for grouping identical product factors.""" _identity_map = { "Identity": (1.0, "Identity"), "PauliX": (1.0, "PauliX"), "PauliY": (1.0, "PauliY"), "PauliZ": (1.0, "PauliZ"), } _x_map = { "Identity": (1.0, "PauliX"), "PauliX": (1.0, "Identity"), "PauliY": (1.0j, "PauliZ"), "PauliZ": (-1.0j, "PauliY"), } _y_map = { "Identity": (1.0, "PauliY"), "PauliX": (-1.0j, "PauliZ"), "PauliY": (1.0, "Identity"), "PauliZ": (1.0j, "PauliX"), } _z_map = { "Identity": (1.0, "PauliZ"), "PauliX": (1.0j, "PauliY"), "PauliY": (-1.0j, "PauliX"), "PauliZ": (1.0, "Identity"), } _pauli_mult = {"Identity": _identity_map, "PauliX": _x_map, "PauliY": _y_map, "PauliZ": _z_map} _paulis = {"PauliX": PauliX, "PauliY": PauliY, "PauliZ": PauliZ} def __init__(self): self._pauli_factors = {} # {wire: (pauli_coeff, pauli_word)} self._non_pauli_factors = {} # {wires: [hash, exponent, operator]} self._factors = [] self.global_phase = 1 def add(self, factor: Operator): """Add factor. Args: factor (Operator): Factor to add. """ wires = factor.wires if isinstance(factor, Prod): for prod_factor in factor: self.add(prod_factor) elif isinstance(factor, Sum): self._remove_pauli_factors(wires=wires) self._remove_non_pauli_factors(wires=wires) self._factors += (factor.operands,) elif not isinstance(factor, qml.Identity): if isinstance(factor, SProd): self.global_phase *= factor.scalar factor = factor.base if isinstance(factor, (qml.Identity, qml.X, qml.Y, qml.Z)): self._add_pauli_factor(factor=factor, wires=wires) self._remove_non_pauli_factors(wires=wires) else: self._add_non_pauli_factor(factor=factor, wires=wires) self._remove_pauli_factors(wires=wires) def _add_pauli_factor(self, factor: Operator, wires: list[int]): """Adds the given Pauli operator to the temporary ``self._pauli_factors`` dictionary. If there was another Pauli operator acting on the same wire, the two operators are grouped together using the ``self._pauli_mult`` dictionary. Args: factor (Operator): Factor to be added. wires (List[int]): Factor wires. This argument is added to avoid calling ``factor.wires`` several times. """ wire = wires[0] op2_name = factor.name old_coeff, old_word = self._pauli_factors.get(wire, (1, "Identity")) coeff, new_word = self._pauli_mult[old_word][op2_name] self._pauli_factors[wire] = old_coeff * coeff, new_word def _add_non_pauli_factor(self, factor: Operator, wires: list[int]): """Adds the given non-Pauli factor to the temporary ``self._non_pauli_factors`` dictionary. If there alerady exists an identical operator in the dictionary, the two are grouped together. If there isn't an identical operator in the dictionary, all non Pauli factors that act on the same wires are removed and added to the ``self._factors`` tuple. Args: factor (Operator): Factor to be added. wires (List[int]): Factor wires. This argument is added to avoid calling ``factor.wires`` several times. """ if isinstance(factor, Pow): exponent = factor.z factor = factor.base else: exponent = 1 op_hash = factor.hash old_hash, old_exponent, old_op = self._non_pauli_factors.get(wires, [None, None, None]) if isinstance(old_op, (qml.RX, qml.RY, qml.RZ)) and factor.name == old_op.name: self._non_pauli_factors[wires] = [ op_hash, old_exponent, factor.__class__(factor.data[0] + old_op.data[0], wires).simplify(), ] elif op_hash == old_hash: self._non_pauli_factors[wires][1] += exponent else: self._remove_non_pauli_factors(wires=wires) self._non_pauli_factors[wires] = [op_hash, copy(exponent), factor] def _remove_non_pauli_factors(self, wires: list[int]): """Remove all factors from the ``self._non_pauli_factors`` dictionary that act on the given wires and add them to the ``self._factors`` tuple. Args: wires (List[int]): Wires of the operators to be removed. """ if not self._non_pauli_factors: return for wire in wires: for key, (_, exponent, op) in list(self._non_pauli_factors.items()): if wire in key: self._non_pauli_factors.pop(key) if exponent == 0: continue if exponent != 1: op = Pow(base=op, z=exponent).simplify() if not isinstance(op, qml.Identity): self._factors += ((op,),) def _remove_pauli_factors(self, wires: list[int]): """Remove all Pauli factors from the ``self._pauli_factors`` dictionary that act on the given wires and add them to the ``self._factors`` tuple. Args: wires (List[int]): Wires of the operators to be removed. """ if not self._pauli_factors: return for wire in wires: pauli_coeff, pauli_word = self._pauli_factors.pop(wire, (1, "Identity")) if pauli_word != "Identity": pauli_op = self._paulis[pauli_word](wire) self._factors += ((pauli_op,),) self.global_phase *= pauli_coeff def remove_factors(self, wires: list[int]): """Remove all factors from the ``self._pauli_factors`` and ``self._non_pauli_factors`` dictionaries that act on the given wires and add them to the ``self._factors`` tuple. Args: wires (List[int]): Wires of the operators to be removed. """ self._remove_pauli_factors(wires=wires) self._remove_non_pauli_factors(wires=wires) @property def factors(self): """Grouped factors tuple. Returns: tuple: Tuple of grouped factors. """ return tuple(self._factors)
pennylane/pennylane/ops/op_math/prod.py/0
{ "file_path": "pennylane/pennylane/ops/op_math/prod.py", "repo_id": "pennylane", "token_count": 11798 }
61
# Copyright 2018-2022 Xanadu Quantum Technologies Inc. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ This module contains the discrete-variable qutrit quantum operations. The operations are in one file: * ``matrix_ops.py``: Generalized operations that accept a matrix parameter, either unitary or hermitian depending. """ from ..identity import Identity from .matrix_ops import * from .non_parametric_ops import * from .observables import * from .parametric_ops import * from .state_preparation import * from .channel import * # TODO: Change `qml.Identity` for qutrit support or add `qml.TIdentity` for qutrits __ops__ = { "Identity", "QutritUnitary", "ControlledQutritUnitary", "TShift", "TClock", "TAdd", "TSWAP", "THadamard", "TRX", "TRY", "TRZ", "QutritBasisState", } __obs__ = { "THermitian", "GellMann", } __channels__ = {"QutritDepolarizingChannel", "QutritAmplitudeDamping", "TritFlip", "QutritChannel"} __all__ = list(__ops__ | __obs__ | __channels__)
pennylane/pennylane/ops/qutrit/__init__.py/0
{ "file_path": "pennylane/pennylane/ops/qutrit/__init__.py", "repo_id": "pennylane", "token_count": 512 }
62
# Copyright 2018-2021 Xanadu Quantum Technologies Inc. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Riemannian gradient optimizer""" import warnings import numpy as np from scipy.sparse.linalg import expm import pennylane as qml from pennylane import transform from pennylane.queuing import QueuingManager from pennylane.tape import QuantumScript, QuantumScriptBatch from pennylane.typing import PostprocessingFn @transform def append_time_evolution( tape: QuantumScript, riemannian_gradient, t, n, exact=False ) -> tuple[QuantumScriptBatch, PostprocessingFn]: r"""Append an approximate time evolution, corresponding to a Riemannian gradient on the Lie group, to an existing circuit. We want to implement the time evolution generated by an operator of the form .. math:: \text{grad} f(U) = sum_i c_i O_i, where :math:`O_i` are Pauli words and :math:`c_t \in \mathbb{R}`. If ``exact`` is ``False``, we Trotterize this operator and apply the unitary .. math:: U' = \prod_{n=1}^{N_{Trot.}} \left(\prod_i \exp{-it / N_{Trot.} O_i}\right), which is then appended to the current circuit. If ``exact`` is ``True``, we calculate the exact time evolution for the Riemannian gradient by way of the matrix exponential. .. math: U' = \exp{-it \text{grad} f(U)} and append this unitary. Args: tape (QuantumTape or QNode or Callable): circuit to transform. riemannian_gradient (.Hamiltonian): Hamiltonian object representing the Riemannian gradient. t (float): time evolution parameter. n (int): number of Trotter steps. Returns: qnode (QNode) or quantum function (Callable) or tuple[List[QuantumTape], function]: The transformed circuit as described in :func:`qml.transform <pennylane.transform>`. """ new_operations = tape.operations if exact: with QueuingManager.stop_recording(): new_operations.append( qml.QubitUnitary( expm(-1j * t * riemannian_gradient.sparse_matrix(tape.wires).toarray()), wires=range(len(riemannian_gradient.wires)), ) ) else: with QueuingManager.stop_recording(): new_operations.append(qml.templates.ApproxTimeEvolution(riemannian_gradient, t, n)) new_tape = type(tape)(new_operations, tape.measurements, shots=tape.shots) def null_postprocessing(results): """A postprocesing function returned by a transform that only converts the batch of results into a result for a single ``QuantumTape``. """ return results[0] # pragma: no cover return [new_tape], null_postprocessing def algebra_commutator(tape, observables, lie_algebra_basis_names, nqubits): """Calculate the Riemannian gradient in the Lie algebra with the parameter shift rule (see :meth:`RiemannianGradientOptimizer.get_omegas`). Args: tape (.QuantumTape or .QNode): input circuit observables (list[.Observable]): list of observables to be measured. Can be grouped. lie_algebra_basis_names (list[str]): List of strings corresponding to valid Pauli words. nqubits (int): the number of qubits. Returns: function or tuple[list[QuantumTape], function]: - If the input is a QNode, an object representing the Riemannian gradient function of the QNode that can be executed with the same arguments as the QNode to obtain the Lie algebra commutator. - If the input is a tape, a tuple containing a list of generated tapes, together with a post-processing function to be applied to the results of the evaluated tapes in order to obtain the Lie algebra commutator. """ tapes_plus_total = [] tapes_min_total = [] for obs in observables: for o in obs: # create a list of tapes for the plus and minus shifted circuits queues_plus = [qml.queuing.AnnotatedQueue() for _ in lie_algebra_basis_names] queues_min = [qml.queuing.AnnotatedQueue() for _ in lie_algebra_basis_names] # loop through all operations on the input tape for op in tape.operations: for t in queues_plus + queues_min: with t: qml.apply(op) for i, t in enumerate(queues_plus): with t: qml.PauliRot( np.pi / 2, lie_algebra_basis_names[i], wires=list(range(nqubits)), ) qml.expval(o) for i, t in enumerate(queues_min): with t: qml.PauliRot( -np.pi / 2, lie_algebra_basis_names[i], wires=list(range(nqubits)), ) qml.expval(o) tapes_plus_total.extend( [ qml.tape.QuantumScript(*qml.queuing.process_queue(q)) for q, p in zip(queues_plus, lie_algebra_basis_names) ] ) tapes_min_total.extend( [ qml.tape.QuantumScript(*qml.queuing.process_queue(q)) for q, p in zip(queues_min, lie_algebra_basis_names) ] ) return tapes_plus_total + tapes_min_total class RiemannianGradientOptimizer: r"""Riemannian gradient optimizer. Riemannian gradient descent algorithms can be used to optimize a function directly on a Lie group as opposed to on an Euclidean parameter space. Consider the function :math:`f(U) = \text{Tr}(U \rho_0 U^\dagger H)` for a given Hamiltonian :math:`H`, unitary :math:`U\in \text{SU}(2^N)` and initial state :math:`\rho_0`. One can show that this function is minimized by the flow equation .. math:: \dot{U} = \text{grad}f(U) where :math:`\text{grad}` is the Riemannian gradient operator on :math:`\text{SU}(2^N)`. By discretizing the flow above, we see that a step of this optimizer iterates the Riemannian gradient flow on :math:`\text{SU}(2^N)` as .. math:: U^{(t+1)} = \exp\left\{\epsilon\: \text{grad}f(U^{(t)}) U^{(t)}\right\}, where :math:`\epsilon` is a user-defined hyperparameter corresponding to the step size. The Riemannian gradient in the Lie algebra is given by .. math:: \text{grad}f(U^{(t)}) = -\left[U \rho U^\dagger, H\right] . Hence we see that subsequent steps of this optimizer will append the unitary generated by the Riemannian gradient and grow the circuit. The exact Riemannian gradient flow on :math:`\text{SU}(2^N)` has desirable optimization properties that can guarantee convergence to global minima under mild assumptions. However, this comes at a cost. Since :math:`\text{dim}(\text{SU}(2^N)) = 4^N-1`, we need an exponential number of parameters to calculate the gradient. This will not be problematic for small systems (:math:`N<5`), but will quickly get out of control as the number of qubits increases. To resolve this issue, we can restrict the Riemannian gradient to a subspace of the Lie algebra and calculate an approximate Riemannian gradient flow. The choice of restriction will affect the optimization behaviour and quality of the final solution. For more information on Riemannian gradient flows on Lie groups see `T. Schulte-Herbrueggen et. al. (2008) <https://arxiv.org/abs/0802.4195>`_ and the application to quantum circuits `Wiersema and Killoran (2022) <https://arxiv.org/abs/2202.06976>`_. Args: circuit (.QNode): a user defined circuit that does not take any arguments and returns the expectation value of a ``qml.Hamiltonian``. stepsize (float): the user-defined hyperparameter :math:`\epsilon`. restriction (.Hamiltonian): Restrict the Lie algebra to a corresponding subspace of the full Lie algebra. This restriction should be passed in the form of a ``qml.Hamiltonian`` that consists only of Pauli words. exact (bool): Flag that indicates wether we approximate the Riemannian gradient with a Trotterization or calculate the exact evolution via a matrix exponential. The latter is not hardware friendly and can only be done in simulation. **Examples** Define a Hamiltonian cost function to minimize: >>> coeffs = [-1., -1., -1.] >>> observables = [qml.X(0), qml.Z(1), qml.Y(0) @ qml.X(1)] >>> hamiltonian = qml.Hamiltonian(coeffs, observables) Create an initial state and return the expectation value of the Hamiltonian: >>> @qml.qnode(qml.device("default.qubit", wires=2)) ... def quant_fun(): ... qml.RX(0.1, wires=[0]) ... qml.RY(0.5, wires=[1]) ... qml.CNOT(wires=[0,1]) ... qml.RY(0.6, wires=[0]) ... return qml.expval(hamiltonian) Instantiate the optimizer with the initial circuit and the cost function and set the stepsize accordingly: >>> opt = qml.RiemannianGradientOptimizer(circuit=quant_fun, stepsize=0.1) Applying 5 steps gets us close the ground state of :math:`E\approx-2.23`: >>> for step in range(6): ... circuit, cost = opt.step_and_cost() ... print(f"Step {step} - cost {cost}") Step 0 - cost -1.3351865007304005 Step 1 - cost -1.9937887238935206 Step 2 - cost -2.1524234485729834 Step 3 - cost -2.1955105378898487 Step 4 - cost -2.2137628169764256 Step 5 - cost -2.2234364822091575 The optimized circuit is returned at each step, and can be used as any other QNode: >>> circuit() -2.2283086057521713 """ # pylint: disable=too-many-arguments # pylint: disable=too-many-instance-attributes def __init__(self, circuit, stepsize=0.01, restriction=None, exact=False, trottersteps=1): if not isinstance(circuit, qml.QNode): raise TypeError(f"circuit must be a QNode, received {type(circuit)}") self.circuit = circuit self.circuit.construct([], {}) self.hamiltonian = circuit.func().obs if not isinstance(self.hamiltonian, (qml.ops.Hamiltonian, qml.ops.LinearCombination)): raise TypeError( f"circuit must return the expectation value of a Hamiltonian," f"received {type(circuit.func().obs)}" ) self.nqubits = len(circuit.device.wires) if self.nqubits > 4: warnings.warn( "The exact Riemannian gradient is exponentially expensive in the number of qubits, " f"optimizing a {self.nqubits} qubit circuit may be slow.", UserWarning, ) if restriction is not None and not isinstance( restriction, (qml.ops.Hamiltonian, qml.ops.LinearCombination) ): raise TypeError(f"restriction must be a Hamiltonian, received {type(restriction)}") ( self.lie_algebra_basis_ops, self.lie_algebra_basis_names, ) = self.get_su_n_operators(restriction) self.exact = exact self.trottersteps = trottersteps self.coeffs, self.observables = self.hamiltonian.terms() self.stepsize = stepsize def step(self): r"""Update the circuit with one step of the optimizer. Returns: float: the optimized circuit and the objective function output prior to the step. """ return self.step_and_cost()[0] def step_and_cost(self): r"""Update the circuit with one step of the optimizer and return the corresponding objective function value prior to the step. Returns: tuple[.QNode, float]: the optimized circuit and the objective function output prior to the step. """ # pylint: disable=not-callable cost = self.circuit() omegas = self.get_omegas() non_zero_omegas = -omegas[omegas != 0] nonzero_idx = np.nonzero(omegas)[0] non_zero_lie_algebra_elements = [self.lie_algebra_basis_names[i] for i in nonzero_idx] lie_gradient = qml.Hamiltonian( non_zero_omegas, [qml.pauli.string_to_pauli_word(ps) for ps in non_zero_lie_algebra_elements], ) new_circuit = append_time_evolution( self.circuit.func, lie_gradient, self.stepsize, self.trottersteps, self.exact ) # we can set diff_method=None because the gradient of the QNode is computed # directly in this optimizer self.circuit = qml.QNode(new_circuit, self.circuit.device, diff_method=None) return self.circuit, cost def get_su_n_operators(self, restriction): r"""Get the SU(N) operators. The dimension of the group is :math:`N^2-1`. Args: restriction (.Hamiltonian): Restrict the Riemannian gradient to a subspace. Returns: tuple[list[array[complex]], list[str]]: list of :math:`N^2 \times N^2` NumPy complex arrays and corresponding Pauli words. """ operators = [] names = [] # construct the corresponding pennylane observables wire_map = dict(zip(range(self.nqubits), range(self.nqubits))) if restriction is None: for ps in qml.pauli.pauli_group(self.nqubits): operators.append(ps) names.append(qml.pauli.pauli_word_to_string(ps, wire_map=wire_map)) else: for ps in set(restriction.ops): operators.append(ps) names.append(qml.pauli.pauli_word_to_string(ps, wire_map=wire_map)) return operators, names def get_omegas(self): r"""Measure the coefficients of the Riemannian gradient with respect to a Pauli word basis. We want to calculate the components of the Riemannian gradient in the Lie algebra with respect to a Pauli word basis. For a Hamiltonian of the form :math:`H = \sum_i c_i O_i`, where :math:`c_i\in\mathbb{R}`, this can be achieved by calculating .. math:: \omega_{i,j} = \text{Tr}(c_i[\rho, O_i] P_j) where :math:`P_j` is a Pauli word in the set of Pauli monomials on :math:`N` qubits. Via the parameter shift rule, the commutator can be calculated as .. math:: [\rho, O_i] = \frac{1}{2}(V(\pi/2) \rho V^\dagger(\pi/2) - V(-\pi/2) \rho V^\dagger(-\pi/2)) where :math:`V` is the unitary generated by the Pauli word :math:`V(\theta) = \exp\{-i\theta P_j\}`. Returns: array: array of omegas for each direction in the Lie algebra. """ obs_groupings, _ = qml.pauli.group_observables(self.observables, self.coeffs) # get all circuits we need to calculate the coefficients circuits = algebra_commutator( self.circuit.qtape, obs_groupings, self.lie_algebra_basis_names, self.nqubits, ) if isinstance(self.circuit.device, qml.devices.Device): program, config = self.circuit.device.preprocess() circuits = qml.execute( circuits, self.circuit.device, transform_program=program, config=config, gradient_fn=None, ) else: circuits = qml.execute( circuits, self.circuit.device, gradient_fn=None ) # pragma: no cover program, _ = self.circuit.device.preprocess() circuits_plus = np.array(circuits[: len(circuits) // 2]).reshape( len(self.coeffs), len(self.lie_algebra_basis_names) ) circuits_min = np.array(circuits[len(circuits) // 2 :]).reshape( len(self.coeffs), len(self.lie_algebra_basis_names) ) # For each observable O_i in the Hamiltonian, we have to calculate all Lie coefficients omegas = circuits_plus - circuits_min return np.dot(self.coeffs, omegas)
pennylane/pennylane/optimize/riemannian_gradient.py/0
{ "file_path": "pennylane/pennylane/optimize/riemannian_gradient.py", "repo_id": "pennylane", "token_count": 7059 }
63
# Copyright 2018-2022 Xanadu Quantum Technologies Inc. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """The Pauli arithmetic abstract reduced representation classes""" # pylint:disable=protected-access from copy import copy from functools import lru_cache, reduce import numpy as np from scipy import sparse import pennylane as qml from pennylane import math from pennylane.operation import Tensor from pennylane.ops import Identity, PauliX, PauliY, PauliZ, Prod, SProd, Sum from pennylane.typing import TensorLike from pennylane.wires import Wires I = "I" X = "X" Y = "Y" Z = "Z" op_map = { I: Identity, X: PauliX, Y: PauliY, Z: PauliZ, } op_to_str_map = { Identity: I, PauliX: X, PauliY: Y, PauliZ: Z, } matI = np.eye(2) matX = np.array([[0, 1], [1, 0]]) matY = np.array([[0, -1j], [1j, 0]]) matZ = np.array([[1, 0], [0, -1]]) mat_map = { I: matI, X: matX, Y: matY, Z: matZ, } anticom_map = { I: {I: 0, X: 0, Y: 0, Z: 0}, X: {I: 0, X: 0, Y: 1, Z: 1}, Y: {I: 0, X: 1, Y: 0, Z: 1}, Z: {I: 0, X: 1, Y: 1, Z: 0}, } @lru_cache def _make_operation(op, wire): return op_map[op](wire) @lru_cache def _cached_sparse_data(op): """Returns the sparse data and indices of a Pauli operator.""" if op == "I": data = np.array([1.0, 1.0], dtype=np.complex128) indices = np.array([0, 1], dtype=np.int64) elif op == "X": data = np.array([1.0, 1.0], dtype=np.complex128) indices = np.array([1, 0], dtype=np.int64) elif op == "Y": data = np.array([-1.0j, 1.0j], dtype=np.complex128) indices = np.array([1, 0], dtype=np.int64) elif op == "Z": data = np.array([1.0, -1.0], dtype=np.complex128) indices = np.array([0, 1], dtype=np.int64) return data, indices @lru_cache(maxsize=2) def _cached_arange(n): "Caches `np.arange` output to speed up sparse calculations." return np.arange(n) pauli_to_sparse_int = {I: 0, X: 1, Y: 1, Z: 0} # (I, Z) and (X, Y) have the same sparsity def _ps_to_sparse_index(pauli_words, wires): """Represent the Pauli words sparse structure in a matrix of shape n_words x n_wires.""" indices = np.zeros((len(pauli_words), len(wires))) for i, pw in enumerate(pauli_words): if not pw.wires: continue wire_indices = np.array(wires.indices(pw.wires)) indices[i, wire_indices] = [pauli_to_sparse_int[pw[w]] for w in pw.wires] return indices _map_I = { I: (1, I), X: (1, X), Y: (1, Y), Z: (1, Z), } _map_X = { I: (1, X), X: (1, I), Y: (1.0j, Z), Z: (-1.0j, Y), } _map_Y = { I: (1, Y), X: (-1.0j, Z), Y: (1, I), Z: (1j, X), } _map_Z = { I: (1, Z), X: (1j, Y), Y: (-1.0j, X), Z: (1, I), } mul_map = {I: _map_I, X: _map_X, Y: _map_Y, Z: _map_Z} class PauliWord(dict): r""" Immutable dictionary used to represent a Pauli Word, associating wires with their respective operators. Can be constructed from a standard dictionary. .. note:: An empty :class:`~.PauliWord` will be treated as the multiplicative identity (i.e identity on all wires). Its matrix is the identity matrix (trivially the :math:`1\times 1` one matrix when no ``wire_order`` is passed to ``PauliWord({}).to_mat()``). **Examples** Initializing a Pauli word: >>> w = PauliWord({"a": 'X', 2: 'Y', 3: 'Z'}) >>> w X(a) @ Y(2) @ Z(3) When multiplying Pauli words together, we obtain a :class:`~PauliSentence` with the resulting ``PauliWord`` as a key and the corresponding coefficient as its value. >>> w1 = PauliWord({0:"X", 1:"Y"}) >>> w2 = PauliWord({1:"X", 2:"Z"}) >>> w1 @ w2 -1j * Z(1) @ Z(2) @ X(0) We can multiply scalars to Pauli words or add/subtract them, resulting in a :class:`~PauliSentence` instance. >>> 0.5 * w1 - 1.5 * w2 + 2 0.5 * X(0) @ Y(1) + -1.5 * X(1) @ Z(2) + 2 * I """ # this allows scalar multiplication from left with numpy arrays np.array(0.5) * pw1 # taken from [stackexchange](https://stackoverflow.com/questions/40694380/forcing-multiplication-to-use-rmul-instead-of-numpy-array-mul-or-byp/44634634#44634634) __array_priority__ = 1000 def __missing__(self, key): """If the wire is not in the Pauli word, then no operator acts on it, so return the Identity.""" return I def __init__(self, mapping): """Strip identities from PauliWord on init!""" for wire, op in mapping.copy().items(): if op == I: del mapping[wire] super().__init__(mapping) @property def pauli_rep(self): """Trivial pauli_rep""" return PauliSentence({self: 1.0}) def __reduce__(self): """Defines how to pickle and unpickle a PauliWord. Otherwise, un-pickling would cause __setitem__ to be called, which is forbidden on PauliWord. For more information, see: https://docs.python.org/3/library/pickle.html#object.__reduce__ """ return (PauliWord, (dict(self),)) def __copy__(self): """Copy the PauliWord instance.""" return PauliWord(dict(self.items())) def __deepcopy__(self, memo): res = self.__copy__() memo[id(self)] = res return res def __setitem__(self, key, item): """Restrict setting items after instantiation.""" raise TypeError("PauliWord object does not support assignment") def update(self, __m, **kwargs) -> None: """Restrict updating PW after instantiation.""" raise TypeError("PauliWord object does not support assignment") def __hash__(self): return hash(frozenset(self.items())) def _matmul(self, other): """Private matrix multiplication that returns (pauli_word, coeff) tuple for more lightweight processing""" base, iterator, swapped = ( (self, other, False) if len(self) >= len(other) else (other, self, True) ) result = copy(dict(base)) coeff = 1 for wire, term in iterator.items(): if wire in base: factor, new_op = mul_map[term][base[wire]] if swapped else mul_map[base[wire]][term] if new_op == I: del result[wire] else: coeff *= factor result[wire] = new_op elif term != I: result[wire] = term return PauliWord(result), coeff def __matmul__(self, other): """Multiply two Pauli words together using the matrix product if wires overlap and the tensor product otherwise. Empty Pauli words are treated as the Identity operator on all wires. Args: other (PauliWord): The Pauli word to multiply with Returns: PauliSentence: coeff * new_word """ if isinstance(other, PauliSentence): return PauliSentence({self: 1.0}) @ other new_word, coeff = self._matmul(other) return PauliSentence({new_word: coeff}) def __mul__(self, other): """Multiply a PauliWord by a scalar Args: other (Scalar): The scalar to multiply the PauliWord with Returns: PauliSentence """ if isinstance(other, TensorLike): if not qml.math.ndim(other) == 0: raise ValueError( f"Attempting to multiply a PauliWord with an array of dimension {qml.math.ndim(other)}" ) return PauliSentence({self: other}) raise TypeError( f"PauliWord can only be multiplied by numerical data. Attempting to multiply by {other} of type {type(other)}" ) __rmul__ = __mul__ def __add__(self, other): """Add PauliWord instances and scalars to PauliWord. Returns a PauliSentence.""" # Note that the case of PauliWord + PauliSentence is covered in PauliSentence if isinstance(other, PauliWord): if other == self: return PauliSentence({self: 2.0}) return PauliSentence({self: 1.0, other: 1.0}) if isinstance(other, TensorLike): # Scalars are interepreted as scalar * Identity IdWord = PauliWord({}) if IdWord == self: return PauliSentence({self: 1.0 + other}) return PauliSentence({self: 1.0, IdWord: other}) return NotImplemented __radd__ = __add__ def __iadd__(self, other): """Inplace addition""" return self + other def __sub__(self, other): """Subtract other PauliSentence, PauliWord, or scalar""" return self + -1 * other def __rsub__(self, other): """Subtract other PauliSentence, PauliWord, or scalar""" return -1 * self + other def __truediv__(self, other): """Divide a PauliWord by a scalar""" if isinstance(other, TensorLike): return self * (1 / other) raise TypeError( f"PauliWord can only be divided by numerical data. Attempting to divide by {other} of type {type(other)}" ) def commutes_with(self, other): """Fast check if two PauliWords commute with each other""" wires = set(self) & set(other) if not wires: return True anticom_count = sum(anticom_map[self[wire]][other[wire]] for wire in wires) return (anticom_count % 2) == 0 def _commutator(self, other): """comm between two PauliWords, returns tuple (new_word, coeff) for faster arithmetic""" # This may be helpful to developers that need a more lightweight comm between pauli words # without creating PauliSentence classes if self.commutes_with(other): return PauliWord({}), 0.0 new_word, coeff = self._matmul(other) return new_word, 2 * coeff def commutator(self, other): """ Compute commutator between a ``PauliWord`` :math:`P` and other operator :math:`O` .. math:: [P, O] = P O - O P When the other operator is a :class:`~PauliWord` or :class:`~PauliSentence`, this method is faster than computing ``P @ O - O @ P``. It is what is being used in :func:`~commutator` when setting ``pauli=True``. Args: other (Union[Operator, PauliWord, PauliSentence]): Second operator Returns: ~PauliSentence: The commutator result in form of a :class:`~PauliSentence` instances. **Examples** You can compute commutators between :class:`~PauliWord` instances. >>> pw = PauliWord({0:"X"}) >>> pw.commutator(PauliWord({0:"Y"})) 2j * Z(0) You can also compute the commutator with other operator types if they have a Pauli representation. >>> pw.commutator(qml.Y(0)) 2j * Z(0) """ if isinstance(other, PauliWord): new_word, coeff = self._commutator(other) if coeff == 0: return PauliSentence({}) return PauliSentence({new_word: coeff}) if isinstance(other, qml.operation.Operator): op_self = PauliSentence({self: 1.0}) return op_self.commutator(other) if isinstance(other, PauliSentence): # for infix method, this would be handled by __ror__ return -1.0 * other.commutator(self) raise NotImplementedError( f"Cannot compute natively a commutator between PauliWord and {other} of type {type(other)}" ) def __str__(self): """String representation of a PauliWord.""" if len(self) == 0: return "I" return " @ ".join(f"{op}({w})" for w, op in self.items()) def __repr__(self): """Terminal representation for PauliWord""" return str(self) @property def wires(self): """Track wires in a PauliWord.""" return Wires(self) def to_mat(self, wire_order=None, format="dense", coeff=1.0): """Returns the matrix representation. Keyword Args: wire_order (iterable or None): The order of qubits in the tensor product. format (str): The format of the matrix. It is "dense" by default. Use "csr" for sparse. coeff (float): Coefficient multiplying the resulting matrix. Returns: (Union[NumpyArray, ScipySparseArray]): Matrix representation of the Pauli word. Raises: ValueError: Can't get the matrix of an empty PauliWord. """ wire_order = self.wires if wire_order is None else Wires(wire_order) if not wire_order.contains_wires(self.wires): raise ValueError( "Can't get the matrix for the specified wire order because it " f"does not contain all the Pauli word's wires {self.wires}" ) if len(self) == 0: n = len(wire_order) if wire_order is not None else 0 return ( np.diag([coeff] * 2**n) if format == "dense" else coeff * sparse.eye(2**n, format=format, dtype="complex128") ) if format == "dense": return coeff * reduce(math.kron, (mat_map[self[w]] for w in wire_order)) return self._to_sparse_mat(wire_order, coeff) def _to_sparse_mat(self, wire_order, coeff): """Compute the sparse matrix of the Pauli word times a coefficient, given a wire order. See pauli_sparse_matrices.md for the technical details of the implementation.""" matrix_size = 2 ** len(wire_order) matrix = sparse.csr_matrix((matrix_size, matrix_size), dtype="complex128") # Avoid checks and copies in __init__ by directly setting the attributes of an empty matrix matrix.data = self._get_csr_data(wire_order, coeff) matrix.indices = self._get_csr_indices(wire_order) matrix.indptr = _cached_arange(matrix_size + 1) # Non-zero entries by row (starting from 0) return matrix def _get_csr_data(self, wire_order, coeff): """Computes the sparse matrix data of the Pauli word times a coefficient, given a wire order.""" full_word = [self[wire] for wire in wire_order] matrix_size = 2 ** len(wire_order) if len(self) == 0: return np.full(matrix_size, coeff, dtype=np.complex128) data = np.empty(matrix_size, dtype=np.complex128) # Non-zero values current_size = 2 data[:current_size], _ = _cached_sparse_data(full_word[-1]) data[:current_size] *= coeff # Multiply initial term better than the full matrix for s in full_word[-2::-1]: if s == "I": data[current_size : 2 * current_size] = data[:current_size] elif s == "X": data[current_size : 2 * current_size] = data[:current_size] elif s == "Y": data[current_size : 2 * current_size] = 1j * data[:current_size] data[:current_size] *= -1j elif s == "Z": data[current_size : 2 * current_size] = -data[:current_size] current_size *= 2 return data def _get_csr_data_2(self, wire_order, coeff): """Computes the sparse matrix data of the Pauli word times a coefficient, given a wire order.""" full_word = [self[wire] for wire in wire_order] nwords = len(full_word) if nwords < 2: return np.array([1.0]), self._get_csr_data(wire_order, coeff) outer = self._get_csr_data(wire_order[: nwords // 2], 1.0) inner = self._get_csr_data(wire_order[nwords // 2 :], coeff) return outer, inner def _get_csr_indices(self, wire_order): """Computes the sparse matrix indices of the Pauli word times a coefficient, given a wire order.""" full_word = [self[wire] for wire in wire_order] matrix_size = 2 ** len(wire_order) if len(self) == 0: return _cached_arange(matrix_size) indices = np.empty(matrix_size, dtype=np.int64) # Column index of non-zero values current_size = 2 _, indices[:current_size] = _cached_sparse_data(full_word[-1]) for s in full_word[-2::-1]: if s == "I": indices[current_size : 2 * current_size] = indices[:current_size] + current_size elif s == "X": indices[current_size : 2 * current_size] = indices[:current_size] indices[:current_size] += current_size elif s == "Y": indices[current_size : 2 * current_size] = indices[:current_size] indices[:current_size] += current_size elif s == "Z": indices[current_size : 2 * current_size] = indices[:current_size] + current_size current_size *= 2 return indices def operation(self, wire_order=None, get_as_tensor=False): """Returns a native PennyLane :class:`~pennylane.operation.Operation` representing the PauliWord.""" if len(self) == 0: return Identity(wires=wire_order) factors = [_make_operation(op, wire) for wire, op in self.items()] if get_as_tensor: return factors[0] if len(factors) == 1 else Tensor(*factors) pauli_rep = PauliSentence({self: 1}) return factors[0] if len(factors) == 1 else Prod(*factors, _pauli_rep=pauli_rep) def hamiltonian(self, wire_order=None): """Return :class:`~pennylane.Hamiltonian` representing the PauliWord.""" if len(self) == 0: if wire_order in (None, [], Wires([])): raise ValueError("Can't get the Hamiltonian for an empty PauliWord.") return qml.Hamiltonian([1], [Identity(wires=wire_order)]) obs = [_make_operation(op, wire) for wire, op in self.items()] return qml.Hamiltonian([1], [obs[0] if len(obs) == 1 else Tensor(*obs)]) def map_wires(self, wire_map: dict) -> "PauliWord": """Return a new PauliWord with the wires mapped.""" return self.__class__({wire_map.get(w, w): op for w, op in self.items()}) pw_id = PauliWord({}) # empty pauli word to be re-used class PauliSentence(dict): r"""Dictionary representing a linear combination of Pauli words, with the keys as :class:`~pennylane.pauli.PauliWord` instances and the values correspond to coefficients. .. note:: An empty :class:`~.PauliSentence` will be treated as the additive identity (i.e ``0 * Identity()``). Its matrix is the all-zero matrix (trivially the :math:`1\times 1` zero matrix when no ``wire_order`` is passed to ``PauliSentence({}).to_mat()``). **Examples** >>> ps = PauliSentence({ PauliWord({0:'X', 1:'Y'}): 1.23, PauliWord({2:'Z', 0:'Y'}): -0.45j }) >>> ps 1.23 * X(0) @ Y(1) + (-0-0.45j) * Z(2) @ Y(0) Combining Pauli words automatically results in Pauli sentences that can be used to construct more complicated operators. >>> w1 = PauliWord({0:"X", 1:"Y"}) >>> w2 = PauliWord({1:"X", 2:"Z"}) >>> ps = 0.5 * w1 - 1.5 * w2 + 2 >>> ps + PauliWord({3:"Z"}) - 1 0.5 * X(0) @ Y(1) + -1.5 * X(1) @ Z(2) + 1 * I + 1.0 * Z(3) Note that while the empty :class:`~PauliWord` ``PauliWord({})`` respresents the identity, the empty ``PauliSentence`` represents 0 >>> PauliSentence({}) 0 * I We can compute commutators using the ``PauliSentence.commutator()`` method >>> op1 = PauliWord({0:"X", 1:"X"}) >>> op2 = PauliWord({0:"Y"}) + PauliWord({1:"Y"}) >>> op1.commutator(op2) 2j * Z(0) @ X(1) + 2j * X(0) @ Z(1) Or, alternatively, use :func:`~commutator`. >>> qml.commutator(op1, op2, pauli=True) Note that we need to specify ``pauli=True`` as :func:`~.commutator` returns PennyLane operators by default. """ # this allows scalar multiplication from left with numpy arrays np.array(0.5) * ps1 # taken from [stackexchange](https://stackoverflow.com/questions/40694380/forcing-multiplication-to-use-rmul-instead-of-numpy-array-mul-or-byp/44634634#44634634) __array_priority__ = 1000 @property def pauli_rep(self): """Trivial pauli_rep""" return self def __missing__(self, key): """If the PauliWord is not in the sentence then the coefficient associated with it should be 0.""" return 0.0 def trace(self): r"""Return the normalized trace of the ``PauliSentence`` instance .. math:: \frac{1}{2^n} \text{tr}\left( P \right). The normalized trace does not scale with the number of qubits :math:`n`. >>> PauliSentence({PauliWord({0:"I", 1:"I"}): 0.5}).trace() 0.5 >>> PauliSentence({PauliWord({}): 0.5}).trace() 0.5 """ return self.get(pw_id, 0.0) def __add__(self, other): """Add a PauliWord, scalar or other PauliSentence to a PauliSentence. Empty Pauli sentences are treated as the additive identity (i.e 0 * Identity on all wires). The non-empty Pauli sentence is returned. """ if isinstance(other, PauliSentence): smaller_ps, larger_ps = ( (self, copy(other)) if len(self) < len(other) else (other, copy(self)) ) for key in smaller_ps: larger_ps[key] += smaller_ps[key] return larger_ps if isinstance(other, PauliWord): res = copy(self) if other in res: res[other] += 1.0 else: res[other] = 1.0 return res if isinstance(other, TensorLike): # Scalars are interepreted as scalar * Identity res = copy(self) IdWord = PauliWord({}) if IdWord in res: res[IdWord] += other else: res[IdWord] = other return res raise TypeError(f"Cannot add {other} of type {type(other)} to PauliSentence") __radd__ = __add__ def __iadd__(self, other): """Inplace addition of two Pauli sentence together by adding terms of other to self""" if isinstance(other, PauliSentence): for key in other: if key in self: self[key] += other[key] else: self[key] = other[key] return self if isinstance(other, PauliWord): if other in self: self[other] += 1.0 else: self[other] = 1.0 return self if isinstance(other, TensorLike): IdWord = PauliWord({}) if IdWord in self: self[IdWord] += other else: self[IdWord] = other return self raise TypeError(f"Cannot add {other} of type {type(other)} to PauliSentence") def __sub__(self, other): """Subtract other PauliSentence, PauliWord, or scalar""" return self + -1 * other def __rsub__(self, other): """Subtract other PauliSentence, PauliWord, or scalar""" return -1 * self + other def __copy__(self): """Copy the PauliSentence instance.""" copied_ps = {} for pw, coeff in self.items(): copied_ps[copy(pw)] = coeff return PauliSentence(copied_ps) def __deepcopy__(self, memo): res = self.__copy__() memo[id(self)] = res return res def __matmul__(self, other): """Matrix / tensor product between two PauliSentences by iterating over each sentence and multiplying the Pauli words pair-wise""" if isinstance(other, PauliWord): other = PauliSentence({other: 1.0}) final_ps = PauliSentence() if len(self) == 0 or len(other) == 0: return final_ps for pw1 in self: for pw2 in other: prod_pw, coeff = pw1._matmul(pw2) final_ps[prod_pw] = final_ps[prod_pw] + coeff * self[pw1] * other[pw2] return final_ps def __mul__(self, other): """Multiply a PauliWord by a scalar Args: other (Scalar): The scalar to multiply the PauliWord with Returns: PauliSentence """ if isinstance(other, TensorLike): if not qml.math.ndim(other) == 0: raise ValueError( f"Attempting to multiply a PauliSentence with an array of dimension {qml.math.ndim(other)}" ) return PauliSentence({key: other * value for key, value in self.items()}) raise TypeError( f"PauliSentence can only be multiplied by numerical data. Attempting to multiply by {other} of type {type(other)}" ) __rmul__ = __mul__ def __truediv__(self, other): """Divide a PauliSentence by a scalar""" if isinstance(other, TensorLike): return self * (1 / other) raise TypeError( f"PauliSentence can only be divided by numerical data. Attempting to divide by {other} of type {type(other)}" ) def commutator(self, other): """ Compute commutator between a ``PauliSentence`` :math:`P` and other operator :math:`O` .. math:: [P, O] = P O - O P When the other operator is a :class:`~PauliWord` or :class:`~PauliSentence`, this method is faster than computing ``P @ O - O @ P``. It is what is being used in :func:`~commutator` when setting ``pauli=True``. Args: other (Union[Operator, PauliWord, PauliSentence]): Second operator Returns: ~PauliSentence: The commutator result in form of a :class:`~PauliSentence` instances. **Examples** You can compute commutators between :class:`~PauliSentence` instances. >>> pw1 = PauliWord({0:"X"}) >>> pw2 = PauliWord({1:"X"}) >>> ps1 = PauliSentence({pw1: 1., pw2: 2.}) >>> ps2 = PauliSentence({pw1: 0.5j, pw2: 1j}) >>> ps1.commutator(ps2) 0 * I You can also compute the commutator with other operator types if they have a Pauli representation. >>> ps1.commutator(qml.Y(0)) 2j * Z(0)""" final_ps = PauliSentence() if isinstance(other, PauliWord): for pw1 in self: comm_pw, coeff = pw1._commutator(other) if len(comm_pw) != 0: final_ps[comm_pw] += coeff * self[pw1] return final_ps if not isinstance(other, PauliSentence): if other.pauli_rep is None: raise NotImplementedError( f"Cannot compute a native commutator of a Pauli word or sentence with the operator {other} of type {type(other)}." f"You can try to use qml.commutator(op1, op2, pauli=False) instead." ) other = qml.pauli.pauli_sentence(other) for pw1 in self: for pw2 in other: comm_pw, coeff = pw1._commutator(pw2) if len(comm_pw) != 0: final_ps[comm_pw] += coeff * self[pw1] * other[pw2] return final_ps def __str__(self): """String representation of the PauliSentence.""" if len(self) == 0: return "0 * I" return "\n+ ".join(f"{coeff} * {str(pw)}" for pw, coeff in self.items()) def __repr__(self): """Terminal representation for PauliSentence""" return str(self) @property def wires(self): """Track wires of the PauliSentence.""" return Wires.all_wires((pw.wires for pw in self.keys())) def to_mat(self, wire_order=None, format="dense", buffer_size=None): """Returns the matrix representation. Keyword Args: wire_order (iterable or None): The order of qubits in the tensor product. format (str): The format of the matrix. It is "dense" by default. Use "csr" for sparse. buffer_size (int or None): The maximum allowed memory in bytes to store intermediate results in the calculation of sparse matrices. It defaults to ``2 ** 30`` bytes that make 1GB of memory. In general, larger buffers allow faster computations. Returns: (Union[NumpyArray, ScipySparseArray]): Matrix representation of the Pauli sentence. Raises: ValueError: Can't get the matrix of an empty PauliSentence. """ wire_order = self.wires if wire_order is None else Wires(wire_order) if len(self) == 0: n = len(wire_order) if wire_order is not None else 0 if format == "dense": return np.zeros((2**n, 2**n)) return sparse.csr_matrix((2**n, 2**n), dtype="complex128") if format == "dense": return self._to_dense_mat(wire_order) return self._to_sparse_mat(wire_order, buffer_size=buffer_size) def _to_sparse_mat(self, wire_order, buffer_size=None): """Compute the sparse matrix of the Pauli sentence by efficiently adding the Pauli words that it is composed of. See pauli_sparse_matrices.md for the technical details.""" pauli_words = list(self) # Ensure consistent ordering n_wires = len(wire_order) matrix_size = 2**n_wires matrix = sparse.csr_matrix((matrix_size, matrix_size), dtype="complex128") op_sparse_idx = _ps_to_sparse_index(pauli_words, wire_order) _, unique_sparse_structures, unique_invs = np.unique( op_sparse_idx, axis=0, return_index=True, return_inverse=True ) pw_sparse_structures = unique_sparse_structures[unique_invs] buffer_size = buffer_size or 2**30 # Default to 1GB of memory # Convert bytes to number of matrices: # complex128 (16) for each data entry and int64 (8) for each indices entry buffer_size = max(1, buffer_size // ((16 + 8) * matrix_size)) mat_data = np.empty((matrix_size, buffer_size), dtype=np.complex128) mat_indices = np.empty((matrix_size, buffer_size), dtype=np.int64) n_matrices_in_buffer = 0 for sparse_structure in unique_sparse_structures: indices, *_ = np.nonzero(pw_sparse_structures == sparse_structure) mat = self._sum_same_structure_pws([pauli_words[i] for i in indices], wire_order) mat_data[:, n_matrices_in_buffer] = mat.data mat_indices[:, n_matrices_in_buffer] = mat.indices n_matrices_in_buffer += 1 if n_matrices_in_buffer == buffer_size: # Add partial results in batches to control the memory usage matrix += self._sum_different_structure_pws(mat_indices, mat_data) n_matrices_in_buffer = 0 matrix += self._sum_different_structure_pws( mat_indices[:, :n_matrices_in_buffer], mat_data[:, :n_matrices_in_buffer] ) matrix.eliminate_zeros() return matrix def _to_dense_mat(self, wire_order): """Compute the dense matrix of the Pauli sentence by efficiently adding the Pauli words that it is composed of. See pauli_sparse_matrices.md for the technical details.""" pauli_words = list(self) # Ensure consistent ordering try: op_sparse_idx = _ps_to_sparse_index(pauli_words, wire_order) except qml.wires.WireError as e: raise ValueError( "Can't get the matrix for the specified wire order because it " f"does not contain all the Pauli sentence's wires {self.wires}" ) from e _, unique_sparse_structures, unique_invs = np.unique( op_sparse_idx, axis=0, return_index=True, return_inverse=True ) pw_sparse_structures = unique_sparse_structures[unique_invs] full_matrix = None for sparse_structure in unique_sparse_structures: indices, *_ = np.nonzero(pw_sparse_structures == sparse_structure) mat = self._sum_same_structure_pws_dense([pauli_words[i] for i in indices], wire_order) full_matrix = mat if full_matrix is None else qml.math.add(full_matrix, mat) return full_matrix def dot(self, vector, wire_order=None): """Computes the matrix-vector product of the Pauli sentence with a state vector. See pauli_sparse_matrices.md for the technical details.""" wire_order = self.wires if wire_order is None else Wires(wire_order) if not wire_order.contains_wires(self.wires): raise ValueError( "Can't get the matrix for the specified wire order because it " f"does not contain all the Pauli sentence's wires {self.wires}" ) pauli_words = list(self) # Ensure consistent ordering op_sparse_idx = _ps_to_sparse_index(pauli_words, wire_order) _, unique_sparse_structures, unique_invs = np.unique( op_sparse_idx, axis=0, return_index=True, return_inverse=True ) pw_sparse_structures = unique_sparse_structures[unique_invs] dtype = np.complex64 if vector.dtype in (np.float32, np.complex64) else np.complex128 if vector.ndim == 1: vector = vector.reshape(1, -1) mv = np.zeros_like(vector, dtype=dtype) for sparse_structure in unique_sparse_structures: indices, *_ = np.nonzero(pw_sparse_structures == sparse_structure) entries, data = self._get_same_structure_csr( [pauli_words[i] for i in indices], wire_order ) mv += vector[:, entries] * data.reshape(1, -1) return mv.reshape(vector.shape) def _get_same_structure_csr(self, pauli_words, wire_order): """Returns the CSR indices and data for Pauli words with the same sparse structure.""" indices = pauli_words[0]._get_csr_indices(wire_order) nwires = len(wire_order) nwords = len(pauli_words) inner = np.empty((nwords, 2 ** (nwires - nwires // 2)), dtype=np.complex128) outer = np.empty((nwords, 2 ** (nwires // 2)), dtype=np.complex128) for i, word in enumerate(pauli_words): outer[i, :], inner[i, :] = word._get_csr_data_2( wire_order, coeff=qml.math.to_numpy(self[word]) ) data = outer.T @ inner return indices, data.ravel() def _sum_same_structure_pws_dense(self, pauli_words, wire_order): matrix_size = 2 ** (len(wire_order)) base_matrix = sparse.csr_matrix((matrix_size, matrix_size), dtype="complex128") data0 = pauli_words[0]._get_csr_data(wire_order, 1) base_matrix.data = np.ones_like(data0) base_matrix.indices = pauli_words[0]._get_csr_indices(wire_order) base_matrix.indptr = _cached_arange( matrix_size + 1 ) # Non-zero entries by row (starting from 0) base_matrix = base_matrix.toarray() coeff = self[pauli_words[0]] ml_interface = qml.math.get_interface(coeff) if ml_interface == "torch": data0 = qml.math.convert_like(data0, coeff) data = coeff * data0 for pw in pauli_words[1:]: coeff = self[pw] csr_data = pw._get_csr_data(wire_order, 1) ml_interface = qml.math.get_interface(coeff) if ml_interface == "torch": csr_data = qml.math.convert_like(csr_data, coeff) data += self[pw] * csr_data return qml.math.einsum("ij,i->ij", base_matrix, data) def _sum_same_structure_pws(self, pauli_words, wire_order): """Sums Pauli words with the same sparse structure.""" mat = pauli_words[0].to_mat( wire_order, coeff=qml.math.to_numpy(self[pauli_words[0]]), format="csr" ) for word in pauli_words[1:]: mat.data += word.to_mat( wire_order, coeff=qml.math.to_numpy(self[word]), format="csr" ).data return mat @staticmethod def _sum_different_structure_pws(indices, data): """Sums Pauli words with different parse structures.""" size = indices.shape[0] idx = np.argsort(indices, axis=1) matrix = sparse.csr_matrix((size, size), dtype="complex128") matrix.indices = np.take_along_axis(indices, idx, axis=1).ravel() matrix.data = np.take_along_axis(data, idx, axis=1).ravel() num_entries_per_row = indices.shape[1] matrix.indptr = _cached_arange(size + 1) * num_entries_per_row # remove zeros and things sufficiently close to zero matrix.data[np.abs(matrix.data) < 1e-16] = 0 # Faster than np.isclose(matrix.data, 0) matrix.eliminate_zeros() return matrix def operation(self, wire_order=None): """Returns a native PennyLane :class:`~pennylane.operation.Operation` representing the PauliSentence.""" if len(self) == 0: return qml.s_prod(0, Identity(wires=wire_order)) summands = [] wire_order = wire_order or self.wires for pw, coeff in self.items(): pw_op = pw.operation(wire_order=list(wire_order)) rep = PauliSentence({pw: coeff}) summands.append(pw_op if coeff == 1 else SProd(coeff, pw_op, _pauli_rep=rep)) return summands[0] if len(summands) == 1 else Sum(*summands, _pauli_rep=self) def hamiltonian(self, wire_order=None): """Returns a native PennyLane :class:`~pennylane.Hamiltonian` representing the PauliSentence.""" if len(self) == 0: if wire_order in (None, [], Wires([])): raise ValueError("Can't get the Hamiltonian for an empty PauliSentence.") return qml.Hamiltonian([], []) wire_order = wire_order or self.wires wire_order = list(wire_order) return qml.Hamiltonian( list(self.values()), [pw.operation(wire_order=wire_order, get_as_tensor=True) for pw in self], ) def simplify(self, tol=1e-8): """Remove any PauliWords in the PauliSentence with coefficients less than the threshold tolerance.""" items = list(self.items()) for pw, coeff in items: if abs(coeff) <= tol: del self[pw] if len(self) == 0: self = PauliSentence({}) # pylint: disable=self-cls-assignment def map_wires(self, wire_map: dict) -> "PauliSentence": """Return a new PauliSentence with the wires mapped.""" return self.__class__({pw.map_wires(wire_map): coeff for pw, coeff in self.items()})
pennylane/pennylane/pauli/pauli_arithmetic.py/0
{ "file_path": "pennylane/pennylane/pauli/pauli_arithmetic.py", "repo_id": "pennylane", "token_count": 17808 }
64
# Copyright 2018-2021 Xanadu Quantum Technologies Inc. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. r""" Methods for generating QAOA cost Hamiltonians corresponding to different optimization problems. """ # pylint: disable=unnecessary-lambda-assignment from collections.abc import Iterable from typing import Union import networkx as nx import rustworkx as rx import pennylane as qml from pennylane import qaoa ######################## # Hamiltonian components def bit_driver(wires: Union[Iterable, qaoa.Wires], b: int): r"""Returns the bit-driver cost Hamiltonian. This Hamiltonian is defined as: .. math:: H \ = \ (-1)^{b + 1} \displaystyle\sum_{i} Z_i where :math:`Z_i` is the Pauli-Z operator acting on the :math:`i`-th wire and :math:`b \ \in \ \{0, \ 1\}`. This Hamiltonian is often used when constructing larger QAOA cost Hamiltonians. Args: wires (Iterable or Wires): The wires on which the Hamiltonian acts b (int): Either :math:`0` or :math:`1`. Determines whether the Hamiltonian assigns lower energies to bitstrings with a majority of bits being :math:`0` or a majority of bits being :math:`1`, respectively. Returns: .Hamiltonian: **Example** >>> wires = range(3) >>> hamiltonian = qaoa.bit_driver(wires, 1) >>> print(hamiltonian) 1 * Z(0) + 1 * Z(1) + 1 * Z(2) """ if b == 0: coeffs = [-1 for _ in wires] elif b == 1: coeffs = [1 for _ in wires] else: raise ValueError(f"'b' must be either 0 or 1, got {b}") ops = [qml.Z(w) for w in wires] return qml.Hamiltonian(coeffs, ops) def edge_driver(graph: Union[nx.Graph, rx.PyGraph], reward: list): r"""Returns the edge-driver cost Hamiltonian. Given some graph, :math:`G` with each node representing a wire, and a binary colouring where each node/wire is assigned either :math:`|0\rangle` or :math:`|1\rangle`, the edge driver cost Hamiltonian will assign a lower energy to edges represented by qubit states with endpoint colourings supplied in ``reward``. For instance, if ``reward`` is ``["11"]``, then edges with both endpoints coloured as ``1`` (the state :math:`|11\rangle`) will be assigned a lower energy, while the other colourings (``"00"``, ``"10"``, and ``"01"`` corresponding to states :math:`|00\rangle`, :math:`|10\rangle`, and :math:`|10\rangle`, respectively) will be assigned a higher energy. See usage details for more information. Args: graph (nx.Graph or rx.PyGraph): The graph on which the Hamiltonian is defined reward (list[str]): The list of two-bit bitstrings that are assigned a lower energy by the Hamiltonian Returns: .Hamiltonian: **Example** >>> import networkx as nx >>> graph = nx.Graph([(0, 1), (1, 2)]) >>> hamiltonian = qaoa.edge_driver(graph, ["11", "10", "01"]) >>> print(hamiltonian) 0.25 * (Z(0) @ Z(1)) + 0.25 * Z(0) + 0.25 * Z(1) + 0.25 * (Z(1) @ Z(2)) + 0.25 * Z(1) + 0.25 * Z(2) >>> import rustworkx as rx >>> graph = rx.PyGraph() >>> graph.add_nodes_from([0, 1, 2]) >>> graph.add_edges_from([(0, 1,""), (1,2,"")]) >>> hamiltonian = qaoa.edge_driver(graph, ["11", "10", "01"]) >>> print(hamiltonian) 0.25 * (Z(0) @ Z(1)) + 0.25 * Z(0) + 0.25 * Z(1) + 0.25 * (Z(1) @ Z(2)) + 0.25 * Z(1) + 0.25 * Z(2) In the above example, ``"11"``, ``"10"``, and ``"01"`` are assigned a lower energy than ``"00"``. For example, a quick calculation of expectation values gives us: .. math:: \langle 000 | H | 000 \rangle \ = \ 1.5 .. math:: \langle 100 | H | 100 \rangle \ = \ 0.5 .. math:: \langle 110 | H | 110\rangle \ = \ -0.5 In the first example, both vertex pairs are not in ``reward``. In the second example, one pair is in ``reward`` and the other is not. Finally, in the third example, both pairs are in ``reward``. .. details:: :title: Usage Details The goal of many combinatorial problems that can be solved with QAOA is to find a `Graph colouring <https://en.wikipedia.org/wiki/Graph_coloring>`__ of some supplied graph :math:`G`, that minimizes some cost function. With QAOA, it is natural to consider the class of graph colouring problems that only admit two colours, as we can easily encode these two colours using the :math:`|1\rangle` and :math:`|0\rangle` states of qubits. Therefore, given some graph :math:`G`, each edge of the graph can be described by a pair of qubits, :math:`|00\rangle`, :math:`|01\rangle`, :math:`|10\rangle`, or :math:`|11\rangle`, corresponding to the colourings of its endpoints. When constructing QAOA cost functions, one must "penalize" certain states of the graph, and "reward" others, by assigning higher and lower energies to these respective configurations. Given a set of vertex-colour pairs (which each describe a possible state of a graph edge), the ``edge_driver()`` function outputs a Hamiltonian that rewards the pairs in the set, and penalizes the others. For example, given the reward set: :math:`\{|00\rangle, \ |01\rangle, \ |10\rangle\}` and the graph :math:`G`, the ``edge_driver()`` function will output the following Hamiltonian: .. math:: H \ = \ \frac{1}{4} \displaystyle\sum_{(i, j) \in E(G)} \big( Z_{i} Z_{j} \ - \ Z_{i} \ - \ Z_{j} \big) where :math:`E(G)` is the set of edges of :math:`G`, and :math:`Z_i` is the Pauli-Z operator acting on the :math:`i`-th wire. As can be checked, this Hamiltonian assigns an energy of :math:`-1/4` to the states :math:`|00\rangle`, :math:`|01\rangle` and :math:`|10\rangle`, and an energy of :math:`3/4` to the state :math:`|11\rangle`. .. Note:: ``reward`` must always contain both :math:`|01\rangle` and :math:`|10\rangle`, or neither of the two. Within an undirected graph, there is no notion of "order" of edge endpoints, so these two states are effectively the same. Therefore, there is no well-defined way to penalize one and reward the other. .. Note:: The absolute difference in energy between colourings in ``reward`` and colourings in its complement is always :math:`1`. """ allowed = ["00", "01", "10", "11"] if not all(e in allowed for e in reward): raise ValueError("Encountered invalid entry in 'reward', expected 2-bit bitstrings.") if "01" in reward and "10" not in reward or "10" in reward and "01" not in reward: raise ValueError( "'reward' cannot contain either '10' or '01', must contain neither or both." ) if not isinstance(graph, (nx.Graph, rx.PyGraph)): raise ValueError( f"Input graph must be a nx.Graph or rx.PyGraph, got {type(graph).__name__}" ) coeffs = [] ops = [] is_rx = isinstance(graph, rx.PyGraph) graph_nodes = graph.nodes() graph_edges = sorted(graph.edge_list()) if is_rx else graph.edges # In RX each node is assigned to an integer index starting from 0; # thus, we use the following lambda function to get node-values. get_nvalue = lambda i: graph_nodes[i] if is_rx else i if len(reward) == 0 or len(reward) == 4: coeffs = [1 for _ in graph_nodes] ops = [qml.Identity(v) for v in graph_nodes] else: reward = list(set(reward) - {"01"}) sign = -1 if len(reward) == 2: reward = list({"00", "10", "11"} - set(reward)) sign = 1 reward = reward[0] if reward == "00": for e in graph_edges: coeffs.extend([0.25 * sign, 0.25 * sign, 0.25 * sign]) ops.extend( [ qml.Z(get_nvalue(e[0])) @ qml.Z(get_nvalue(e[1])), qml.Z(get_nvalue(e[0])), qml.Z(get_nvalue(e[1])), ] ) if reward == "10": for e in graph_edges: coeffs.append(-0.5 * sign) ops.append(qml.Z(get_nvalue(e[0])) @ qml.Z(get_nvalue(e[1]))) if reward == "11": for e in graph_edges: coeffs.extend([0.25 * sign, -0.25 * sign, -0.25 * sign]) ops.extend( [ qml.Z(get_nvalue(e[0])) @ qml.Z(get_nvalue(e[1])), qml.Z(get_nvalue(e[0])), qml.Z(get_nvalue(e[1])), ] ) return qml.Hamiltonian(coeffs, ops) ####################### # Optimization problems def maxcut(graph: Union[nx.Graph, rx.PyGraph]): r"""Returns the QAOA cost Hamiltonian and the recommended mixer corresponding to the MaxCut problem, for a given graph. The goal of the MaxCut problem for a particular graph is to find a partition of nodes into two sets, such that the number of edges in the graph with endpoints in different sets is maximized. Formally, we wish to find the `cut of the graph <https://en.wikipedia.org/wiki/Cut_(graph_theory)>`__ such that the number of edges crossing the cut is maximized. The MaxCut cost Hamiltonian is defined as: .. math:: H_C \ = \ \frac{1}{2} \displaystyle\sum_{(i, j) \in E(G)} \big( Z_i Z_j \ - \ \mathbb{I} \big), where :math:`G` is a graph, :math:`\mathbb{I}` is the identity, and :math:`Z_i` and :math:`Z_j` are the Pauli-Z operators on the :math:`i`-th and :math:`j`-th wire respectively. The mixer Hamiltonian returned from :func:`~qaoa.maxcut` is :func:`~qaoa.x_mixer` applied to all wires. .. note:: **Recommended initialization circuit:** Even superposition over all basis states Args: graph (nx.Graph or rx.PyGraph): a graph defining the pairs of wires on which each term of the Hamiltonian acts Returns: (.Hamiltonian, .Hamiltonian): The cost and mixer Hamiltonians **Example** >>> import networkx as nx >>> graph = nx.Graph([(0, 1), (1, 2)]) >>> cost_h, mixer_h = qml.qaoa.maxcut(graph) >>> print(cost_h) 0.5 * (Z(0) @ Z(1)) + 0.5 * (Z(1) @ Z(2)) + -0.5 * (I(0) @ I(1)) + -0.5 * (I(1) @ I(2)) >>> print(mixer_h) 1 * X(0) + 1 * X(1) + 1 * X(2) >>> import rustworkx as rx >>> graph = rx.PyGraph() >>> graph.add_nodes_from([0, 1, 2]) >>> graph.add_edges_from([(0, 1,""), (1,2,"")]) >>> cost_h, mixer_h = qml.qaoa.maxcut(graph) >>> print(cost_h) 0.5 * (Z(0) @ Z(1)) + 0.5 * (Z(1) @ Z(2)) + -0.5 * (I(0) @ I(1)) + -0.5 * (I(1) @ I(2)) >>> print(mixer_h) 1 * X(0) + 1 * X(1) + 1 * X(2) """ if not isinstance(graph, (nx.Graph, rx.PyGraph)): raise ValueError( f"Input graph must be a nx.Graph or rx.PyGraph, got {type(graph).__name__}" ) is_rx = isinstance(graph, rx.PyGraph) graph_nodes = graph.nodes() graph_edges = sorted(graph.edge_list()) if is_rx else graph.edges # In RX each node is assigned to an integer index starting from 0; # thus, we use the following lambda function to get node-values. get_nvalue = lambda i: graph_nodes[i] if is_rx else i identity_h = qml.Hamiltonian( [-0.5 for e in graph_edges], [qml.Identity(get_nvalue(e[0])) @ qml.Identity(get_nvalue(e[1])) for e in graph_edges], ) H = edge_driver(graph, ["10", "01"]) + identity_h # store the valuable information that all observables are in one commuting group H.grouping_indices = [list(range(len(H.ops)))] return (H, qaoa.x_mixer(graph_nodes)) def max_independent_set(graph: Union[nx.Graph, rx.PyGraph], constrained: bool = True): r"""For a given graph, returns the QAOA cost Hamiltonian and the recommended mixer corresponding to the Maximum Independent Set problem. Given some graph :math:`G`, an independent set is a set of vertices such that no pair of vertices in the set share a common edge. The Maximum Independent Set problem, is the problem of finding the largest such set. Args: graph (nx.Graph or rx.PyGraph): a graph whose edges define the pairs of vertices on which each term of the Hamiltonian acts constrained (bool): specifies the variant of QAOA that is performed (constrained or unconstrained) Returns: (.Hamiltonian, .Hamiltonian): The cost and mixer Hamiltonians .. details:: :title: Usage Details There are two variations of QAOA for this problem, constrained and unconstrained: **Constrained** .. note:: This method of constrained QAOA was introduced by `Hadfield, Wang, Gorman, Rieffel, Venturelli, and Biswas (2019) <https://doi.org/10.3390/a12020034>`__. The Maximum Independent Set cost Hamiltonian for constrained QAOA is defined as: .. math:: H_C \ = \ \displaystyle\sum_{v \in V(G)} Z_{v}, where :math:`V(G)` is the set of vertices of the input graph, and :math:`Z_i` is the Pauli-Z operator applied to the :math:`i`-th vertex. The returned mixer Hamiltonian is :func:`~qaoa.bit_flip_mixer` applied to :math:`G`. .. note:: **Recommended initialization circuit:** Each wire in the :math:`|0\rangle` state. **Unconstrained** The Maximum Independent Set cost Hamiltonian for unconstrained QAOA is defined as: .. math:: H_C \ = \ 3 \sum_{(i, j) \in E(G)} (Z_i Z_j \ - \ Z_i \ - \ Z_j) \ + \ \displaystyle\sum_{i \in V(G)} Z_i where :math:`E(G)` is the set of edges of :math:`G`, :math:`V(G)` is the set of vertices, and :math:`Z_i` is the Pauli-Z operator acting on the :math:`i`-th vertex. The returned mixer Hamiltonian is :func:`~qaoa.x_mixer` applied to all wires. .. note:: **Recommended initialization circuit:** Even superposition over all basis states. """ if not isinstance(graph, (nx.Graph, rx.PyGraph)): raise ValueError( f"Input graph must be a nx.Graph or rx.PyGraph, got {type(graph).__name__}" ) graph_nodes = graph.nodes() if constrained: cost_h = bit_driver(graph_nodes, 1) cost_h.grouping_indices = [list(range(len(cost_h.ops)))] return (cost_h, qaoa.bit_flip_mixer(graph, 0)) cost_h = 3 * edge_driver(graph, ["10", "01", "00"]) + bit_driver(graph_nodes, 1) mixer_h = qaoa.x_mixer(graph_nodes) # store the valuable information that all observables are in one commuting group cost_h.grouping_indices = [list(range(len(cost_h.ops)))] return (cost_h, mixer_h) def min_vertex_cover(graph: Union[nx.Graph, rx.PyGraph], constrained: bool = True): r"""Returns the QAOA cost Hamiltonian and the recommended mixer corresponding to the Minimum Vertex Cover problem, for a given graph. To solve the Minimum Vertex Cover problem, we attempt to find the smallest `vertex cover <https://en.wikipedia.org/wiki/Vertex_cover>`__ of a graph --- a collection of vertices such that every edge in the graph has one of the vertices as an endpoint. Args: graph (nx.Graph or rx.PyGraph): a graph whose edges define the pairs of vertices on which each term of the Hamiltonian acts constrained (bool): specifies the variant of QAOA that is performed (constrained or unconstrained) Returns: (.Hamiltonian, .Hamiltonian): The cost and mixer Hamiltonians .. details:: :title: Usage Details There are two variations of QAOA for this problem, constrained and unconstrained: **Constrained** .. note:: This method of constrained QAOA was introduced by Hadfield, Wang, Gorman, Rieffel, Venturelli, and Biswas in arXiv:1709.03489. The Minimum Vertex Cover cost Hamiltonian for constrained QAOA is defined as: .. math:: H_C \ = \ - \displaystyle\sum_{v \in V(G)} Z_{v}, where :math:`V(G)` is the set of vertices of the input graph, and :math:`Z_i` is the Pauli-Z operator applied to the :math:`i`-th vertex. The returned mixer Hamiltonian is :func:`~qaoa.bit_flip_mixer` applied to :math:`G`. .. note:: **Recommended initialization circuit:** Each wire in the :math:`|1\rangle` state. **Unconstrained** The Minimum Vertex Cover cost Hamiltonian for unconstrained QAOA is defined as: .. math:: H_C \ = \ 3 \sum_{(i, j) \in E(G)} (Z_i Z_j \ + \ Z_i \ + \ Z_j) \ - \ \displaystyle\sum_{i \in V(G)} Z_i where :math:`E(G)` is the set of edges of :math:`G`, :math:`V(G)` is the set of vertices, and :math:`Z_i` is the Pauli-Z operator acting on the :math:`i`-th vertex. The returned mixer Hamiltonian is :func:`~qaoa.x_mixer` applied to all wires. .. note:: **Recommended initialization circuit:** Even superposition over all basis states. """ if not isinstance(graph, (nx.Graph, rx.PyGraph)): raise ValueError( f"Input graph must be a nx.Graph or rx.PyGraph, got {type(graph).__name__}" ) graph_nodes = graph.nodes() if constrained: cost_h = bit_driver(graph_nodes, 0) cost_h.grouping_indices = [list(range(len(cost_h.ops)))] return (cost_h, qaoa.bit_flip_mixer(graph, 1)) cost_h = 3 * edge_driver(graph, ["11", "10", "01"]) + bit_driver(graph_nodes, 0) mixer_h = qaoa.x_mixer(graph_nodes) # store the valuable information that all observables are in one commuting group cost_h.grouping_indices = [list(range(len(cost_h.ops)))] return (cost_h, mixer_h) def max_clique(graph: Union[nx.Graph, rx.PyGraph], constrained: bool = True): r"""Returns the QAOA cost Hamiltonian and the recommended mixer corresponding to the Maximum Clique problem, for a given graph. The goal of Maximum Clique is to find the largest `clique <https://en.wikipedia.org/wiki/Clique_(graph_theory)>`__ of a graph --- the largest subgraph such that all vertices are connected by an edge. Args: graph (nx.Graph or rx.PyGraph): a graph whose edges define the pairs of vertices on which each term of the Hamiltonian acts constrained (bool): specifies the variant of QAOA that is performed (constrained or unconstrained) Returns: (.Hamiltonian, .Hamiltonian): The cost and mixer Hamiltonians .. details:: :title: Usage Details There are two variations of QAOA for this problem, constrained and unconstrained: **Constrained** .. note:: This method of constrained QAOA was introduced by Hadfield, Wang, Gorman, Rieffel, Venturelli, and Biswas in arXiv:1709.03489. The Maximum Clique cost Hamiltonian for constrained QAOA is defined as: .. math:: H_C \ = \ \displaystyle\sum_{v \in V(G)} Z_{v}, where :math:`V(G)` is the set of vertices of the input graph, and :math:`Z_i` is the Pauli-Z operator applied to the :math:`i`-th vertex. The returned mixer Hamiltonian is :func:`~qaoa.bit_flip_mixer` applied to :math:`\bar{G}`, the complement of the graph. .. note:: **Recommended initialization circuit:** Each wire in the :math:`|0\rangle` state. **Unconstrained** The Maximum Clique cost Hamiltonian for unconstrained QAOA is defined as: .. math:: H_C \ = \ 3 \sum_{(i, j) \in E(\bar{G})} (Z_i Z_j \ - \ Z_i \ - \ Z_j) \ + \ \displaystyle\sum_{i \in V(G)} Z_i where :math:`V(G)` is the set of vertices of the input graph :math:`G`, :math:`E(\bar{G})` is the set of edges of the complement of :math:`G`, and :math:`Z_i` is the Pauli-Z operator applied to the :math:`i`-th vertex. The returned mixer Hamiltonian is :func:`~qaoa.x_mixer` applied to all wires. .. note:: **Recommended initialization circuit:** Even superposition over all basis states. """ if not isinstance(graph, (nx.Graph, rx.PyGraph)): raise ValueError( f"Input graph must be a nx.Graph or rx.PyGraph, got {type(graph).__name__}" ) graph_nodes = graph.nodes() graph_complement = ( rx.complement(graph) if isinstance(graph, rx.PyGraph) else nx.complement(graph) ) if constrained: cost_h = bit_driver(graph_nodes, 1) cost_h.grouping_indices = [list(range(len(cost_h.ops)))] return (cost_h, qaoa.bit_flip_mixer(graph_complement, 0)) cost_h = 3 * edge_driver(graph_complement, ["10", "01", "00"]) + bit_driver(graph_nodes, 1) mixer_h = qaoa.x_mixer(graph_nodes) # store the valuable information that all observables are in one commuting group cost_h.grouping_indices = [list(range(len(cost_h.ops)))] return (cost_h, mixer_h) def max_weight_cycle(graph: Union[nx.Graph, rx.PyGraph, rx.PyDiGraph], constrained: bool = True): r"""Returns the QAOA cost Hamiltonian and the recommended mixer corresponding to the maximum-weighted cycle problem, for a given graph. The maximum-weighted cycle problem is defined in the following way (see `here <https://1qbit.com/whitepaper/arbitrage/>`__ for more details). The product of weights of a subset of edges in a graph is given by .. math:: P = \prod_{(i, j) \in E} [(c_{ij} - 1)x_{ij} + 1] where :math:`E` are the edges of the graph, :math:`x_{ij}` is a binary number that selects whether to include the edge :math:`(i, j)` and :math:`c_{ij}` is the corresponding edge weight. Our objective is to maximimize :math:`P`, subject to selecting the :math:`x_{ij}` so that our subset of edges composes a `cycle <https://en.wikipedia.org/wiki/Cycle_(graph_theory)>`__. Args: graph (nx.Graph or rx.PyGraph or rx.PyDiGraph): the directed graph on which the Hamiltonians are defined constrained (bool): specifies the variant of QAOA that is performed (constrained or unconstrained) Returns: (.Hamiltonian, .Hamiltonian, dict): The cost and mixer Hamiltonians, as well as a dictionary mapping from wires to the graph's edges .. details:: :title: Usage Details There are two variations of QAOA for this problem, constrained and unconstrained: **Constrained** .. note:: This method of constrained QAOA was introduced by Hadfield, Wang, Gorman, Rieffel, Venturelli, and Biswas in `arXiv:1709.03489 <https://arxiv.org/abs/1709.03489>`__. The maximum weighted cycle cost Hamiltonian for unconstrained QAOA is .. math:: H_C = H_{\rm loss}. Here, :math:`H_{\rm loss}` is a loss Hamiltonian: .. math:: H_{\rm loss} = \sum_{(i, j) \in E} Z_{ij}\log c_{ij} where :math:`E` are the edges of the graph and :math:`Z_{ij}` is a qubit Pauli-Z matrix acting upon the wire specified by the edge :math:`(i, j)` (see :func:`~.loss_hamiltonian` for more details). The returned mixer Hamiltonian is :func:`~.cycle_mixer` given by .. math:: H_M = \frac{1}{4}\sum_{(i, j)\in E} \left(\sum_{k \in V, k\neq i, k\neq j, (i, k) \in E, (k, j) \in E} \left[X_{ij}X_{ik}X_{kj} +Y_{ij}Y_{ik}X_{kj} + Y_{ij}X_{ik}Y_{kj} - X_{ij}Y_{ik}Y_{kj}\right] \right). This mixer provides transitions between collections of cycles, i.e., any subset of edges in :math:`E` such that all the graph's nodes :math:`V` have zero net flow (see the :func:`~.net_flow_constraint` function). .. note:: **Recommended initialization circuit:** Your circuit must prepare a state that corresponds to a cycle (or a superposition of cycles). Follow the example code below to see how this is done. **Unconstrained** The maximum weighted cycle cost Hamiltonian for constrained QAOA is defined as: .. math:: H_C \ = H_{\rm loss} + 3 H_{\rm netflow} + 3 H_{\rm outflow}. The netflow constraint Hamiltonian :func:`~.net_flow_constraint` is given by .. math:: H_{\rm netflow} = \sum_{i \in V} \left((d_{i}^{\rm out} - d_{i}^{\rm in})\mathbb{I} - \sum_{j, (i, j) \in E} Z_{ij} + \sum_{j, (j, i) \in E} Z_{ji} \right)^{2}, where :math:`d_{i}^{\rm out}` and :math:`d_{i}^{\rm in}` are the outdegree and indegree, respectively, of node :math:`i`. It is minimized whenever a subset of edges in :math:`E` results in zero net flow from each node in :math:`V`. The outflow constraint Hamiltonian :func:`~.out_flow_constraint` is given by .. math:: H_{\rm outflow} = \sum_{i\in V}\left(d_{i}^{out}(d_{i}^{out} - 2)\mathbb{I} - 2(d_{i}^{out}-1)\sum_{j,(i,j)\in E}\hat{Z}_{ij} + \left( \sum_{j,(i,j)\in E}\hat{Z}_{ij} \right)^{2}\right). It is minimized whenever a subset of edges in :math:`E` results in an outflow of at most one from each node in :math:`V`. The returned mixer Hamiltonian is :func:`~.x_mixer` applied to all wires. .. note:: **Recommended initialization circuit:** Even superposition over all basis states. **Example** First set up a simple graph: .. code-block:: python import pennylane as qml import numpy as np import networkx as nx a = np.random.random((4, 4)) np.fill_diagonal(a, 0) g = nx.DiGraph(a) The cost and mixer Hamiltonian as well as the mapping from wires to edges can be loaded using: >>> cost, mixer, mapping = qml.qaoa.max_weight_cycle(g, constrained=True) Since we are using ``constrained=True``, we must ensure that the input state to the QAOA algorithm corresponds to a cycle. Consider the mapping: >>> mapping {0: (0, 1), 1: (0, 2), 2: (0, 3), 3: (1, 0), 4: (1, 2), 5: (1, 3), 6: (2, 0), 7: (2, 1), 8: (2, 3), 9: (3, 0), 10: (3, 1), 11: (3, 2)} A simple cycle is given by the edges ``(0, 1)`` and ``(1, 0)`` and corresponding wires ``0`` and ``3``. Hence, the state :math:`|100100000000\rangle` corresponds to a cycle and can be prepared using :class:`~.BasisState` or simple :class:`~.PauliX` rotations on the ``0`` and ``3`` wires. """ if not isinstance(graph, (nx.Graph, rx.PyGraph, rx.PyDiGraph)): raise ValueError( f"Input graph must be a nx.Graph or rx.PyGraph or rx.PyDiGraph, got {type(graph).__name__}" ) mapping = qaoa.cycle.wires_to_edges(graph) if constrained: cost_h = qaoa.cycle.loss_hamiltonian(graph) cost_h.grouping_indices = [list(range(len(cost_h.ops)))] return (cost_h, qaoa.cycle.cycle_mixer(graph), mapping) cost_h = qaoa.cycle.loss_hamiltonian(graph) + 3 * ( qaoa.cycle.net_flow_constraint(graph) + qaoa.cycle.out_flow_constraint(graph) ) mixer_h = qaoa.x_mixer(mapping.keys()) return (cost_h, mixer_h, mapping)
pennylane/pennylane/qaoa/cost.py/0
{ "file_path": "pennylane/pennylane/qaoa/cost.py", "repo_id": "pennylane", "token_count": 11568 }
65
# Copyright 2018-2021 Xanadu Quantum Technologies Inc. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ This module contains functions and classes to create a :class:`~pennylane.qchem.molecule.Molecule` object. This object stores all the necessary information to perform a Hartree-Fock calculation for a given molecule. """ import collections # pylint: disable=too-few-public-methods, too-many-arguments, too-many-instance-attributes import itertools from pennylane import numpy as pnp from .basis_data import atomic_numbers from .basis_set import BasisFunction, mol_basis_data from .integrals import contracted_norm, primitive_norm # Bohr-Angstrom correlation coefficient (https://physics.nist.gov/cgi-bin/cuu/Value?bohrrada0) bohr_angs = 0.529177210903 class Molecule: r"""Create a molecule object that stores molecular information and default basis set parameters. The molecule object can be passed to functions that perform a Hartree-Fock calculation. Args: symbols (list[str]): Symbols of the atomic species in the molecule. Currently, atoms with atomic numbers 1-10 are supported. coordinates (array[float]): 1D array with the atomic positions in Cartesian coordinates. The coordinates must be given in atomic units and the size of the array should be ``3*N`` where ``N`` is the number of atoms. charge (int): net charge of the molecule mult (int): Spin multiplicity :math:`\mathrm{mult}=N_\mathrm{unpaired} + 1` for :math:`N_\mathrm{unpaired}` unpaired electrons occupying the HF orbitals. basis_name (str): Atomic basis set used to represent the molecular orbitals. Currently, the only supported basis sets are ``STO-3G``, ``6-31G``, ``6-311G`` and ``CC-PVDZ``. Other basis sets can be loaded from the basis-set-exchange library using ``load_data``. load_data (bool): flag to load data from the basis-set-exchange library l (tuple[int]): angular momentum quantum numbers of the basis function alpha (array[float]): exponents of the primitive Gaussian functions coeff (array[float]): coefficients of the contracted Gaussian functions r (array[float]): positions of the Gaussian functions normalize (bool): if True, the basis functions get normalized unit (str): unit of atomic coordinates. Available options are ``unit="bohr"`` and ``unit="angstrom"``. **Example** >>> symbols = ['H', 'H'] >>> geometry = np.array([[0.0, 0.0, -0.694349], >>> [0.0, 0.0, 0.694349]], requires_grad = True) >>> mol = Molecule(symbols, geometry) >>> print(mol.n_electrons) 2 """ def __init__( self, symbols, coordinates, charge=0, mult=1, basis_name="sto-3g", name="molecule", load_data=False, l=None, alpha=None, coeff=None, normalize=True, unit="bohr", ): if ( basis_name.lower() not in [ "sto-3g", "6-31g", "6-311g", "cc-pvdz", ] and load_data is False ): raise ValueError( "Currently, the only supported basis sets are 'sto-3g', '6-31g', '6-311g' and " "'cc-pvdz'. Please consider using `load_data=True` to download the basis set from " "an external library that can be installed with: pip install basis-set-exchange." ) if set(symbols) - set(atomic_numbers): raise ValueError(f"Atoms in {set(symbols) - set(atomic_numbers)} are not supported.") self.symbols = symbols self.coordinates = coordinates self.unit = unit.strip().lower() self.charge = charge self.mult = mult self.basis_name = basis_name.lower() self.name = name self.load_data = load_data self.n_basis, self.basis_data = mol_basis_data(self.basis_name, self.symbols, load_data) if self.unit not in ("angstrom", "bohr"): raise ValueError( f"The provided unit '{unit}' is not supported. " f"Please set 'unit' to 'bohr' or 'angstrom'." ) if self.unit == "angstrom": self.coordinates = self.coordinates / bohr_angs self.nuclear_charges = [atomic_numbers[s] for s in self.symbols] self.n_electrons = sum(self.nuclear_charges) - self.charge if l is None: l = [i[0] for i in self.basis_data] if alpha is None: alpha = [pnp.array(i[1], requires_grad=False) for i in self.basis_data] if coeff is None: coeff = [pnp.array(i[2], requires_grad=False) for i in self.basis_data] if normalize: coeff = [ pnp.array(c * primitive_norm(l[i], alpha[i]), requires_grad=False) for i, c in enumerate(coeff) ] r = list( itertools.chain( *[[self.coordinates[i]] * self.n_basis[i] for i in range(len(self.n_basis))] ) ) self.l = l self.alpha = alpha self.coeff = coeff self.r = r self.basis_set = [ BasisFunction(self.l[i], self.alpha[i], self.coeff[i], self.r[i]) for i in range(len(l)) ] self.n_orbitals = len(self.l) self.mo_coefficients = None def __repr__(self): """Returns the molecule representation in string format""" elements, counter, flags = set(self.symbols), collections.Counter(self.symbols), [] if counter["C"]: # Hill Notation flags = ["C", "H"] if counter["H"] else ["C"] ordered_elems = flags + list(sorted(elements.difference(set(flags)))) formula = "".join([x + str(counter[x]) if counter[x] > 1 else x for x in ordered_elems]) return f"<Molecule = {formula}, Charge: {self.charge}, Basis: {self.basis_name.upper()}, Orbitals: {self.n_orbitals}, Electrons: {self.n_electrons}>" def atomic_orbital(self, index): r"""Return a function that evaluates an atomic orbital at a given position. Args: index (int): index of the atomic orbital, order follwos the order of atomic symbols Returns: function: function that computes the value of the orbital at a given position **Example** >>> symbols = ['H', 'H'] >>> geometry = np.array([[0.0, 0.0, 0.0], [0.0, 0.0, 1.0]], requires_grad = False) >>> mol = qml.qchem.Molecule(symbols, geometry) >>> ao = mol.atomic_orbital(0) >>> ao(0.0, 0.0, 0.0) 0.62824688 """ l = self.basis_set[index].l alpha = self.basis_set[index].alpha coeff = self.basis_set[index].coeff r = self.basis_set[index].r coeff = coeff * contracted_norm(l, alpha, coeff) lx, ly, lz = l def orbital(x, y, z): r"""Evaluate a basis function at a given position. Args: x (float): x component of the position y (float): y component of the position z (float): z component of the position Returns: array[float]: value of a basis function """ c = ((x - r[0]) ** lx) * ((y - r[1]) ** ly) * ((z - r[2]) ** lz) e = [pnp.exp(-a * ((x - r[0]) ** 2 + (y - r[1]) ** 2 + (z - r[2]) ** 2)) for a in alpha] return c * pnp.dot(coeff, e) return orbital def molecular_orbital(self, index): r"""Return a function that evaluates a molecular orbital at a given position. Args: index (int): index of the molecular orbital Returns: function: function to evaluate the molecular orbital **Example** >>> symbols = ['H', 'H'] >>> geometry = np.array([[0.0, 0.0, 0.0], [0.0, 0.0, 1.0]], requires_grad = False) >>> mol = qml.qchem.Molecule(symbols, geometry) >>> qml.qchem.scf(mol)() # run scf to obtain the optimized molecular orbitals >>> mo = mol.molecular_orbital(1) >>> mo(0.0, 0.0, 0.0) 0.01825128 """ # molecular coefficients are set by other modules c = self.mo_coefficients[index] # pylint:disable=unsubscriptable-object def orbital(x, y, z): r"""Evaluate a molecular orbital at a given position. Args: x (float): x component of the position y (float): y component of the position z (float): z component of the position Returns: array[float]: value of a molecular orbital """ m = 0.0 for i in range(self.n_orbitals): m = m + c[i] * self.atomic_orbital(i)(x, y, z) return m return orbital
pennylane/pennylane/qchem/molecule.py/0
{ "file_path": "pennylane/pennylane/qchem/molecule.py", "repo_id": "pennylane", "token_count": 4178 }
66
# Copyright 2018-2021 Xanadu Quantum Technologies Inc. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Code for resource estimation""" import inspect import warnings import pennylane as qml def _get_absolute_import_path(fn): return f"{inspect.getmodule(fn).__name__}.{fn.__name__}" def _determine_spec_level(kwargs, qnode): if "max_expansion" in kwargs: warnings.warn( "'max_expansion' has no effect on the output of 'specs()' and should not be used.", qml.PennyLaneDeprecationWarning, ) sentinel = object() level = kwargs.get("level", sentinel) expansion_strategy = kwargs.get("expansion_strategy", sentinel) if all(val != sentinel for val in (level, expansion_strategy)): raise ValueError("Either 'level' or 'expansion_strategy' need to be set, but not both.") if expansion_strategy != sentinel: warnings.warn( "The 'expansion_strategy' argument is deprecated and will be removed in " "version 0.39. Instead, use the 'level' argument which offers more flexibility " "and options.", qml.PennyLaneDeprecationWarning, ) if level == sentinel: if expansion_strategy == sentinel: return qnode.expansion_strategy return expansion_strategy return level def specs(qnode, **kwargs): r"""Resource information about a quantum circuit. This transform converts a QNode into a callable that provides resource information about the circuit after applying the specified amount of transforms/expansions first. Args: qnode (.QNode): the QNode to calculate the specifications for. Keyword Args: level (None, str, int, slice): An indication of what transforms to apply before computing the resource information. Check :func:`~.workflow.get_transform_program` for more information on the allowed values and usage details of this argument. expansion_strategy (str): The strategy to use when circuit expansions or decompositions are required. - ``gradient``: The QNode will attempt to decompose the internal circuit such that all circuit operations are supported by the gradient method. - ``device``: The QNode will attempt to decompose the internal circuit such that all circuit operations are natively supported by the device. max_expansion (int): The number of times the internal circuit should be expanded when calculating the specification. Defaults to ``qnode.max_expansion``. Returns: A function that has the same argument signature as ``qnode``. This function returns a dictionary (or a list of dictionaries) of information about qnode structure. .. note:: At most, one of ``level`` or ``expansion_strategy`` needs to be provided. If neither is provided, ``qnode.expansion_strategy`` will be used instead. Users are encouraged to predominantly use ``level``, as it allows for the same values as ``expansion_strategy`` and offers more flexibility in choosing the desired transforms/expansions. .. warning:: ``max_expansion`` and ``qnode.max_expansion`` have no effect on the return of this function and will be ignored. .. warning:: The ``expansion_strategy`` argument is deprecated and will be removed in version 0.39. Use the ``level`` argument instead to specify the resulting tape you want. **Example** .. code-block:: python3 from pennylane import numpy as pnp x = pnp.array([0.1, 0.2]) hamiltonian = qml.dot([1.0, 0.5], [qml.X(0), qml.Y(0)]) dev = qml.device('default.qubit', wires=2) @qml.qnode(dev, diff_method="parameter-shift", shifts=pnp.pi / 4) def circuit(x, add_ry=True): qml.RX(x[0], wires=0) qml.CNOT(wires=(0,1)) qml.TrotterProduct(hamiltonian, time=1.0, n=4, order=2) if add_ry: qml.RY(x[1], wires=1) qml.TrotterProduct(hamiltonian, time=1.0, n=4, order=4) return qml.probs(wires=(0,1)) >>> qml.specs(circuit)(x, add_ry=False) {'resources': Resources(num_wires=2, num_gates=98, gate_types=defaultdict(<class 'int'>, {'RX': 1, 'CNOT': 1, 'Exp': 96}), gate_sizes=defaultdict(<class 'int'>, {1: 97, 2: 1}), depth=98, shots=Shots(total_shots=None, shot_vector=())), 'errors': {'SpectralNormError': SpectralNormError(0.42998560822421455)}, 'num_observables': 1, 'num_diagonalizing_gates': 0, 'num_trainable_params': 1, 'num_device_wires': 2, 'num_tape_wires': 2, 'device_name': 'default.qubit', 'level': 'gradient', 'gradient_options': {'shifts': 0.7853981633974483}, 'interface': 'auto', 'diff_method': 'parameter-shift', 'gradient_fn': 'pennylane.gradients.parameter_shift.param_shift', 'num_gradient_executions': 2} .. details:: :title: Usage Details Here you can see how the number of gates and their types change as we apply different amounts of transforms through the ``level`` argument: .. code-block:: python3 @qml.transforms.merge_rotations @qml.transforms.undo_swaps @qml.transforms.cancel_inverses @qml.qnode(qml.device("default.qubit"), diff_method="parameter-shift", shifts=np.pi / 4) def circuit(x): qml.RandomLayers(qml.numpy.array([[1.0, 2.0]]), wires=(0, 1)) qml.RX(x, wires=0) qml.RX(-x, wires=0) qml.SWAP((0, 1)) qml.X(0) qml.X(0) return qml.expval(qml.X(0) + qml.Y(1)) First, we can check the resource information of the ``QNode`` without any modifications. Note that ``level=top`` would return the same results: >>> print(qml.specs(circuit, level=0)(0.1)["resources"]) wires: 2 gates: 6 depth: 6 shots: Shots(total=None) gate_types: {'RandomLayers': 1, 'RX': 2, 'SWAP': 1, 'PauliX': 2} gate_sizes: {2: 2, 1: 4} We then check the resources after applying all transforms: >>> print(qml.specs(circuit, level=None)(0.1)["resources"]) wires: 2 gates: 2 depth: 1 shots: Shots(total=None) gate_types: {'RY': 1, 'RX': 1} gate_sizes: {1: 2} We can also notice that ``SWAP`` and ``PauliX`` are not present in the circuit if we set ``level=2``: >>> print(qml.specs(circuit, level=2)(0.1)["resources"]) wires: 2 gates: 3 depth: 3 shots: Shots(total=None) gate_types: {'RandomLayers': 1, 'RX': 2} gate_sizes: {2: 1, 1: 2} If we attempt to apply only the ``merge_rotations`` transform, we end up with only one trainable object, which is in ``RandomLayers``: >>> qml.specs(circuit, level=slice(2, 3))(0.1)["num_trainable_params"] 1 However, if we apply all transforms, ``RandomLayers`` is decomposed into an ``RY`` and an ``RX``, giving us two trainable objects: >>> qml.specs(circuit, level=None)(0.1)["num_trainable_params"] 2 If a ``QNode`` with a tape-splitting transform is supplied to the function, with the transform included in the desired transforms, a dictionary is returned for each resulting tape: .. code-block:: python3 H = qml.Hamiltonian([0.2, -0.543], [qml.X(0) @ qml.Z(1), qml.Z(0) @ qml.Y(2)]) @qml.transforms.split_non_commuting @qml.qnode(qml.device("default.qubit"), diff_method="parameter-shift", shifts=np.pi / 4) def circuit(): qml.RandomLayers(qml.numpy.array([[1.0, 2.0]]), wires=(0, 1)) return qml.expval(H) >>> len(qml.specs(circuit, level="user")()) 2 """ specs_level = _determine_spec_level(kwargs, qnode) def specs_qnode(*args, **kwargs): """Returns information on the structure and makeup of provided QNode. Dictionary keys: * ``"num_operations"`` number of operations in the qnode * ``"num_observables"`` number of observables in the qnode * ``"num_diagonalizing_gates"`` number of diagonalizing gates required for execution of the qnode * ``"resources"``: a :class:`~.resource.Resources` object containing resource quantities used by the qnode * ``"errors"``: combined algorithmic errors from the quantum operations executed by the qnode * ``"num_used_wires"``: number of wires used by the circuit * ``"num_device_wires"``: number of wires in device * ``"depth"``: longest path in directed acyclic graph representation * ``"device_name"``: name of QNode device * ``"expansion_strategy"``: string specifying method for decomposing operations in the circuit * ``"gradient_options"``: additional configurations for gradient computations * ``"interface"``: autodiff framework to dispatch to for the qnode execution * ``"diff_method"``: a string specifying the differntiation method * ``"gradient_fn"``: executable to compute the gradient of the qnode Potential Additional Information: * ``"num_trainable_params"``: number of individual scalars that are trainable * ``"num_gradient_executions"``: number of times circuit will execute when calculating the derivative Returns: dict[str, Union[defaultdict,int]]: dictionaries that contain QNode specifications """ infos = [] batch, _ = qml.workflow.construct_batch(qnode, level=specs_level)(*args, **kwargs) for tape in batch: info = tape.specs.copy() info["num_device_wires"] = len(qnode.device.wires or tape.wires) info["num_tape_wires"] = tape.num_wires info["device_name"] = getattr(qnode.device, "short_name", qnode.device.name) info["level"] = specs_level info["gradient_options"] = qnode.gradient_kwargs info["interface"] = qnode.interface info["diff_method"] = ( _get_absolute_import_path(qnode.diff_method) if callable(qnode.diff_method) else qnode.diff_method ) if isinstance(qnode.gradient_fn, qml.transforms.core.TransformDispatcher): info["gradient_fn"] = _get_absolute_import_path(qnode.gradient_fn) try: info["num_gradient_executions"] = len(qnode.gradient_fn(tape)[0]) except Exception as e: # pylint: disable=broad-except # In the case of a broad exception, we don't want the `qml.specs` transform # to fail. Instead, we simply indicate that the number of gradient executions # is not supported for the reason specified. info["num_gradient_executions"] = f"NotSupported: {str(e)}" else: info["gradient_fn"] = qnode.gradient_fn infos.append(info) return infos[0] if len(infos) == 1 else infos return specs_qnode
pennylane/pennylane/resource/specs.py/0
{ "file_path": "pennylane/pennylane/resource/specs.py", "repo_id": "pennylane", "token_count": 4959 }
67
# Copyright 2018-2021 Xanadu Quantum Technologies Inc. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. r""" Contains the BasisEmbedding template. """ # pylint: disable-msg=too-many-branches,too-many-arguments,protected-access from pennylane.ops.qubit.state_preparation import BasisState class BasisEmbedding(BasisState): r"""Encodes :math:`n` binary features into a basis state of :math:`n` qubits. For example, for ``features=np.array([0, 1, 0])`` or ``features=2`` (binary 010), the quantum system will be prepared in state :math:`|010 \rangle`. .. warning:: ``BasisEmbedding`` calls a circuit whose architecture depends on the binary features. The ``features`` argument is therefore not differentiable when using the template, and gradients with respect to the argument cannot be computed by PennyLane. Args: features (tensor_like or int): binary input of shape ``(len(wires), )`` or integer that represents the binary input. wires (Any or Iterable[Any]): wires that the template acts on. Example: Basis embedding encodes the binary feature vector into a basis state. .. code-block:: python dev = qml.device('default.qubit', wires=3) @qml.qnode(dev) def circuit(feature_vector): qml.BasisEmbedding(features=feature_vector, wires=range(3)) return qml.state() X = [1,1,1] The resulting circuit is: >>> print(qml.draw(circuit, level="device")(X)) 0: ──X─┤ State 1: ──X─┤ State 2: ──X─┤ State And, the output state is: >>> print(circuit(X)) [0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j 1.+0.j] Thus, ``[1,1,1]`` is mapped to :math:`|111 \rangle`. """ def __init__(self, features, wires, id=None): super().__init__(features, wires=wires, id=id)
pennylane/pennylane/templates/embeddings/basis.py/0
{ "file_path": "pennylane/pennylane/templates/embeddings/basis.py", "repo_id": "pennylane", "token_count": 937 }
68
# Copyright 2018-2021 Xanadu Quantum Technologies Inc. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. r""" Contains the ArbitraryStatePreparation template. """ # pylint: disable=trailing-comma-tuple import functools import pennylane as qml from pennylane.operation import AnyWires, Operation @functools.lru_cache() def _state_preparation_pauli_words(num_wires): """Pauli words necessary for a state preparation. Args: num_wires (int): Number of wires of the state preparation Returns: List[str]: List of all necessary Pauli words for the state preparation """ if num_wires == 1: return ["X", "Y"] sub_pauli_words = _state_preparation_pauli_words(num_wires - 1) sub_id = "I" * (num_wires - 1) single_qubit_words = ["X" + sub_id, "Y" + sub_id] multi_qubit_words = list(map(lambda word: "I" + word, sub_pauli_words)) + list( map(lambda word: "X" + word, sub_pauli_words) ) return single_qubit_words + multi_qubit_words class ArbitraryStatePreparation(Operation): """Implements an arbitrary state preparation on the specified wires. An arbitrary state on :math:`n` wires is parametrized by :math:`2^{n+1} - 2` independent real parameters. This templates uses Pauli word rotations to parametrize the unitary. Args: weights (tensor_like): Angles of the Pauli word rotations. Needs to have length :math:`2^{n+1} - 2` where :math:`n` is the number of wires the template acts upon. wires (Iterable): wires that the template acts on **Example** ArbitraryStatePreparation can be used to train state preparations, for example using a circuit with some measurement observable ``H``: .. code-block:: python dev = qml.device("default.qubit", wires=4) @qml.qnode(dev) def vqe(weights): qml.ArbitraryStatePreparation(weights, wires=[0, 1, 2, 3]) return qml.expval(qml.Hermitian(H, wires=[0, 1, 2, 3])) The shape of the weights parameter can be computed as follows: .. code-block:: python shape = qml.ArbitraryStatePreparation.shape(n_wires=4) """ num_wires = AnyWires grad_method = None def __init__(self, weights, wires, id=None): shape = qml.math.shape(weights) if shape != (2 ** (len(wires) + 1) - 2,): raise ValueError( f"Weights tensor must be of shape {(2 ** (len(wires) + 1) - 2,)}; got {shape}." ) super().__init__(weights, wires=wires, id=id) @property def num_params(self): return 1 @staticmethod def compute_decomposition(weights, wires): # pylint: disable=arguments-differ r"""Representation of the operator as a product of other operators. .. math:: O = O_1 O_2 \dots O_n. .. seealso:: :meth:`~.ArbitraryStatePreparation.decomposition`. Args: weights (tensor_like): Angles of the Pauli word rotations. Needs to have length :math:`2^{n+1} - 2` where :math:`n` is the number of wires the template acts upon. wires (Any or Iterable[Any]): wires that the operator acts on Returns: list[.Operator]: decomposition of the operator **Example** >>> weights = torch.tensor([1., 2., 3., 4., 5., 6.]) >>> qml.ArbitraryStatePreparation.compute_decomposition(weights, wires=["a", "b"]) [PauliRot(tensor(1.), 'XI', wires=['a', 'b']), PauliRot(tensor(2.), 'YI', wires=['a', 'b']), PauliRot(tensor(3.), 'IX', wires=['a', 'b']), PauliRot(tensor(4.), 'IY', wires=['a', 'b']), PauliRot(tensor(5.), 'XX', wires=['a', 'b']), PauliRot(tensor(6.), 'XY', wires=['a', 'b'])] """ op_list = [] for i, pauli_word in enumerate(_state_preparation_pauli_words(len(wires))): op_list.append(qml.PauliRot(weights[i], pauli_word, wires=wires)) return op_list @staticmethod def shape(n_wires): r"""Returns the required shape for the weight tensor. Args: n_wires (int): number of wires Returns: tuple[int]: shape """ return (2 ** (n_wires + 1) - 2,)
pennylane/pennylane/templates/state_preparations/arbitrary_state_preparation.py/0
{ "file_path": "pennylane/pennylane/templates/state_preparations/arbitrary_state_preparation.py", "repo_id": "pennylane", "token_count": 1935 }
69
# Copyright 2018-2021 Xanadu Quantum Technologies Inc. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. r""" Contains the FermionicDoubleExcitation template. """ # pylint: disable-msg=too-many-branches,too-many-arguments,protected-access import copy import numpy as np import pennylane as qml from pennylane.operation import AnyWires, Operation from pennylane.ops import CNOT, RX, RZ, Hadamard from pennylane.wires import Wires def _layer1(weight, s, r, q, p, set_cnot_wires): r"""Implement the first layer of the circuit to exponentiate the double-excitation operator entering the UCCSD ansatz. .. math:: \hat{U}_{pqrs}^{(1)}(\theta) = \mathrm{exp} \Big\{ \frac{i\theta}{8} \bigotimes_{b=s+1}^{r-1} \hat{Z}_b \bigotimes_{a=q+1}^{p-1} \hat{Z}_a (\hat{X}_s \hat{X}_r \hat{Y}_q \hat{X}_p) \Big\} Args: weight (float): angle :math:`\theta` entering the Z rotation acting on wire ``p`` s (int): qubit index ``s`` r (int): qubit index ``r`` q (int): qubit index ``q`` p (int): qubit index ``p`` set_cnot_wires (list[Wires]): list of CNOT wires Returns: list[.Operator]: sequence of operators defined by this function """ # U_1, U_2, U_3, U_4 acting on wires 's', 'r', 'q' and 'p' op_list = [Hadamard(wires=s), Hadamard(wires=r), RX(-np.pi / 2, wires=q), Hadamard(wires=p)] # Applying CNOTs for cnot_wires in set_cnot_wires: op_list.append(CNOT(wires=cnot_wires)) # Z rotation acting on wire 'p' op_list.append(RZ(weight / 8, wires=p)) # Applying CNOTs in reverse order for cnot_wires in reversed(set_cnot_wires): op_list.append(CNOT(wires=cnot_wires)) # U_1^+, U_2^+, U_3^+, U_4^+ acting on wires 's', 'r', 'q' and 'p' op_list.append(Hadamard(wires=s)) op_list.append(Hadamard(wires=r)) op_list.append(RX(np.pi / 2, wires=q)) op_list.append(Hadamard(wires=p)) return op_list def _layer2(weight, s, r, q, p, set_cnot_wires): r"""Implement the second layer of the circuit to exponentiate the double-excitation operator entering the UCCSD ansatz. .. math:: \hat{U}_{pqrs}^{(2)}(\theta) = \mathrm{exp} \Big\{ \frac{i\theta}{8} \bigotimes_{b=s+1}^{r-1} \hat{Z}_b \bigotimes_{a=q+1}^{p-1} \hat{Z}_a (\hat{Y}_s \hat{X}_r \hat{Y}_q \hat{Y}_p) \Big\} Args: weight (float): angle :math:`\theta` entering the Z rotation acting on wire ``p`` s (int): qubit index ``s`` r (int): qubit index ``r`` q (int): qubit index ``q`` p (int): qubit index ``p`` set_cnot_wires (list[Wires]): list of CNOT wires Returns: list[.Operator]: sequence of operators defined by this function """ # U_1, U_2, U_3, U_4 acting on wires 's', 'r', 'q' and 'p' op_list = [ RX(-np.pi / 2, wires=s), Hadamard(wires=r), RX(-np.pi / 2, wires=q), RX(-np.pi / 2, wires=p), ] # Applying CNOTs for cnot_wires in set_cnot_wires: op_list.append(CNOT(wires=cnot_wires)) # Z rotation acting on wire 'p' op_list.append(RZ(weight / 8, wires=p)) # Applying CNOTs in reverse order for cnot_wires in reversed(set_cnot_wires): op_list.append(CNOT(wires=cnot_wires)) # U_1^+, U_2^+, U_3^+, U_4^+ acting on wires 's', 'r', 'q' and 'p' op_list.append(RX(np.pi / 2, wires=s)) op_list.append(Hadamard(wires=r)) op_list.append(RX(np.pi / 2, wires=q)) op_list.append(RX(np.pi / 2, wires=p)) return op_list def _layer3(weight, s, r, q, p, set_cnot_wires): r"""Implement the third layer of the circuit to exponentiate the double-excitation operator entering the UCCSD ansatz. .. math:: \hat{U}_{pqrs}^{(3)}(\theta) = \mathrm{exp} \Big\{ \frac{i\theta}{8} \bigotimes_{b=s+1}^{r-1} \hat{Z}_b \bigotimes_{a=q+1}^{p-1} \hat{Z}_a (\hat{X}_s \hat{Y}_r \hat{Y}_q \hat{Y}_p) \Big\} Args: weight (float): angle :math:`\theta` entering the Z rotation acting on wire ``p`` s (int): qubit index ``s`` r (int): qubit index ``r`` q (int): qubit index ``q`` p (int): qubit index ``p`` set_cnot_wires (list[Wires]): list of CNOT wires Returns: list[.Operator]: sequence of operators defined by this function """ # U_1, U_2, U_3, U_4 acting on wires 's', 'r', 'q' and 'p' op_list = [ Hadamard(wires=s), RX(-np.pi / 2, wires=r), RX(-np.pi / 2, wires=q), RX(-np.pi / 2, wires=p), ] # Applying CNOTs for cnot_wires in set_cnot_wires: op_list.append(CNOT(wires=cnot_wires)) # Z rotation acting on wire 'p' op_list.append(RZ(weight / 8, wires=p)) # Applying CNOTs in reverse order for cnot_wires in reversed(set_cnot_wires): op_list.append(CNOT(wires=cnot_wires)) # U_1^+, U_2^+, U_3^+, U_4^+ acting on wires 's', 'r', 'q' and 'p' op_list.append(Hadamard(wires=s)) op_list.append(RX(np.pi / 2, wires=r)) op_list.append(RX(np.pi / 2, wires=q)) op_list.append(RX(np.pi / 2, wires=p)) return op_list def _layer4(weight, s, r, q, p, set_cnot_wires): r"""Implement the fourth layer of the circuit to exponentiate the double-excitation operator entering the UCCSD ansatz. .. math:: \hat{U}_{pqrs}^{(4)}(\theta) = \mathrm{exp} \Big\{ \frac{i\theta}{8} \bigotimes_{b=s+1}^{r-1} \hat{Z}_b \bigotimes_{a=q+1}^{p-1} \hat{Z}_a (\hat{X}_s \hat{X}_r \hat{X}_q \hat{Y}_p) \Big\} Args: weight (float): angle :math:`\theta` entering the Z rotation acting on wire ``p`` s (int): qubit index ``s`` r (int): qubit index ``r`` q (int): qubit index ``q`` p (int): qubit index ``p`` set_cnot_wires (list[Wires]): list of CNOT wires Returns: list[.Operator]: sequence of operators defined by this function """ # U_1, U_2, U_3, U_4 acting on wires 's', 'r', 'q' and 'p' op_list = [Hadamard(wires=s), Hadamard(wires=r), Hadamard(wires=q), RX(-np.pi / 2, wires=p)] # Applying CNOTs for cnot_wires in set_cnot_wires: op_list.append(CNOT(wires=cnot_wires)) # Z rotation acting on wire 'p' op_list.append(RZ(weight / 8, wires=p)) # Applying CNOTs in reverse order for cnot_wires in reversed(set_cnot_wires): op_list.append(CNOT(wires=cnot_wires)) # U_1^+, U_2^+, U_3^+, U_4^+ acting on wires 's', 'r', 'q' and 'p' op_list.append(Hadamard(wires=s)) op_list.append(Hadamard(wires=r)) op_list.append(Hadamard(wires=q)) op_list.append(RX(np.pi / 2, wires=p)) return op_list def _layer5(weight, s, r, q, p, set_cnot_wires): r"""Implement the fifth layer of the circuit to exponentiate the double-excitation operator entering the UCCSD ansatz. .. math:: \hat{U}_{pqrs}^{(5)}(\theta) = \mathrm{exp} \Big\{ -\frac{i\theta}{8} \bigotimes_{b=s+1}^{r-1} \hat{Z}_b \bigotimes_{a=q+1}^{p-1} \hat{Z}_a (\hat{Y}_s \hat{X}_r \hat{X}_q \hat{X}_p) \Big\} Args: weight (float): angle :math:`\theta` entering the Z rotation acting on wire ``p`` s (int): qubit index ``s`` r (int): qubit index ``r`` q (int): qubit index ``q`` p (int): qubit index ``p`` set_cnot_wires (list[Wires]): list of CNOT wires Returns: list[.Operator]: sequence of operators defined by this function """ # U_1, U_2, U_3, U_4 acting on wires 's', 'r', 'q' and 'p' op_list = [RX(-np.pi / 2, wires=s), Hadamard(wires=r), Hadamard(wires=q), Hadamard(wires=p)] # Applying CNOTs for cnot_wires in set_cnot_wires: op_list.append(CNOT(wires=cnot_wires)) # Z rotation acting on wire 'p' op_list.append(RZ(-weight / 8, wires=p)) # Applying CNOTs in reverse order for cnot_wires in reversed(set_cnot_wires): op_list.append(CNOT(wires=cnot_wires)) # U_1^+, U_2^+, U_3^+, U_4^+ acting on wires 's', 'r', 'q' and 'p' op_list.append(RX(np.pi / 2, wires=s)) op_list.append(Hadamard(wires=r)) op_list.append(Hadamard(wires=q)) op_list.append(Hadamard(wires=p)) return op_list def _layer6(weight, s, r, q, p, set_cnot_wires): r"""Implement the sixth layer of the circuit to exponentiate the double-excitation operator entering the UCCSD ansatz. .. math:: \hat{U}_{pqrs}^{(6)}(\theta) = \mathrm{exp} \Big\{ -\frac{i\theta}{8} \bigotimes_{b=s+1}^{r-1} \hat{Z}_b \bigotimes_{a=q+1}^{p-1} \hat{Z}_a (\hat{X}_s \hat{Y}_r \hat{X}_q \hat{X}_p) \Big\} Args: weight (float): angle :math:`\theta` entering the Z rotation acting on wire ``p`` s (int): qubit index ``s`` r (int): qubit index ``r`` q (int): qubit index ``q`` p (int): qubit index ``p`` set_cnot_wires (list[Wires]): list of CNOT wires Returns: list[.Operator]: sequence of operators defined by this function """ # U_1, U_2, U_3, U_4 acting on wires 's', 'r', 'q' and 'p' op_list = [Hadamard(wires=s), RX(-np.pi / 2, wires=r), Hadamard(wires=q), Hadamard(wires=p)] # Applying CNOTs for cnot_wires in set_cnot_wires: op_list.append(CNOT(wires=cnot_wires)) # Z rotation acting on wire 'p' op_list.append(RZ(-weight / 8, wires=p)) # Applying CNOTs in reverse order for cnot_wires in reversed(set_cnot_wires): op_list.append(CNOT(wires=cnot_wires)) # U_1^+, U_2^+, U_3^+, U_4^+ acting on wires 's', 'r', 'q' and 'p' op_list.append(Hadamard(wires=s)) op_list.append(RX(np.pi / 2, wires=r)) op_list.append(Hadamard(wires=q)) op_list.append(Hadamard(wires=p)) return op_list def _layer7(weight, s, r, q, p, set_cnot_wires): r"""Implement the seventh layer of the circuit to exponentiate the double-excitation operator entering the UCCSD ansatz. .. math:: \hat{U}_{pqrs}^{(7)}(\theta) = \mathrm{exp} \Big\{ -\frac{i\theta}{8} \bigotimes_{b=s+1}^{r-1} \hat{Z}_b \bigotimes_{a=q+1}^{p-1} \hat{Z}_a (\hat{Y}_s \hat{Y}_r \hat{Y}_q \hat{X}_p) \Big\} Args: weight (float): angle :math:`\theta` entering the Z rotation acting on wire ``p`` s (int): qubit index ``s`` r (int): qubit index ``r`` q (int): qubit index ``q`` p (int): qubit index ``p`` set_cnot_wires (list[Wires]): list of CNOT wires Returns: list[.Operator]: sequence of operators defined by this function """ # U_1, U_2, U_3, U_4 acting on wires 's', 'r', 'q' and 'p' op_list = [ RX(-np.pi / 2, wires=s), RX(-np.pi / 2, wires=r), RX(-np.pi / 2, wires=q), Hadamard(wires=p), ] # Applying CNOTs for cnot_wires in set_cnot_wires: op_list.append(CNOT(wires=cnot_wires)) # Z rotation acting on wire 'p' op_list.append(RZ(-weight / 8, wires=p)) # Applying CNOTs in reverse order for cnot_wires in reversed(set_cnot_wires): op_list.append(CNOT(wires=cnot_wires)) # U_1^+, U_2^+, U_3^+, U_4^+ acting on wires 's', 'r', 'q' and 'p' op_list.append(RX(np.pi / 2, wires=s)) op_list.append(RX(np.pi / 2, wires=r)) op_list.append(RX(np.pi / 2, wires=q)) op_list.append(Hadamard(wires=p)) return op_list def _layer8(weight, s, r, q, p, set_cnot_wires): r"""Implement the eighth layer of the circuit to exponentiate the double-excitation operator entering the UCCSD ansatz. .. math:: \hat{U}_{pqrs}^{(8)}(\theta) = \mathrm{exp} \Big\{ -\frac{i\theta}{8} \bigotimes_{b=s+1}^{r-1} \hat{Z}_b \bigotimes_{a=q+1}^{p-1} \hat{Z}_a (\hat{Y}_s \hat{Y}_r \hat{X}_q \hat{Y}_p) \Big\} Args: weight (float): angle :math:`\theta` entering the Z rotation acting on wire ``p`` s (int): qubit index ``s`` r (int): qubit index ``r`` q (int): qubit index ``q`` p (int): qubit index ``p`` set_cnot_wires (list[Wires]): list of CNOT wires Returns: list[.Operator]: sequence of operators defined by this function """ # U_1, U_2, U_3, U_4 acting on wires 's', 'r', 'q' and 'p' op_list = [ RX(-np.pi / 2, wires=s), RX(-np.pi / 2, wires=r), Hadamard(wires=q), RX(-np.pi / 2, wires=p), ] # Applying CNOTs for cnot_wires in set_cnot_wires: op_list.append(CNOT(wires=cnot_wires)) # Z rotation acting on wire 'p' op_list.append(RZ(-weight / 8, wires=p)) # Applying CNOTs in reverse order for cnot_wires in reversed(set_cnot_wires): op_list.append(CNOT(wires=cnot_wires)) # U_1^+, U_2^+, U_3^+, U_4^+ acting on wires 's', 'r', 'q' and 'p' op_list.append(RX(np.pi / 2, wires=s)) op_list.append(RX(np.pi / 2, wires=r)) op_list.append(Hadamard(wires=q)) op_list.append(RX(np.pi / 2, wires=p)) return op_list class FermionicDoubleExcitation(Operation): r"""Circuit to exponentiate the tensor product of Pauli matrices representing the double-excitation operator entering the Unitary Coupled-Cluster Singles and Doubles (UCCSD) ansatz. UCCSD is a VQE ansatz commonly used to run quantum chemistry simulations. The CC double-excitation operator is given by .. math:: \hat{U}_{pqrs}(\theta) = \mathrm{exp} \{ \theta (\hat{c}_p^\dagger \hat{c}_q^\dagger \hat{c}_r \hat{c}_s - \mathrm{H.c.}) \}, where :math:`\hat{c}` and :math:`\hat{c}^\dagger` are the fermionic annihilation and creation operators and the indices :math:`r, s` and :math:`p, q` run over the occupied and unoccupied molecular orbitals, respectively. Using the `Jordan-Wigner transformation <https://arxiv.org/abs/1208.5986>`_ the fermionic operator defined above can be written in terms of Pauli matrices (for more details see `arXiv:1805.04340 <https://arxiv.org/abs/1805.04340>`_): .. math:: \hat{U}_{pqrs}(\theta) = \mathrm{exp} \Big\{ \frac{i\theta}{8} \bigotimes_{b=s+1}^{r-1} \hat{Z}_b \bigotimes_{a=q+1}^{p-1} \hat{Z}_a (\hat{X}_s \hat{X}_r \hat{Y}_q \hat{X}_p + \hat{Y}_s \hat{X}_r \hat{Y}_q \hat{Y}_p + \hat{X}_s \hat{Y}_r \hat{Y}_q \hat{Y}_p + \hat{X}_s \hat{X}_r \hat{X}_q \hat{Y}_p - \mathrm{H.c.} ) \Big\} The quantum circuit to exponentiate the tensor product of Pauli matrices entering the latter equation is shown below (see `arXiv:1805.04340 <https://arxiv.org/abs/1805.04340>`_): | .. figure:: ../../_static/templates/subroutines/double_excitation_unitary.png :align: center :width: 60% :target: javascript:void(0); | As explained in `Seely et al. (2012) <https://arxiv.org/abs/1208.5986>`_, the exponential of a tensor product of Pauli-Z operators can be decomposed in terms of :math:`2(n-1)` CNOT gates and a single-qubit Z-rotation referred to as :math:`U_\theta` in the figure above. If there are :math:`X` or:math:`Y` Pauli matrices in the product, the Hadamard (:math:`H`) or :math:`R_x` gate has to be applied to change to the :math:`X` or :math:`Y` basis, respectively. The latter operations are denoted as :math:`U_1`, :math:`U_2`, :math:`U_3` and :math:`U_4` in the figure above. See the Usage Details section for more details. Args: weight (float or tensor_like): angle :math:`\theta` entering the Z rotation acting on wire ``p`` wires1 (Iterable): Wires of the qubits representing the subset of occupied orbitals in the interval ``[s, r]``. The first wire is interpreted as ``s`` and the last wire as ``r``. Wires in between are acted on with CNOT gates to compute the parity of the set of qubits. wires2 (Iterable): Wires of the qubits representing the subset of unoccupied orbitals in the interval ``[q, p]``. The first wire is interpreted as ``q`` and the last wire is interpreted as ``p``. Wires in between are acted on with CNOT gates to compute the parity of the set of qubits. .. details:: :title: Usage Details Notice that: #. :math:`\hat{U}_{pqrs}(\theta)` involves eight exponentiations where :math:`\hat{U}_1`, :math:`\hat{U}_2`, :math:`\hat{U}_3`, :math:`\hat{U}_4` and :math:`\hat{U}_\theta` are defined as follows, .. math:: [U_1, && U_2, U_3, U_4, U_{\theta}] = \\ && \Bigg\{\bigg[H, H, R_x(-\frac{\pi}{2}), H, R_z(\theta/8)\bigg], \bigg[R_x(-\frac{\pi}{2}), H, R_x(-\frac{\pi}{2}), R_x(-\frac{\pi}{2}), R_z(\frac{\theta}{8}) \bigg], \\ && \bigg[H, R_x(-\frac{\pi}{2}), R_x(-\frac{\pi}{2}), R_x(-\frac{\pi}{2}), R_z(\frac{\theta}{8}) \bigg], \bigg[H, H, H, R_x(-\frac{\pi}{2}), R_z(\frac{\theta}{8}) \bigg], \\ && \bigg[R_x(-\frac{\pi}{2}), H, H, H, R_z(-\frac{\theta}{8}) \bigg], \bigg[H, R_x(-\frac{\pi}{2}), H, H, R_z(-\frac{\theta}{8}) \bigg], \\ && \bigg[R_x(-\frac{\pi}{2}), R_x(-\frac{\pi}{2}), R_x(-\frac{\pi}{2}), H, R_z(-\frac{\theta}{8}) \bigg], \bigg[R_x(-\frac{\pi}{2}), R_x(-\frac{\pi}{2}), H, R_x(-\frac{\pi}{2}), R_z(-\frac{\theta}{8}) \bigg] \Bigg\} #. For a given quadruple ``[s, r, q, p]`` with :math:`p>q>r>s`, seventy-two single-qubit and ``16*(len(wires1)-1 + len(wires2)-1 + 1)`` CNOT operations are applied. Consecutive CNOT gates act on qubits with indices between ``s`` and ``r`` and ``q`` and ``p`` while a single CNOT acts on wires ``r`` and ``q``. The operations performed across these qubits are shown in dashed lines in the figure above. An example of how to use this template is shown below: .. code-block:: python import pennylane as qml dev = qml.device('default.qubit', wires=5) @qml.qnode(dev) def circuit(weight, wires1=None, wires2=None): qml.FermionicDoubleExcitation(weight, wires1=wires1, wires2=wires2) return qml.expval(qml.Z(0)) weight = 1.34817 print(circuit(weight, wires1=[0, 1], wires2=[2, 3, 4])) """ num_wires = AnyWires grad_method = "A" parameter_frequencies = [(0.5, 1.0)] def _flatten(self): return self.data, (self.hyperparameters["wires1"], self.hyperparameters["wires2"]) @classmethod def _primitive_bind_call(cls, *args, **kwargs): return cls._primitive.bind(*args, **kwargs) @classmethod def _unflatten(cls, data, metadata) -> "FermionicDoubleExcitation": return cls(data[0], wires1=metadata[0], wires2=metadata[1]) def __init__(self, weight, wires1=None, wires2=None, id=None): if len(wires1) < 2: raise ValueError( f"expected at least two wires representing the occupied orbitals; " f"got {len(wires1)}" ) if len(wires2) < 2: raise ValueError( f"expected at least two wires representing the unoccupied orbitals; " f"got {len(wires2)}" ) shape = qml.math.shape(weight) if shape != (): raise ValueError(f"Weight must be a scalar; got shape {shape}.") wires1 = qml.wires.Wires(wires1) wires2 = qml.wires.Wires(wires2) self._hyperparameters = { "wires1": wires1, "wires2": wires2, } wires = wires1 + wires2 super().__init__(weight, wires=wires, id=id) def map_wires(self, wire_map: dict): new_op = copy.deepcopy(self) new_op._wires = Wires([wire_map.get(wire, wire) for wire in self.wires]) for key in ["wires1", "wires2"]: new_op._hyperparameters[key] = Wires( [wire_map.get(wire, wire) for wire in self._hyperparameters[key]] ) return new_op @property def num_params(self): return 1 @staticmethod def compute_decomposition( weight, wires, wires1, wires2 ): # pylint: disable=arguments-differ,unused-argument r"""Representation of the operator as a product of other operators. .. math:: O = O_1 O_2 \dots O_n. .. seealso:: :meth:`~.FermionicDoubleExcitation.decomposition`. Args: weight (float or tensor_like): angle :math:`\theta` entering the Z rotation wires (Any or Iterable[Any]): full set of wires that the operator acts on wires1 (Iterable): Wires of the qubits representing the subset of occupied orbitals in the interval ``[s, r]``. wires2 (Iterable): Wires of the qubits representing the subset of unoccupied orbitals in the interval ``[q, p]``. Returns: list[.Operator]: decomposition of the operator """ s = wires1[0] r = wires1[-1] q = wires2[0] p = wires2[-1] # Sequence of the wires entering the CNOTs cnots_occ = [wires1[l : l + 2] for l in range(len(wires1) - 1)] cnots_unocc = [wires2[l : l + 2] for l in range(len(wires2) - 1)] set_cnot_wires = cnots_occ + [[r, q]] + cnots_unocc op_list = [] op_list.extend(_layer1(weight, s, r, q, p, set_cnot_wires)) op_list.extend(_layer2(weight, s, r, q, p, set_cnot_wires)) op_list.extend(_layer3(weight, s, r, q, p, set_cnot_wires)) op_list.extend(_layer4(weight, s, r, q, p, set_cnot_wires)) op_list.extend(_layer5(weight, s, r, q, p, set_cnot_wires)) op_list.extend(_layer6(weight, s, r, q, p, set_cnot_wires)) op_list.extend(_layer7(weight, s, r, q, p, set_cnot_wires)) op_list.extend(_layer8(weight, s, r, q, p, set_cnot_wires)) return op_list
pennylane/pennylane/templates/subroutines/fermionic_double_excitation.py/0
{ "file_path": "pennylane/pennylane/templates/subroutines/fermionic_double_excitation.py", "repo_id": "pennylane", "token_count": 10655 }
70
# Copyright 2018-2021 Xanadu Quantum Technologies Inc. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Contains the QuantumMonteCarlo template and utility functions. """ # pylint: disable=too-many-arguments import copy import numpy as np import pennylane as qml from pennylane.operation import AnyWires, Operation from pennylane.ops import QubitUnitary from pennylane.wires import Wires def probs_to_unitary(probs): r"""Calculates the unitary matrix corresponding to an input probability distribution. For a given distribution :math:`p(i)`, this function returns the unitary :math:`\mathcal{A}` that transforms the :math:`|0\rangle` state as .. math:: \mathcal{A} |0\rangle = \sum_{i} \sqrt{p(i)} |i\rangle, so that measuring the resulting state in the computational basis will give the state :math:`|i\rangle` with probability :math:`p(i)`. Note that the returned unitary matrix is real and hence an orthogonal matrix. Args: probs (array): input probability distribution as a flat array Returns: array: unitary Raises: ValueError: if the input array is not flat or does not correspond to a probability distribution **Example:** >>> p = np.ones(4) / 4 >>> probs_to_unitary(p) array([[ 0.5 , 0.5 , 0.5 , 0.5 ], [ 0.5 , -0.83333333, 0.16666667, 0.16666667], [ 0.5 , 0.16666667, -0.83333333, 0.16666667], [ 0.5 , 0.16666667, 0.16666667, -0.83333333]]) """ if not qml.math.is_abstract( sum(probs) ): # skip check and error if jitting to avoid JAX tracer errors if not qml.math.allclose(sum(probs), 1) or min(probs) < 0: raise ValueError( "A valid probability distribution of non-negative numbers that sum to one " "must be input" ) # Using the approach discussed here: # https://quantumcomputing.stackexchange.com/questions/10239/how-can-i-fill-a-unitary-knowing-only-its-first-column psi = qml.math.sqrt(probs) overlap = psi[0] denominator = qml.math.sqrt(2 + 2 * overlap) psi = qml.math.set_index(psi, 0, psi[0] + 1) # psi[0] += 1, but JAX-JIT compatible psi /= denominator dim = len(probs) return 2 * qml.math.outer(psi, psi) - np.eye(dim) def func_to_unitary(func, M): r"""Calculates the unitary that encodes a function onto an ancilla qubit register. Consider a function defined on the set of integers :math:`X = \{0, 1, \ldots, M - 1\}` whose output is bounded in the interval :math:`[0, 1]`, i.e., :math:`f: X \rightarrow [0, 1]`. The ``func_to_unitary`` function returns a unitary :math:`\mathcal{R}` that performs the transformation: .. math:: \mathcal{R} |i\rangle \otimes |0\rangle = |i\rangle\otimes \left(\sqrt{1 - f(i)}|0\rangle + \sqrt{f(i)} |1\rangle\right). In other words, for a given input state :math:`|i\rangle \otimes |0\rangle`, this unitary encodes the amplitude :math:`\sqrt{f(i)}` onto the :math:`|1\rangle` state of the ancilla qubit. Hence, measuring the ancilla qubit will result in the :math:`|1\rangle` state with probability :math:`f(i)`. Args: func (callable): a function defined on the set of integers :math:`X = \{0, 1, \ldots, M - 1\}` with output value inside :math:`[0, 1]` M (int): the number of integers that the function is defined on Returns: array: the :math:`\mathcal{R}` unitary Raises: ValueError: if func is not bounded with :math:`[0, 1]` for all :math:`X` **Example:** >>> func = lambda i: np.sin(i) ** 2 >>> M = 16 >>> func_to_unitary(func, M) array([[ 1. , 0. , 0. , ..., 0. , 0. , 0. ], [ 0. , -1. , 0. , ..., 0. , 0. , 0. ], [ 0. , 0. , 0.54030231, ..., 0. , 0. , 0. ], ..., [ 0. , 0. , 0. , ..., -0.13673722, 0. , 0. ], [ 0. , 0. , 0. , ..., 0. , 0.75968791, 0.65028784], [ 0. , 0. , 0. , ..., 0. , 0.65028784, -0.75968791]]) """ unitary = np.zeros((2 * M, 2 * M)) fs = [func(i) for i in range(M)] if not qml.math.is_abstract( fs[0] ): # skip check and error if jitting to avoid JAX tracer errors if min(fs) < 0 or max(fs) > 1: raise ValueError( "func must be bounded within the interval [0, 1] for the range of input values" ) for i, f in enumerate(fs): # array = set_index(array, idx, val) is a JAX-JIT compatible version of array[idx] = val unitary = qml.math.set_index(unitary, (2 * i, 2 * i), qml.math.sqrt(1 - f)) unitary = qml.math.set_index(unitary, (2 * i + 1, 2 * i), qml.math.sqrt(f)) unitary = qml.math.set_index(unitary, (2 * i, 2 * i + 1), qml.math.sqrt(f)) unitary = qml.math.set_index(unitary, (2 * i + 1, 2 * i + 1), -qml.math.sqrt(1 - f)) return unitary def _make_V(dim): r"""Calculates the :math:`\mathcal{V}` unitary which performs a reflection along the :math:`|1\rangle` state of the end ancilla qubit. Args: dim (int): dimension of :math:`\mathcal{V}` Returns: array: the :math:`\mathcal{V}` unitary """ assert dim % 2 == 0, "dimension for _make_V() must be even" one = np.array([[0, 0], [0, 1]]) dim_without_qubit = int(dim / 2) return 2 * np.kron(np.eye(dim_without_qubit), one) - np.eye(dim) def _make_Z(dim): r"""Calculates the :math:`\mathcal{Z}` unitary which performs a reflection along the all :math:`|0\rangle` state. Args: dim (int): dimension of :math:`\mathcal{Z}` Returns: array: the :math:`\mathcal{Z}` unitary """ Z = -np.eye(dim) Z[0, 0] = 1 return Z def make_Q(A, R): r"""Calculates the :math:`\mathcal{Q}` matrix that encodes the expectation value according to the probability unitary :math:`\mathcal{A}` and the function-encoding unitary :math:`\mathcal{R}`. Following `this <https://journals.aps.org/pra/abstract/10.1103/PhysRevA.98.022321>`__ paper, the expectation value is encoded as the phase of an eigenvalue of :math:`\mathcal{Q}`. This phase can be estimated using quantum phase estimation using the :func:`~.QuantumPhaseEstimation` template. See :func:`~.QuantumMonteCarlo` for more details, which loads ``make_Q()`` internally and applies phase estimation. Args: A (array): The unitary matrix of :math:`\mathcal{A}` which encodes the probability distribution R (array): The unitary matrix of :math:`\mathcal{R}` which encodes the function Returns: array: the :math:`\mathcal{Q}` unitary """ A_big = qml.math.kron(A, np.eye(2)) F = R @ A_big F_dagger = F.conj().T dim = len(R) V = _make_V(dim) Z = _make_Z(dim) UV = F @ Z @ F_dagger @ V return UV @ UV class QuantumMonteCarlo(Operation): r"""Performs the `quantum Monte Carlo estimation <https://arxiv.org/abs/1805.00109>`__ algorithm. Given a probability distribution :math:`p(i)` of dimension :math:`M = 2^{m}` for some :math:`m \geq 1` and a function :math:`f: X \rightarrow [0, 1]` defined on the set of integers :math:`X = \{0, 1, \ldots, M - 1\}`, this function implements the algorithm that allows the following expectation value to be estimated: .. math:: \mu = \sum_{i \in X} p(i) f(i). .. figure:: ../../_static/templates/subroutines/qmc.svg :align: center :width: 60% :target: javascript:void(0); Args: probs (array): input probability distribution as a flat array func (callable): input function :math:`f` defined on the set of integers :math:`X = \{0, 1, \ldots, M - 1\}` such that :math:`f(i)\in [0, 1]` for :math:`i \in X` target_wires (Union[Wires, Sequence[int], or int]): the target wires estimation_wires (Union[Wires, Sequence[int], or int]): the estimation wires Raises: ValueError: if ``probs`` is not flat or has a length that is not compatible with ``target_wires`` .. note:: This template is only compatible with simulators because the algorithm is performed using unitary matrices. Additionally, this operation is not differentiable. To implement the quantum Monte Carlo algorithm on hardware requires breaking down the unitary matrices into hardware-compatible gates, check out the :func:`~.quantum_monte_carlo` transformation for more details. .. details:: :title: Usage Details The algorithm proceeds as follows: #. The probability distribution :math:`p(i)` is encoded using a unitary :math:`\mathcal{A}` applied to the first :math:`m` qubits specified by ``target_wires``. #. The function :math:`f(i)` is encoded onto the last qubit of ``target_wires`` using a unitary :math:`\mathcal{R}`. #. The unitary :math:`\mathcal{Q}` is defined with eigenvalues :math:`e^{\pm 2 \pi i \theta}` such that the phase :math:`\theta` encodes the expectation value through the equation :math:`\mu = (1 + \cos (\pi \theta)) / 2`. The circuit in steps 1 and 2 prepares an equal superposition over the two states corresponding to the eigenvalues :math:`e^{\pm 2 \pi i \theta}`. #. The :func:`~.QuantumPhaseEstimation` circuit is applied so that :math:`\pm\theta` can be estimated by finding the probabilities of the :math:`n` estimation wires. This in turn allows for the estimation of :math:`\mu`. Visit `Rebentrost et al. (2018) <https://arxiv.org/abs/1805.00109>`__ for further details. In this algorithm, the number of applications :math:`N` of the :math:`\mathcal{Q}` unitary scales as :math:`2^{n}`. However, due to the use of quantum phase estimation, the error :math:`\epsilon` scales as :math:`\mathcal{O}(2^{-n})`. Hence, .. math:: N = \mathcal{O}\left(\frac{1}{\epsilon}\right). This scaling can be compared to standard Monte Carlo estimation, where :math:`N` samples are generated from the probability distribution and the average over :math:`f` is taken. In that case, .. math:: N = \mathcal{O}\left(\frac{1}{\epsilon^{2}}\right). Hence, the quantum Monte Carlo algorithm has a quadratically improved time complexity with :math:`N`. An example use case is given below. Consider a standard normal distribution :math:`p(x)` and a function :math:`f(x) = \sin ^{2} (x)`. The expectation value of :math:`f(x)` is :math:`\int_{-\infty}^{\infty}f(x)p(x)dx \approx 0.432332`. This number can be approximated by discretizing the problem and using the quantum Monte Carlo algorithm. First, the problem is discretized: .. code-block:: python from scipy.stats import norm m = 5 M = 2 ** m xmax = np.pi # bound to region [-pi, pi] xs = np.linspace(-xmax, xmax, M) probs = np.array([norm().pdf(x) for x in xs]) probs /= np.sum(probs) func = lambda i: np.sin(xs[i]) ** 2 The ``QuantumMonteCarlo`` template can then be used: .. code-block:: n = 10 N = 2 ** n target_wires = range(m + 1) estimation_wires = range(m + 1, n + m + 1) dev = qml.device("default.qubit", wires=(n + m + 1)) @qml.qnode(dev) def circuit(): qml.templates.QuantumMonteCarlo( probs, func, target_wires=target_wires, estimation_wires=estimation_wires, ) return qml.probs(estimation_wires) phase_estimated = np.argmax(circuit()[:int(N / 2)]) / N The estimated value can be retrieved using the formula :math:`\mu = (1-\cos(\pi \theta))/2` >>> (1 - np.cos(np.pi * phase_estimated)) / 2 0.4327096457464369 """ num_wires = AnyWires grad_method = None @classmethod def _primitive_bind_call(cls, *args, **kwargs): return cls._primitive.bind(*args, **kwargs) @classmethod def _unflatten(cls, data, metadata): new_op = cls.__new__(cls) new_op._hyperparameters = dict(metadata[1]) # pylint: disable=protected-access # call operation.__init__ to initialize private properties like _name, _id, _pauli_rep, etc. Operation.__init__(new_op, *data, wires=metadata[0]) return new_op def __init__(self, probs, func, target_wires, estimation_wires, id=None): if isinstance(probs, np.ndarray) and probs.ndim != 1: raise ValueError("The probability distribution must be specified as a flat array") dim_p = len(probs) num_target_wires_ = np.log2(2 * dim_p) num_target_wires = int(num_target_wires_) if not np.allclose(num_target_wires_, num_target_wires): raise ValueError( "The probability distribution must have a length that is a power of two" ) target_wires = tuple(target_wires) estimation_wires = tuple(estimation_wires) wires = target_wires + estimation_wires if num_target_wires != len(target_wires): raise ValueError( f"The probability distribution of dimension {dim_p} requires" f" {num_target_wires} target wires" ) self._hyperparameters = {"estimation_wires": estimation_wires, "target_wires": target_wires} A = probs_to_unitary(probs) R = func_to_unitary(func, dim_p) Q = make_Q(A, R) super().__init__(A, R, Q, wires=wires, id=id) def map_wires(self, wire_map: dict): # pylint: disable=protected-access new_op = copy.deepcopy(self) new_op._wires = Wires([wire_map.get(wire, wire) for wire in self.wires]) for key in ["estimation_wires", "target_wires"]: new_op._hyperparameters[key] = tuple( wire_map.get(w, w) for w in self._hyperparameters[key] ) return new_op @property def num_params(self): return 3 @staticmethod def compute_decomposition( A, R, Q, wires, estimation_wires, target_wires ): # pylint: disable=arguments-differ,unused-argument r"""Representation of the operator as a product of other operators. .. math:: O = O_1 O_2 \dots O_n. .. seealso:: :meth:`~.QuantumMonteCarlo.decomposition`. Args: A (array): unitary matrix corresponding to an input probability distribution R (array): unitary that encodes the function applied to the ancilla qubit register Q (array): matrix that encodes the expectation value according to the probability unitary and the function-encoding unitary wires (Any or Iterable[Any]): full set of wires that the operator acts on target_wires (Iterable[Any]): the target wires estimation_wires (Iterable[Any]): the estimation wires Returns: list[.Operator]: decomposition of the operator """ op_list = [ QubitUnitary(A, wires=target_wires[:-1]), QubitUnitary(R, wires=target_wires), qml.templates.QuantumPhaseEstimation( Q, target_wires=target_wires, estimation_wires=estimation_wires ), ] return op_list
pennylane/pennylane/templates/subroutines/qmc.py/0
{ "file_path": "pennylane/pennylane/templates/subroutines/qmc.py", "repo_id": "pennylane", "token_count": 7284 }
71
# Copyright 2018-2024 Xanadu Quantum Technologies Inc. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ This subpackage contains PennyLane transforms and their building blocks. .. currentmodule:: pennylane Custom transforms ----------------- :func:`qml.transform <pennylane.transform>` can be used to define custom transformations that work with PennyLane QNodes; such transformations can map a circuit to one or many new circuits alongside associated classical post-processing. .. autosummary:: :toctree: api ~transforms.core.transform Transforms library ------------------ A range of ready-to-use transforms are available in PennyLane. Transforms for circuit compilation ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ A set of transforms to perform basic circuit compilation tasks. .. autosummary:: :toctree: api ~compile ~transforms.cancel_inverses ~transforms.commute_controlled ~transforms.merge_rotations ~transforms.single_qubit_fusion ~transforms.unitary_to_rot ~transforms.merge_amplitude_embedding ~transforms.remove_barrier ~transforms.undo_swaps ~transforms.pattern_matching_optimization ~transforms.transpile There are also utility functions and decompositions available that assist with both transforms, and decompositions within the larger PennyLane codebase. .. autosummary:: :toctree: api ~transforms.set_decomposition ~transforms.pattern_matching ~transforms.to_zx ~transforms.from_zx There are also utility functions that take a circuit and return a DAG. .. autosummary:: :toctree: api ~transforms.commutation_dag ~transforms.CommutationDAG ~transforms.CommutationDAGNode Transform for Clifford+T decomposition ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ This transform accepts quantum circuits and decomposes them to the Clifford+T basis. .. autosummary:: :toctree: api ~clifford_t_decomposition Transforms for error mitigation ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ .. autosummary:: :toctree: api ~transforms.mitigate_with_zne ~transforms.fold_global ~transforms.poly_extrapolate ~transforms.richardson_extrapolate ~transforms.exponential_extrapolate Other transforms ~~~~~~~~~~~~~~~~ These transforms use the :func:`pennylane.transform` function/decorator and can be used on :class:`pennylane.tape.QuantumTape`, :class:`pennylane.QNode`. They fulfill multiple purposes like circuit preprocessing, getting information from a circuit, and more. .. autosummary:: :toctree: api ~batch_params ~batch_input ~transforms.insert ~transforms.add_noise ~defer_measurements ~transforms.diagonalize_measurements ~transforms.split_non_commuting ~transforms.split_to_single_terms ~transforms.broadcast_expand ~transforms.hamiltonian_expand ~transforms.sign_expand ~transforms.sum_expand ~transforms.convert_to_numpy_parameters ~apply_controlled_Q ~quantum_monte_carlo Transforms that act only on QNodes ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ These transforms only accept QNodes, and return new transformed functions that compute the desired quantity. .. autosummary:: :toctree: api ~batch_partial ~draw ~draw_mpl Decorators and utility functions -------------------------------- The following decorators and convenience functions are provided to help build custom QNode, quantum function, and tape transforms: .. autosummary:: :toctree: api ~transforms.make_tape ~transforms.create_expand_fn ~transforms.create_decomp_expand_fn ~transforms.expand_invalid_trainable ~transforms.expand_invalid_trainable_hadamard_gradient ~transforms.expand_multipar ~transforms.expand_trainable_multipar ~transforms.expand_nonunitary_gen Transforms developer functions ------------------------------ :class:`~.TransformContainer`, :class:`~.TransformDispatcher`, and :class:`~.TransformProgram` are developer-facing objects that allow the creation, dispatching, and composability of transforms. If you would like to make a custom transform, refer instead to the documentation of :func:`qml.transform <pennylane.transform>`. .. autosummary:: :toctree: api ~transforms.core.transform_dispatcher ~transforms.core.transform_program Transforming circuits --------------------- A quantum transform is a crucial concept in PennyLane, and refers to mapping a quantum circuit to one or more circuits, alongside a classical post-processing function. Once a transform is registered with PennyLane, the transformed circuits will be executed, and the classical post-processing function automatically applied to the outputs. This becomes particularly valuable when a transform generates multiple circuits, requiring a method to aggregate or reduce the results (e.g., applying the parameter-shift rule or computing the expectation value of a Hamiltonian term-by-term). .. note:: For examples of built-in transforms that come with PennyLane, see the :doc:`/introduction/compiling_circuits` documentation. Creating your own transform --------------------------- To streamline the creation of transforms and ensure their versatility across various circuit abstractions in PennyLane, the :func:`pennylane.transform` is available. This decorator registers transforms that accept a :class:`~.QuantumTape` as its primary input and returns a sequence of :class:`~.QuantumTape` and an associated processing function. To illustrate the process of creating a quantum transform, let's consider an example. Suppose we want a transform that removes all :class:`~.RX` operations from a given circuit. In this case, we merely need to filter the original :class:`~.QuantumTape` and return a new one without the filtered operations. As we don't require a specific processing function in this scenario, we include a function that simply returns the first and only result. .. code-block:: python from pennylane.tape import QuantumScript, QuantumScriptBatch from pennylane.typing import PostprocessingFn def remove_rx(tape: QuantumScript) -> tuple[QuantumScriptBatch, PostprocessingFn]: operations = filter(lambda op: op.name != "RX", tape.operations) new_tape = type(tape)(operations, tape.measurements, shots=tape.shots) def null_postprocessing(results): return results[0] return [new_tape], null_postprocessing To make your transform applicable to both :class:`~.QNode` and quantum functions, you can use the :func:`pennylane.transform` decorator. .. code-block:: python dispatched_transform = qml.transform(remove_rx) For a more advanced example, let's consider a transform that sums a circuit with its adjoint. We define the adjoint of the tape operations, create a new tape with these new operations, and return both tapes. The processing function then sums the results of the original and the adjoint tape. In this example, we use ``qml.transform`` in the form of a decorator in order to turn the custom function into a quantum transform. .. code-block:: python from pennylane.tape import QuantumScript, QuantumScriptBatch from pennylane.typing import PostprocessingFn @qml.transform def sum_circuit_and_adjoint(tape: QuantumScript) -> tuple[QuantumScriptBatch, PostprocessingFn]: operations = [qml.adjoint(op) for op in tape.operation] new_tape = type(tape)(operations, tape.measurements, shots=tape.shots) def sum_postprocessing(results): return qml.sum(results) return [tape, new_tape], sum_postprocessing Composability of transforms --------------------------- Transforms are inherently composable on a :class:`~.QNode`, meaning that transforms with compatible post-processing functions can be successively applied to QNodes. For example, this allows for the application of multiple compilation passes on a QNode to maximize gate reduction before execution. .. code-block:: python dev = qml.device("default.qubit", wires=1) @qml.transforms.merge_rotations @qml.transforms.cancel_inverses @qml.qnode(device=dev) def circuit(x, y): qml.Hadamard(wires=0) qml.Hadamard(wires=0) qml.RX(x, wires=0) qml.RY(y, wires=0) qml.RZ(y, wires=0) qml.RY(x, wires=0) return qml.expval(qml.Z(0)) In this example, inverses are canceled, leading to the removal of two Hadamard gates. Subsequently, rotations are merged into a single :class:`qml.Rot` gate. Consequently, two transforms are successfully applied to the circuit. Passing arguments to transforms ------------------------------- We can decorate a QNode with ``@partial(transform_fn, **transform_kwargs)`` to provide additional keyword arguments to a transform function. In the following example, we pass the keyword argument ``grouping_strategy="wires"`` to the :func:`~.split_non_commuting` quantum transform, which splits a circuit into tapes measuring groups of commuting observables. .. code-block:: python from functools import partial dev = qml.device("default.qubit", wires=2) @partial(qml.transforms.split_non_commuting, grouping_strategy="wires") @qml.qnode(dev) def circuit(params): qml.RX(params[0], wires=0) qml.RZ(params[1], wires=1) return [ qml.expval(qml.X(0)), qml.expval(qml.Y(1)), qml.expval(qml.Z(0) @ qml.Z(1)), qml.expval(qml.X(0) @ qml.Z(1) + 0.5 * qml.Y(1) + qml.Z(0)), ] Additional information ---------------------- Explore practical examples of transforms focused on compiling circuits in the :doc:`compiling circuits documentation </introduction/compiling_circuits>`. For gradient transforms, refer to the examples in the :doc:`gradients documentation <../code/qml_gradients>`. Discover quantum information transformations in the :doc:`quantum information documentation <../code/qml_qinfo>`. Finally, for a comprehensive overview of transforms and core functionalities, consult the :doc:`summary above <../code/qml_transforms>`. """ # Leave as alias for backwards-compatibility from pennylane.tape import make_qscript as make_tape # Import the decorators first to prevent circular imports when used in other transforms from .core import transform, TransformError from .batch_params import batch_params from .batch_input import batch_input from .batch_partial import batch_partial from .convert_to_numpy_parameters import convert_to_numpy_parameters from .compile import compile from .add_noise import add_noise from .decompositions import clifford_t_decomposition from .defer_measurements import defer_measurements from .diagonalize_measurements import diagonalize_measurements from .dynamic_one_shot import dynamic_one_shot, is_mcm from .sign_expand import sign_expand from .hamiltonian_expand import hamiltonian_expand, sum_expand from .split_non_commuting import split_non_commuting from .split_to_single_terms import split_to_single_terms from .insert_ops import insert from .mitigate import ( mitigate_with_zne, fold_global, poly_extrapolate, richardson_extrapolate, exponential_extrapolate, ) from .optimization import ( cancel_inverses, commute_controlled, merge_rotations, single_qubit_fusion, merge_amplitude_embedding, remove_barrier, undo_swaps, pattern_matching, pattern_matching_optimization, ) from .qmc import apply_controlled_Q, quantum_monte_carlo from .unitary_to_rot import unitary_to_rot from .commutation_dag import ( commutation_dag, CommutationDAG, CommutationDAGNode, ) from .tape_expand import ( expand_invalid_trainable, expand_invalid_trainable_hadamard_gradient, expand_multipar, expand_nonunitary_gen, expand_trainable_multipar, create_expand_fn, create_decomp_expand_fn, create_expand_trainable_multipar, set_decomposition, ) from .transpile import transpile from .zx import to_zx, from_zx from .broadcast_expand import broadcast_expand
pennylane/pennylane/transforms/__init__.py/0
{ "file_path": "pennylane/pennylane/transforms/__init__.py", "repo_id": "pennylane", "token_count": 4064 }
72
# Copyright 2018-2024 Xanadu Quantum Technologies Inc. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Transform to diagonalize measurements on a tape, assuming all measurements are commuting.""" from copy import copy from functools import singledispatch import pennylane as qml from pennylane.operation import Tensor from pennylane.ops import CompositeOp, LinearCombination, SymbolicOp from pennylane.transforms.core import transform # pylint: disable=protected-access _default_supported_obs = (qml.Z, qml.Identity) def null_postprocessing(results): """A postprocessing function returned by a transform that only converts the batch of results into a result for a single ``QuantumTape``. """ return results[0] @transform def diagonalize_measurements(tape, supported_base_obs=_default_supported_obs): """Diagonalize a set of measurements into the standard basis. Raises an error if the measurements do not commute. See the usage details for more information on which measurements are supported. Args: tape (QNode or QuantumScript or Callable): The quantum circuit to modify the measurements of. supported_base_obs (Optional, Iterable(Observable)): A list of supported base observable classes. Allowed observables are ``qml.X``, ``qml.Y``, ``qml.Z``, ``qml.Hadamard`` and ``qml.Identity``. Z and Identity are always treated as supported, regardless of input. If no list is provided, the transform will diagonalize everything into the Z basis. If a list is provided, only unsupported observables will be diagonalized to the Z basis. Returns: qnode (QNode) or tuple[List[QuantumScript], function]: The transformed circuit as described in :func:`qml.transform <pennylane.transform>`. .. note:: This transform will raise an error if it encounters non-commuting terms. To avoid non-commuting terms in circuit measurements, the :func:`split_non_commuting <pennylane.transforms.split_non_commuting>` transform can be applied. **Examples:** This transform allows us to transform QNode measurements into the measurement basis by adding the relevant diagonalizing gates to the end of the tape operations. .. code-block:: python3 from pennylane.transforms import diagonalize_measurements dev = qml.device("default.qubit") @diagonalize_measurements @qml.qnode(dev) def circuit(x): qml.RY(x[0], wires=0) qml.RX(x[1], wires=1) return qml.expval(qml.X(0) @ qml.Z(1)), qml.var(0.5 * qml.Y(2) + qml.X(0)) Applying the transform appends the relevant gates to the end of the circuit to allow measurements to be in the Z basis, so the original circuit >>> print(qml.draw(circuit, level=0)([np.pi/4, np.pi/4])) 0: ──RY(0.79)─┤ ╭<X@Z> ╭Var[(0.50*Y)+X] 1: ──RX(0.79)─┤ ╰<X@Z> │ 2: ───────────┤ ╰Var[(0.50*Y)+X] becomes >>> print(qml.draw(circuit)([np.pi/4, np.pi/4])) 0: ──RY(0.79)──H────┤ ╭<Z@Z> ╭Var[(0.50*Z)+Z] 1: ──RX(0.79)───────┤ ╰<Z@Z> │ 2: ──Z─────────S──H─┤ ╰Var[(0.50*Z)+Z] >>> circuit([np.pi/4, np.pi/4]) (tensor(0.5, requires_grad=True), tensor(0.75, requires_grad=True)) .. details:: :title: Usage Details The transform diagonalizes observables from the local Pauli basis only, i.e. it diagonalizes X, Y, Z, and Hadamard. The transform can also diagonalize only a subset of these operators. By default, the only supported base observable is Z. What if a backend device can handle X, Y and Z, but doesn't provide support for Hadamard? We can set this by passing ``supported_base_obs`` to the transform. Let's create a tape with some measurements: .. code-block:: python3 measurements = [ qml.expval(qml.X(0) + qml.Hadamard(1)), qml.expval(qml.X(0) + 0.2 * qml.Hadamard(1)), qml.var(qml.Y(2) + qml.X(0)), ] tape = qml.tape.QuantumScript(measurements=measurements) tapes, processing_fn = diagonalize_measurements( tape, supported_base_obs=[qml.X, qml.Y, qml.Z] ) Now ``tapes`` is a tuple containing a single tape with the updated measurements, where only the Hadamard gate has been diagonalized: >>> tapes[0].measurements [expval(X(0) + Z(1)), expval(X(0) + 0.2 * Z(1)), var(Y(2) + X(0))] """ bad_obs_input = [ o for o in supported_base_obs if o not in {qml.X, qml.Y, qml.Z, qml.Hadamard, qml.Identity} ] if bad_obs_input: raise ValueError( "Supported base observables must be a subset of [X, Y, Z, Hadamard, and Identity] " f"but received {list(bad_obs_input)}" ) supported_base_obs = set(list(supported_base_obs) + [qml.Z, qml.Identity]) _visited_obs = (set(), set()) # tracks which observables and wires have been diagonalized diagonalizing_gates = [] new_measurements = [] for m in tape.measurements: if m.obs: gates, new_obs, _visited_obs = _diagonalize_observable( m.obs, _visited_obs, supported_base_obs ) diagonalizing_gates.extend(gates) meas = copy(m) meas.obs = new_obs new_measurements.append(meas) else: new_measurements.append(m) new_operations = tape.operations + diagonalizing_gates new_tape = type(tape)( ops=new_operations, measurements=new_measurements, shots=tape.shots, trainable_params=tape.trainable_params, ) return (new_tape,), null_postprocessing def _check_if_diagonalizing(obs, _visited_obs, switch_basis): """Checks if the observable should be diagonalized based on whether its basis should be switched, and whether the same observable has already been diagonalized. Args: obs: the observable to be diagonalized _visited_obs: a tuple containing a list of all observables that have already been encountered, and a list of all wires that have already been encountered switch_basis: whether the observable should be switched for one measuring in the Z-basis on the same wires. Returns: diagonalize (bool): whether or not to apply diagonalizing gates for the observable _visited_obs (tuple(Iterables): an up-to-date record of the observables and wires encountered on the tape so far """ if obs in _visited_obs[0] or isinstance(obs, qml.Identity): # its already been encountered before, and if need be, diagonalized - we will # not be applying any gates or updating _visited_obs # same if it's just an Identity return False, _visited_obs # a different observable has been diagonalized on the same wire - error if obs.wires[0] in _visited_obs[1]: raise ValueError( f"Expected measurements on the same wire to commute, but {obs} " f"overlaps with another non-commuting observable on the tape." ) # we diagonalize if it's an operator we are switching the basis for # we update _visited_obs to indicate that we've encountered that observable regardless _visited_obs[0].add(obs) _visited_obs[1].add(obs.wires[0]) return switch_basis, _visited_obs def _diagonalize_observable( observable, _visited_obs=None, supported_base_obs=_default_supported_obs, ): """Takes an observable and changes all unsupported obs to the measurement basis. Applies diagonalizing gates if the observable being switched to the measurement basis hasn't already been diagonalized for a previous observable on the tape. Args: observable: the observable to be diagonalized _visited_obs: a tuple containing a list of all observables that have already been encountered, and a list of all wires that have already been encountered supported_base_obs (Optional, Iterable(Str)): A list of names of supported base observables. Allowed names are 'PauliX', 'PauliY', 'PauliZ' and 'Hadamard'. If no list is provided, the function will diagonalize everything. Returns: diagonalizing_gates: A list of operations to be applied to diagonalize the observable new_obs: the relevant measurement to perform after applying diagonalzing_gates to get the correct measurement output _visited_obs: an up-to-date record of the observables and wires encountered on the tape so far """ if _visited_obs is None: _visited_obs = (set(), set()) if not isinstance(observable, (qml.X, qml.Y, qml.Z, qml.Hadamard, qml.Identity)): return _diagonalize_compound_observable( observable, _visited_obs, supported_base_obs=supported_base_obs ) # also validates that the wire hasn't already been diagonalized and updated _visited_obs switch_basis = type(observable) not in supported_base_obs diagonalize, _visited_obs = _check_if_diagonalizing(observable, _visited_obs, switch_basis) if isinstance(observable, qml.Z): # maybe kind of redundant return [], observable, _visited_obs new_obs = qml.Z(wires=observable.wires) if switch_basis else observable diagonalizing_gates = observable.diagonalizing_gates() if diagonalize else [] return diagonalizing_gates, new_obs, _visited_obs def _get_obs_and_gates(obs_list, _visited_obs, supported_base_obs=_default_supported_obs): """Calls _diagonalize_observable on each observable in a list, and returns the full result for the list of observables""" new_obs = [] diagonalizing_gates = [] for o in obs_list: gates, obs, _visited_obs = _diagonalize_observable(o, _visited_obs, supported_base_obs) if gates: diagonalizing_gates.extend(gates) new_obs.append(obs) return diagonalizing_gates, new_obs, _visited_obs @singledispatch def _diagonalize_compound_observable( observable, _visited_obs, supported_base_obs=_default_supported_obs ): """Takes an observable consisting of multiple other observables, and changes all unsupported obs to the measurement basis. Applies diagonalizing gates if changing the basis of an observable whose diagonalizing gates have not already been applied.""" raise NotImplementedError( f"Unable to convert observable of type {type(observable)} to the measurement basis" ) @_diagonalize_compound_observable.register def _diagonalize_symbolic_op( observable: SymbolicOp, _visited_obs, supported_base_obs=_default_supported_obs ): diagonalizing_gates, new_base, _visited_obs = _diagonalize_observable( observable.base, _visited_obs, supported_base_obs ) params, hyperparams = observable.parameters, observable.hyperparameters hyperparams = copy(hyperparams) hyperparams["base"] = new_base new_observable = observable.__class__(*params, **hyperparams) return diagonalizing_gates, new_observable, _visited_obs @_diagonalize_compound_observable.register def _diagonalize_tensor( observable: Tensor, _visited_obs, supported_base_obs=_default_supported_obs ): diagonalizing_gates, new_obs, _visited_obs = _get_obs_and_gates( observable.obs, _visited_obs, supported_base_obs ) new_observable = Tensor(*new_obs) return diagonalizing_gates, new_observable, _visited_obs @_diagonalize_compound_observable.register def _diagonalize_hamiltonian( observable: qml.ops.Hamiltonian, _visited_obs, supported_base_obs=_default_supported_obs, ): diagonalizing_gates, new_ops, _visited_obs = _get_obs_and_gates( observable.ops, _visited_obs, supported_base_obs ) new_observable = qml.ops.Hamiltonian(observable.coeffs, new_ops) return diagonalizing_gates, new_observable, _visited_obs @_diagonalize_compound_observable.register def _diagonalize_composite_op( observable: LinearCombination, _visited_obs, supported_base_obs=_default_supported_obs ): coeffs, obs = observable.terms() diagonalizing_gates, new_obs, _visited_obs = _get_obs_and_gates( obs, _visited_obs, supported_base_obs ) new_observable = LinearCombination(coeffs, new_obs) return diagonalizing_gates, new_observable, _visited_obs @_diagonalize_compound_observable.register def _diagonalize_composite_op( observable: CompositeOp, _visited_obs, supported_base_obs=_default_supported_obs ): diagonalizing_gates, new_operands, _visited_obs = _get_obs_and_gates( observable.operands, _visited_obs, supported_base_obs ) new_observable = observable.__class__(*new_operands) return diagonalizing_gates, new_observable, _visited_obs
pennylane/pennylane/transforms/diagonalize_measurements.py/0
{ "file_path": "pennylane/pennylane/transforms/diagonalize_measurements.py", "repo_id": "pennylane", "token_count": 5088 }
73
# Copyright 2018-2020 Xanadu Quantum Technologies Inc. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Pytest configuration file for PennyLane test suite. """ # pylint: disable=unused-import import contextlib import os import pathlib import sys import warnings import numpy as np import pytest import pennylane as qml from pennylane.devices import DefaultGaussian from pennylane.operation import disable_new_opmath_cm, enable_new_opmath_cm sys.path.append(os.path.join(os.path.dirname(__file__), "helpers")) # defaults TOL = 1e-3 TF_TOL = 2e-2 TOL_STOCHASTIC = 0.05 # pylint: disable=too-few-public-methods class DummyDevice(DefaultGaussian): """Dummy device to allow Kerr operations""" _operation_map = DefaultGaussian._operation_map.copy() _operation_map["Kerr"] = lambda *x, **y: np.identity(2) @pytest.fixture(autouse=True) def set_numpy_seed(): np.random.seed(9872653) yield @pytest.fixture(scope="function", autouse=True) def capture_legacy_device_deprecation_warnings(): with warnings.catch_warnings(record=True) as recwarn: warnings.simplefilter("always") yield for w in recwarn: if isinstance(w, qml.PennyLaneDeprecationWarning): assert "Use of 'default.qubit." in str(w.message) assert "is deprecated" in str(w.message) assert "use 'default.qubit'" in str(w.message) for w in recwarn: if "Use of 'default.qubit." not in str(w.message): warnings.warn(message=w.message, category=w.category) @pytest.fixture(scope="session") def tol(): """Numerical tolerance for equality tests.""" return float(os.environ.get("TOL", TOL)) @pytest.fixture(scope="session") def tol_stochastic(): """Numerical tolerance for equality tests of stochastic values.""" return TOL_STOCHASTIC @pytest.fixture(scope="session") def tf_tol(): """Numerical tolerance for equality tests.""" return float(os.environ.get("TF_TOL", TF_TOL)) @pytest.fixture(scope="session", params=[1, 2]) def n_layers(request): """Number of layers.""" return request.param @pytest.fixture(scope="session", params=[2, 3], name="n_subsystems") def n_subsystems_fixture(request): """Number of qubits or qumodes.""" return request.param @pytest.fixture(scope="session") def qubit_device(n_subsystems): with pytest.warns(qml.PennyLaneDeprecationWarning, match="Use of 'default.qubit.legacy'"): return qml.device("default.qubit.legacy", wires=n_subsystems) @pytest.fixture(scope="function", params=[(np.float32, np.complex64), (np.float64, np.complex128)]) def qubit_device_1_wire(request): return qml.device( "default.qubit.legacy", wires=1, r_dtype=request.param[0], c_dtype=request.param[1] ) @pytest.fixture(scope="function", params=[(np.float32, np.complex64), (np.float64, np.complex128)]) def qubit_device_2_wires(request): return qml.device( "default.qubit.legacy", wires=2, r_dtype=request.param[0], c_dtype=request.param[1] ) @pytest.fixture(scope="function", params=[(np.float32, np.complex64), (np.float64, np.complex128)]) def qubit_device_3_wires(request): return qml.device( "default.qubit.legacy", wires=3, r_dtype=request.param[0], c_dtype=request.param[1] ) # The following 3 fixtures are for default.qutrit devices to be used # for testing with various real and complex dtypes. @pytest.fixture(scope="function", params=[(np.float32, np.complex64), (np.float64, np.complex128)]) def qutrit_device_1_wire(request): return qml.device("default.qutrit", wires=1, r_dtype=request.param[0], c_dtype=request.param[1]) @pytest.fixture(scope="function", params=[(np.float32, np.complex64), (np.float64, np.complex128)]) def qutrit_device_2_wires(request): return qml.device("default.qutrit", wires=2, r_dtype=request.param[0], c_dtype=request.param[1]) @pytest.fixture(scope="function", params=[(np.float32, np.complex64), (np.float64, np.complex128)]) def qutrit_device_3_wires(request): return qml.device("default.qutrit", wires=3, r_dtype=request.param[0], c_dtype=request.param[1]) @pytest.fixture(scope="session") def gaussian_device(n_subsystems): """Number of qubits or modes.""" return DummyDevice(wires=n_subsystems) @pytest.fixture(scope="session") def gaussian_dummy(): """Gaussian device with dummy Kerr gate.""" return DummyDevice @pytest.fixture(scope="session") def gaussian_device_2_wires(): """A 2-mode Gaussian device.""" return DummyDevice(wires=2) @pytest.fixture(scope="session") def gaussian_device_4modes(): """A 4 mode Gaussian device.""" return DummyDevice(wires=4) ####################################################################### @pytest.fixture(scope="module", params=[1, 2, 3]) def seed(request): """Different seeds.""" return request.param @pytest.fixture(scope="function") def mock_device(monkeypatch): """A mock instance of the abstract Device class""" with monkeypatch.context() as m: dev = qml.Device m.setattr(dev, "__abstractmethods__", frozenset()) m.setattr(dev, "short_name", "mock_device") m.setattr(dev, "capabilities", lambda cls: {"model": "qubit"}) m.setattr(dev, "operations", {"RX", "RY", "RZ", "CNOT", "SWAP"}) yield qml.Device(wires=2) # pylint:disable=abstract-class-instantiated # pylint: disable=protected-access @pytest.fixture def tear_down_hermitian(): yield None qml.Hermitian._eigs = {} # pylint: disable=protected-access @pytest.fixture def tear_down_thermitian(): yield None qml.THermitian._eigs = {} ####################################################################### # Fixtures for testing under new and old opmath def pytest_addoption(parser): parser.addoption( "--disable-opmath", action="store", default="False", help="Whether to disable new_opmath" ) # pylint: disable=eval-used @pytest.fixture(scope="session", autouse=True) def disable_opmath_if_requested(request): disable_opmath = request.config.getoption("--disable-opmath") # value from yaml file is a string, convert to boolean if eval(disable_opmath): qml.operation.disable_new_opmath(warn=True) @pytest.fixture(scope="function") def use_legacy_opmath(): with disable_new_opmath_cm() as cm: yield cm # pylint: disable=contextmanager-generator-missing-cleanup @pytest.fixture(scope="function") def use_new_opmath(): with enable_new_opmath_cm() as cm: yield cm @pytest.fixture(params=[disable_new_opmath_cm, enable_new_opmath_cm], scope="function") def use_legacy_and_new_opmath(request): with request.param() as cm: yield cm @pytest.fixture def new_opmath_only(): if not qml.operation.active_new_opmath(): pytest.skip("This feature only works with new opmath enabled") @pytest.fixture def legacy_opmath_only(): if qml.operation.active_new_opmath(): pytest.skip("This test exclusively tests legacy opmath") ####################################################################### try: import tensorflow as tf except (ImportError, ModuleNotFoundError) as e: tf_available = False else: tf_available = True try: import torch from torch.autograd import Variable torch_available = True except ImportError as e: torch_available = False try: import jax import jax.numpy as jnp jax_available = True except ImportError as e: jax_available = False # pylint: disable=unused-argument def pytest_generate_tests(metafunc): if jax_available: jax.config.update("jax_enable_x64", True) def pytest_collection_modifyitems(items, config): rootdir = pathlib.Path(config.rootdir) for item in items: rel_path = pathlib.Path(item.fspath).relative_to(rootdir) if "qchem" in rel_path.parts: mark = getattr(pytest.mark, "qchem") item.add_marker(mark) if "finite_diff" in rel_path.parts: mark = getattr(pytest.mark, "finite-diff") item.add_marker(mark) if "parameter_shift" in rel_path.parts: mark = getattr(pytest.mark, "param-shift") item.add_marker(mark) if "data" in rel_path.parts: mark = getattr(pytest.mark, "data") item.add_marker(mark) # Tests that do not have a specific suite marker are marked `core` for item in items: markers = {mark.name for mark in item.iter_markers()} if ( not any( elem in [ "autograd", "data", "torch", "tf", "jax", "qchem", "qcut", "all_interfaces", "finite-diff", "param-shift", "external", ] for elem in markers ) or not markers ): item.add_marker(pytest.mark.core) def pytest_runtest_setup(item): """Automatically skip tests if interfaces are not installed""" # Autograd is assumed to be installed interfaces = {"tf", "torch", "jax"} available_interfaces = { "tf": tf_available, "torch": torch_available, "jax": jax_available, } allowed_interfaces = [ allowed_interface for allowed_interface in interfaces if available_interfaces[allowed_interface] is True ] # load the marker specifying what the interface is all_interfaces = {"tf", "torch", "jax", "all_interfaces"} marks = {mark.name for mark in item.iter_markers() if mark.name in all_interfaces} for b in marks: if b == "all_interfaces": required_interfaces = {"tf", "torch", "jax"} for interface in required_interfaces: if interface not in allowed_interfaces: pytest.skip( f"\nTest {item.nodeid} only runs with {allowed_interfaces} interfaces(s) but {b} interface provided", ) else: if b not in allowed_interfaces: pytest.skip( f"\nTest {item.nodeid} only runs with {allowed_interfaces} interfaces(s) but {b} interface provided", )
pennylane/tests/conftest.py/0
{ "file_path": "pennylane/tests/conftest.py", "repo_id": "pennylane", "token_count": 4417 }
74
# Copyright 2018-2023 Xanadu Quantum Technologies Inc. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Tests for the :class:`pennylane.data.base.mapper.AttributeTypeMapper` class. """ from unittest.mock import MagicMock import pytest import pennylane.data.base.mapper from pennylane.data import AttributeInfo, Dataset, DatasetScalar from pennylane.data.base.hdf5 import create_group from pennylane.data.base.mapper import AttributeTypeMapper pytestmark = pytest.mark.data class TestMapper: # pylint: disable=too-few-public-methods """Tests for :class:`pennylane.data.mapper.AttributeTypeMapper`.""" def test_info(self): """Test that info() returns the attribute info from bind.""" bind = create_group() info = AttributeInfo(bind.attrs) info.doc = "documentation" mapper = AttributeTypeMapper(bind) assert mapper.info == info def test_set_item_attribute_with_info(self): """Test that set_item() copies info from the info argument when passed a DatasetAttribute.""" dset = Dataset() mapper = AttributeTypeMapper(dset.bind) mapper.set_item( "x", DatasetScalar(1, info=AttributeInfo(doc="abc")), info=AttributeInfo(extra="xyz") ) assert dset.attr_info["x"].doc == "abc" assert dset.attr_info["x"]["extra"] == "xyz" def test_set_item_other_value_error(self, monkeypatch): """Test that set_item() only captures a ValueError if it is caused by a HDF5 file not being writeable.""" monkeypatch.setattr( pennylane.data.base.mapper, "match_obj_type", MagicMock(side_effect=ValueError("Something")), ) with pytest.raises(ValueError, match="Something"): AttributeTypeMapper(create_group()).set_item("x", 1, None) def test_repr(self): """Test that __repr__ is equivalent to dict.__repr__.""" mapper = AttributeTypeMapper(create_group()) mapper["x"] = 1 mapper["y"] = {"a": "b"} assert repr(mapper) == repr({"x": DatasetScalar(1), "y": {"a": "b"}}) def test_str(self): """Test that __str__ is equivalent to dict.__str__.""" mapper = AttributeTypeMapper(create_group()) mapper["x"] = 1 mapper["y"] = {"a": "b"} assert str(mapper) == str({"x": DatasetScalar(1), "y": {"a": "b"}})
pennylane/tests/data/base/test_mapper.py/0
{ "file_path": "pennylane/tests/data/base/test_mapper.py", "repo_id": "pennylane", "token_count": 1143 }
75
# Copyright 2018-2023 Xanadu Quantum Technologies Inc. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Unit tests for the :class:`~pennylane.devices.ExecutionConfig` class. """ import pytest from pennylane.devices.execution_config import ExecutionConfig, MCMConfig def test_default_values(): """Tests that the default values are as expected.""" config = ExecutionConfig() assert config.derivative_order == 1 assert config.device_options == {} assert config.interface is None assert config.gradient_method is None assert config.gradient_keyword_arguments == {} assert config.grad_on_execution is None assert config.use_device_gradient is None assert config.mcm_config == MCMConfig() def test_mcm_config_default_values(): """Test that the default values of MCMConfig are correct""" mcm_config = MCMConfig() assert mcm_config.postselect_mode is None assert mcm_config.mcm_method is None def test_invalid_interface(): """Tests that unknown frameworks raise a ValueError.""" with pytest.raises(ValueError, match="interface must be in"): _ = ExecutionConfig(interface="nonsense") @pytest.mark.parametrize("option", (True, False, None)) def test_valid_grad_on_execution(option): """Test execution config allows True, False and None""" config = ExecutionConfig(grad_on_execution=option) assert config.grad_on_execution == option def test_invalid_grad_on_execution(): """Test invalid values for grad on execution raise an error.""" with pytest.raises(ValueError, match=r"grad_on_execution must be True, False,"): ExecutionConfig(grad_on_execution="forward") @pytest.mark.parametrize( "option", [MCMConfig(mcm_method="deferred"), {"mcm_method": "deferred"}, None] ) def test_valid_execution_config_mcm_config(option): """Test that the mcm_config attribute is set correctly""" config = ExecutionConfig(mcm_config=option) if option else ExecutionConfig() if option is None: assert config.mcm_config == MCMConfig() else: assert config.mcm_config == MCMConfig(mcm_method="deferred") def test_invalid_execution_config_mcm_config(): """Test that an error is raised if mcm_config is set incorrectly""" option = "foo" with pytest.raises(ValueError, match="Got invalid type"): _ = ExecutionConfig(mcm_config=option) def test_mcm_config_invalid_mcm_method(): """Test that an error is raised if creating MCMConfig with invalid mcm_method""" option = "foo" with pytest.raises(ValueError, match="Invalid mid-circuit measurements method"): _ = MCMConfig(mcm_method=option) def test_mcm_config_invalid_postselect_mode(): """Test that an error is raised if creating MCMConfig with invalid postselect_mode""" option = "foo" with pytest.raises(ValueError, match="Invalid postselection mode"): _ = MCMConfig(postselect_mode=option)
pennylane/tests/devices/experimental/test_execution_config.py/0
{ "file_path": "pennylane/tests/devices/experimental/test_execution_config.py", "repo_id": "pennylane", "token_count": 1102 }
76
# Copyright 2018-2024 Xanadu Quantum Technologies Inc. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Unit tests for simulate in devices/qutrit_mixed.""" import numpy as np import pytest from dummy_debugger import Debugger from flaky import flaky import pennylane as qml from pennylane import math from pennylane.devices.qutrit_mixed import get_final_state, measure_final_state, simulate # pylint: disable=inconsistent-return-statements def expected_TRX_circ_expval_values(phi, subspace): """Find the expect-values of GellManns 2,3,5,8 on a circuit with a TRX gate on subspace (0,1) or (0,2)""" if subspace == (0, 1): return np.array([-np.sin(phi), np.cos(phi), 0, np.sqrt(1 / 3)]) if subspace == (0, 2): return np.array( [ 0, np.cos(phi / 2) ** 2, -np.sin(phi), np.sqrt(1 / 3) * (np.cos(phi) - np.sin(phi / 2) ** 2), ] ) pytest.skip(f"Test cases doesn't support subspace {subspace}") def expected_TRX_circ_expval_jacobians(phi, subspace): """Find the Jacobians of expect-values of GellManns 2,3,5,8 on a circuit with a TRX gate on subspace (0,1) or (0,2)""" if subspace == (0, 1): return np.array([-np.cos(phi), -np.sin(phi), 0, 0]) if subspace == (0, 2): return np.array([0, -np.sin(phi) / 2, -np.cos(phi), np.sqrt(1 / 3) * -(1.5 * np.sin(phi))]) pytest.skip(f"Test cases doesn't support subspace {subspace}") def expected_TRX_circ_state(phi, subspace): """Find the state after applying TRX gate on |0>""" expected_vector = np.array([0, 0, 0], dtype=complex) expected_vector[subspace[0]] = np.cos(phi / 2) expected_vector[subspace[1]] = -1j * np.sin(phi / 2) return np.outer(expected_vector, np.conj(expected_vector)) class TestCurrentlyUnsupportedCases: """Test currently unsupported cases, such as sampling counts or samples without shots, or probs with shots""" # pylint: disable=too-few-public-methods def test_sample_based_observable(self): """Test sample-only measurements raise a NotImplementedError.""" qs = qml.tape.QuantumScript(measurements=[qml.sample(wires=0)]) with pytest.raises(NotImplementedError): simulate(qs) @pytest.mark.parametrize("mp", [qml.probs(0), qml.probs(op=qml.GellMann(0, 2))]) def test_invalid_samples(self, mp): """Test Sampling MeasurementProcesses that are currently unsupported on this device""" qs = qml.tape.QuantumScript(ops=[qml.TAdd(wires=(0, 1))], measurements=[mp], shots=10) with pytest.raises(NotImplementedError): simulate(qs) def test_custom_operation(): """Test execution works with a manually defined operator if it has a matrix.""" # pylint: disable=too-few-public-methods class MyOperator(qml.operation.Operator): num_wires = 1 @staticmethod def compute_matrix(): return np.array([[0, 0, 1], [0, 1, 0], [1, 0, 0]]) qs = qml.tape.QuantumScript([MyOperator(0)], [qml.expval(qml.GellMann(0, 8))]) result = simulate(qs) assert qml.math.allclose(result, -np.sqrt(4 / 3)) @pytest.mark.all_interfaces @pytest.mark.parametrize("op", [qml.TRX(np.pi, 0), qml.QutritBasisState([1], 0)]) @pytest.mark.parametrize("interface", ("jax", "tensorflow", "torch", "autograd", "numpy")) def test_result_has_correct_interface(op, interface): """Test that even if no interface parameters are given, result is correct.""" qs = qml.tape.QuantumScript([op], [qml.expval(qml.GellMann(0, 3))]) res = simulate(qs, interface=interface) assert qml.math.get_interface(res) == interface assert qml.math.allclose(res, -1) # pylint: disable=too-few-public-methods class TestStatePrepBase: """Tests integration with various state prep methods.""" def test_basis_state(self): """Test that the BasisState operator prepares the desired state.""" qs = qml.tape.QuantumScript( ops=[qml.QutritBasisState((2, 1), wires=(0, 1))], measurements=[qml.probs(wires=(0, 1, 2))], ) probs = simulate(qs) expected = np.zeros(27) expected[21] = 1.0 assert qml.math.allclose(probs, expected) @pytest.mark.parametrize("subspace", [(0, 1), (0, 2)]) class TestBasicCircuit: """Tests a basic circuit with one TRX gate and a few simple expectation values.""" @staticmethod def get_TRX_quantum_script(phi, subspace): """Get the quantum script where TRX is applied then GellMann observables are measured""" ops = [qml.TRX(phi, wires=0, subspace=subspace)] obs = [qml.expval(qml.GellMann(0, index)) for index in [2, 3, 5, 8]] return qml.tape.QuantumScript(ops, obs) def test_basic_circuit_numpy(self, subspace): """Test execution with a basic circuit.""" phi = np.array(0.397) qs = self.get_TRX_quantum_script(phi, subspace) result = simulate(qs) expected_measurements = expected_TRX_circ_expval_values(phi, subspace) assert isinstance(result, tuple) assert len(result) == 4 assert np.allclose(result, expected_measurements) state, is_state_batched = get_final_state(qs) result = measure_final_state(qs, state, is_state_batched) expected_state = expected_TRX_circ_state(phi, subspace) assert np.allclose(state, expected_state) assert not is_state_batched assert isinstance(result, tuple) assert len(result) == 4 assert np.allclose(result, expected_measurements) @pytest.mark.autograd def test_autograd_results_and_backprop(self, subspace): """Tests execution and gradients with autograd""" phi = qml.numpy.array(-0.52) def f(x): qs = self.get_TRX_quantum_script(x, subspace) return qml.numpy.array(simulate(qs)) result = f(phi) expected = expected_TRX_circ_expval_values(phi, subspace) assert qml.math.allclose(result, expected) g = qml.jacobian(f)(phi) expected = expected_TRX_circ_expval_jacobians(phi, subspace) assert qml.math.allclose(g, expected) @pytest.mark.jax @pytest.mark.parametrize("use_jit", (True, False)) def test_jax_results_and_backprop(self, use_jit, subspace): """Tests execution and gradients with jax.""" import jax phi = jax.numpy.array(0.678) def f(x): qs = self.get_TRX_quantum_script(x, subspace) return simulate(qs) if use_jit: f = jax.jit(f) result = f(phi) expected = expected_TRX_circ_expval_values(phi, subspace) assert qml.math.allclose(result, expected) g = jax.jacobian(f)(phi) expected = expected_TRX_circ_expval_jacobians(phi, subspace) assert qml.math.allclose(g, expected) @pytest.mark.torch def test_torch_results_and_backprop(self, subspace): """Tests execution and gradients of a simple circuit with torch.""" import torch phi = torch.tensor(-0.526, requires_grad=True) def f(x): qs = self.get_TRX_quantum_script(x, subspace) return simulate(qs) result = f(phi) expected = expected_TRX_circ_expval_values(phi.detach().numpy(), subspace) result_detached = math.asarray(result, like="torch").detach().numpy() assert math.allclose(result_detached, expected) jacobian = math.asarray(torch.autograd.functional.jacobian(f, phi + 0j), like="torch") expected = expected_TRX_circ_expval_jacobians(phi.detach().numpy(), subspace) assert math.allclose(jacobian.detach().numpy(), expected) @pytest.mark.tf def test_tf_results_and_backprop(self, subspace): """Tests execution and gradients of a simple circuit with tensorflow.""" import tensorflow as tf phi = tf.Variable(4.873) with tf.GradientTape(persistent=True) as grad_tape: qs = self.get_TRX_quantum_script(phi, subspace) result = simulate(qs) expected = expected_TRX_circ_expval_values(phi, subspace) assert qml.math.allclose(result, expected) expected = expected_TRX_circ_expval_jacobians(phi, subspace) assert math.all( [ math.allclose(grad_tape.jacobian(one_obs_result, [phi])[0], one_obs_expected) for one_obs_result, one_obs_expected in zip(result, expected) ] ) @pytest.mark.parametrize("subspace", [(0, 1), (0, 2)]) class TestBroadcasting: """Test that simulate works with broadcasted parameters.""" @staticmethod def get_expected_state(x, subspace): """Gets the expected final state of the circuit described in `get_ops_and_measurements`.""" state = [] for x_val in x: vec = np.zeros(9, dtype=complex) vec[subspace[1]] = -1j * np.cos(x_val / 2) vec[3 + (2 * subspace[1])] = -1j * np.sin(x_val / 2) state.append(np.outer(vec, np.conj(vec)).reshape((3,) * 4)) return state @staticmethod def get_expectation_values(x, subspace): """Gets the expected final expvals of the circuit described in `get_ops_and_measurements`.""" if subspace == (0, 1): return [np.cos(x), -np.cos(x / 2) ** 2] if subspace == (0, 2): return [np.cos(x / 2) ** 2, -np.sin(x / 2) ** 2] raise ValueError(f"Test cases doesn't support subspace {subspace}") @staticmethod def get_quantum_script(x, subspace, shots=None, extra_wire=False): """Gets quantum script of a circuit that includes parameter broadcasted operations and measurements.""" ops = [ qml.TRX(np.pi, wires=1 + extra_wire, subspace=subspace), qml.TRY(x, wires=0 + extra_wire, subspace=subspace), qml.TAdd(wires=[0 + extra_wire, 1 + extra_wire]), ] measurements = [qml.expval(qml.GellMann(i, 3)) for i in range(2 + extra_wire)] return qml.tape.QuantumScript(ops, measurements, shots=shots) def test_broadcasted_op_state(self, subspace): """Test that simulate works for state measurements when an operation has broadcasted parameters""" x = np.array([0.8, 1.0, 1.2, 1.4]) qs = self.get_quantum_script(x, subspace) res = simulate(qs) expected = self.get_expectation_values(x, subspace) assert isinstance(res, tuple) assert len(res) == 2 assert np.allclose(res, expected) state, is_state_batched = get_final_state(qs) res = measure_final_state(qs, state, is_state_batched) assert np.allclose(state, self.get_expected_state(x, subspace)) assert is_state_batched assert isinstance(res, tuple) assert len(res) == 2 assert np.allclose(res, expected) def test_broadcasted_op_sample(self, subspace): """Test that simulate works for sample measurements when an operation has broadcasted parameters""" x = np.array([0.8, 1.0, 1.2, 1.4]) qs = self.get_quantum_script(x, subspace, shots=qml.measurements.Shots(10000)) res = simulate(qs, rng=123) expected = self.get_expectation_values(x, subspace) assert isinstance(res, tuple) assert len(res) == 2 assert np.allclose(res, expected, atol=0.05) state, is_state_batched = get_final_state(qs) res = measure_final_state(qs, state, is_state_batched, rng=123) assert np.allclose(state, self.get_expected_state(x, subspace)) assert is_state_batched assert isinstance(res, tuple) assert len(res) == 2 assert np.allclose(res, expected, atol=0.05) def test_broadcasting_with_extra_measurement_wires(self, mocker, subspace): """Test that broadcasting works when the operations don't act on all wires.""" # I can't mock anything in `simulate` because the module name is the function name spy = mocker.spy(qml, "map_wires") x = np.array([0.8, 1.0, 1.2, 1.4]) qs = self.get_quantum_script(x, subspace, extra_wire=True) res = simulate(qs) assert isinstance(res, tuple) assert len(res) == 3 assert np.allclose(res[0], 1.0) assert np.allclose(res[1:], self.get_expectation_values(x, subspace)) assert spy.call_args_list[0].args == (qs, {2: 0, 1: 1, 0: 2}) @pytest.mark.parametrize("extra_wires", [1, 3]) class TestStatePadding: """Tests if the state zeros padding works as expected for when operators don't act on all measured wires.""" @staticmethod def get_expected_dm(x, extra_wires): """Gets the final density matrix of the circuit described in `get_ops_and_measurements`.""" vec = np.zeros(9, dtype=complex) vec[1] = -1j * np.cos(x / 2) vec[6] = -1j * np.sin(x / 2) state = np.outer(vec, np.conj(vec)) zero_padding = np.zeros((3**extra_wires, 3**extra_wires)) zero_padding[0, 0] = 1 return np.kron(state, zero_padding) @staticmethod def get_quantum_script(x, extra_wires): """Gets a quantum script of a circuit where operators don't act on all measured wires.""" ops = [ qml.TRX(np.pi, wires=1, subspace=(0, 1)), qml.TRY(x, wires=0, subspace=(0, 2)), qml.TAdd(wires=[0, 1]), ] return qml.tape.QuantumScript(ops, [qml.density_matrix(wires=range(2 + extra_wires))]) def test_extra_measurement_wires(self, extra_wires): """Tests if correct state is returned when operators don't act on all measured wires.""" x = 1.32 final_dim = 3 ** (2 + extra_wires) qs = self.get_quantum_script(x, extra_wires) state = get_final_state(qs)[0] assert state.shape == (3,) * (2 + extra_wires) * 2 expected_state = self.get_expected_dm(x, extra_wires) assert math.allclose(state.reshape((final_dim, final_dim)), expected_state) def test_extra_measurement_wires_broadcasting(self, extra_wires): """Tests if correct state is returned when there is broadcasting and operators don't act on all measured wires.""" x = np.array([1.32, 0.56, 2.81, 2.1]) final_dim = 3 ** (2 + extra_wires) qs = self.get_quantum_script(x, extra_wires) state = get_final_state(qs)[0] assert state.shape == tuple([4] + [3] * (2 + extra_wires) * 2) expected_state = [self.get_expected_dm(x_val, extra_wires) for x_val in x] assert math.allclose(state.reshape((len(x), final_dim, final_dim)), expected_state) @pytest.mark.parametrize("subspace", [(0, 1), (0, 2)]) class TestDebugger: """Tests that the debugger works for a simple circuit""" basis_state = np.array([[1.0, 0, 0], [0, 0, 0], [0, 0, 0]]) @staticmethod def get_debugger_quantum_script(phi, subspace): """Get the quantum script with debugging where TRX is applied then GellMann observables are measured""" ops = [ qml.Snapshot(), qml.TRX(phi, wires=0, subspace=subspace), qml.Snapshot("final_state"), ] obs = [qml.expval(qml.GellMann(0, index)) for index in [2, 3, 5, 8]] return qml.tape.QuantumScript(ops, obs) def test_debugger_numpy(self, subspace): """Test debugger with numpy""" phi = np.array(0.397) qs = self.get_debugger_quantum_script(phi, subspace) debugger = Debugger() result = simulate(qs, debugger=debugger) assert isinstance(result, tuple) assert len(result) == 4 expected = expected_TRX_circ_expval_values(phi, subspace) assert np.allclose(result, expected) assert list(debugger.snapshots.keys()) == [0, "final_state"] assert np.allclose(debugger.snapshots[0], self.basis_state) expected_final_state = expected_TRX_circ_state(phi, subspace) assert np.allclose(debugger.snapshots["final_state"], expected_final_state) @pytest.mark.autograd def test_debugger_autograd(self, subspace): """Tests debugger with autograd""" phi = qml.numpy.array(-0.52) debugger = Debugger() def f(x): qs = self.get_debugger_quantum_script(x, subspace) return qml.numpy.array(simulate(qs, debugger=debugger)) result = f(phi) expected = expected_TRX_circ_expval_values(phi, subspace) assert qml.math.allclose(result, expected) assert list(debugger.snapshots.keys()) == [0, "final_state"] assert qml.math.allclose(debugger.snapshots[0], self.basis_state) expected_final_state = expected_TRX_circ_state(phi, subspace) assert qml.math.allclose(debugger.snapshots["final_state"], expected_final_state) @pytest.mark.jax def test_debugger_jax(self, subspace): """Tests debugger with JAX""" import jax phi = jax.numpy.array(0.678) debugger = Debugger() def f(x): qs = self.get_debugger_quantum_script(x, subspace) return simulate(qs, debugger=debugger) result = f(phi) expected = expected_TRX_circ_expval_values(phi, subspace) assert qml.math.allclose(result, expected) assert list(debugger.snapshots.keys()) == [0, "final_state"] assert qml.math.allclose(debugger.snapshots[0], self.basis_state) expected_final_state = expected_TRX_circ_state(phi, subspace) assert qml.math.allclose(debugger.snapshots["final_state"], expected_final_state) @pytest.mark.torch def test_debugger_torch(self, subspace): """Tests debugger with torch""" import torch phi = torch.tensor(-0.526, requires_grad=True) debugger = Debugger() def f(x): qs = self.get_debugger_quantum_script(x, subspace) return simulate(qs, debugger=debugger) results = f(phi) expected_values = expected_TRX_circ_expval_values(phi.detach().numpy(), subspace) for result, expected in zip(results, expected_values): assert qml.math.allclose(result, expected) assert list(debugger.snapshots.keys()) == [0, "final_state"] assert qml.math.allclose(debugger.snapshots[0], self.basis_state) expected_final_state = math.asarray( expected_TRX_circ_state(phi.detach().numpy(), subspace), like="torch" ) assert qml.math.allclose(debugger.snapshots["final_state"], expected_final_state) # pylint: disable=invalid-unary-operand-type @pytest.mark.tf def test_debugger_tf(self, subspace): """Tests debugger with tensorflow.""" import tensorflow as tf phi = tf.Variable(4.873) debugger = Debugger() qs = self.get_debugger_quantum_script(phi, subspace) result = simulate(qs, debugger=debugger) expected = expected_TRX_circ_expval_values(phi, subspace) assert qml.math.allclose(result, expected) assert list(debugger.snapshots.keys()) == [0, "final_state"] assert qml.math.allclose(debugger.snapshots[0], self.basis_state) expected_final_state = expected_TRX_circ_state(phi, subspace) assert qml.math.allclose(debugger.snapshots["final_state"], expected_final_state) @flaky @pytest.mark.parametrize("subspace", [(0, 1), (0, 2)]) class TestSampleMeasurements: """Tests circuits with sample-based measurements""" @staticmethod def expval_of_TRY_circ(x, subspace): """Find the expval of GellMann_3 on simple TRY circuit""" if subspace == (0, 1): return np.cos(x) if subspace == (0, 2): return np.cos(x / 2) ** 2 raise ValueError(f"Test cases doesn't support subspace {subspace}") @staticmethod def sample_sum_of_TRY_circ(x, subspace): """Find the expval of computational basis bitstring value for both wires on simple TRY circuit""" if subspace == (0, 1): return [np.sin(x / 2) ** 2, 0] if subspace == (0, 2): return [2 * np.sin(x / 2) ** 2, 0] raise ValueError(f"Test cases doesn't support subspace {subspace}") @staticmethod def expval_of_2_qutrit_circ(x, subspace): """Gets the expval of GellMann_3 on wire=0 on the 2-qutrit circuit used""" if subspace == (0, 1): return np.cos(x) if subspace == (0, 2): return np.cos(x / 2) ** 2 raise ValueError(f"Test cases doesn't support subspace {subspace}") @staticmethod def probs_of_2_qutrit_circ(x, y, subspace): """Possible measurement values and probabilities for the 2-qutrit circuit used""" probs = np.array( [ np.cos(x / 2) * np.cos(y / 2), np.cos(x / 2) * np.sin(y / 2), np.sin(x / 2) * np.sin(y / 2), np.sin(x / 2) * np.cos(y / 2), ] ) probs **= 2 if subspace[1] == 1: keys = ["00", "01", "10", "11"] else: keys = ["00", "02", "20", "22"] return keys, probs def test_single_expval(self, subspace): """Test a simple circuit with a single expval measurement""" x = np.array(0.732) qs = qml.tape.QuantumScript( [qml.TRY(x, wires=0, subspace=subspace)], [qml.expval(qml.GellMann(0, 3))], shots=10000, ) result = simulate(qs) assert isinstance(result, np.float64) assert result.shape == () assert np.allclose(result, self.expval_of_TRY_circ(x, subspace), atol=0.1) def test_single_sample(self, subspace): """Test a simple circuit with a single sample measurement""" x = np.array(0.732) qs = qml.tape.QuantumScript( [qml.TRY(x, wires=0, subspace=subspace)], [qml.sample(wires=range(2))], shots=10000 ) result = simulate(qs) assert isinstance(result, np.ndarray) assert result.shape == (10000, 2) assert np.allclose( np.sum(result, axis=0).astype(np.float32) / 10000, self.sample_sum_of_TRY_circ(x, subspace), atol=0.1, ) def test_multi_measurements(self, subspace): """Test a simple circuit containing multiple measurements""" num_shots = 100000 x, y = np.array(0.732), np.array(0.488) qs = qml.tape.QuantumScript( [ qml.TRX(x, wires=0, subspace=subspace), qml.TAdd(wires=[0, 1]), qml.TRY(y, wires=1, subspace=subspace), ], [ qml.expval(qml.GellMann(0, 3)), qml.counts(wires=range(2)), qml.sample(wires=range(2)), ], shots=num_shots, ) result = simulate(qs) assert isinstance(result, tuple) assert len(result) == 3 assert np.allclose(result[0], self.expval_of_2_qutrit_circ(x, subspace), atol=0.01) expected_keys, expected_probs = self.probs_of_2_qutrit_circ(x, y, subspace) assert list(result[1].keys()) == expected_keys assert np.allclose( np.array(list(result[1].values())) / num_shots, expected_probs, atol=0.01, ) assert result[2].shape == (100000, 2) shots_data = [ [10000, 10000], [(10000, 2)], [10000, 20000], [(10000, 2), 20000], [(10000, 3), 20000, (30000, 2)], ] @pytest.mark.parametrize("shots", shots_data) def test_expval_shot_vector(self, shots, subspace): """Test a simple circuit with a single expval measurement for shot vectors""" x = np.array(0.732) shots = qml.measurements.Shots(shots) qs = qml.tape.QuantumScript( [qml.TRY(x, wires=0, subspace=subspace)], [qml.expval(qml.GellMann(0, 3))], shots=shots ) result = simulate(qs) assert isinstance(result, tuple) assert len(result) == len(list(shots)) expected = self.expval_of_TRY_circ(x, subspace) assert all(isinstance(res, np.float64) for res in result) assert all(res.shape == () for res in result) assert all(np.allclose(res, expected, atol=0.1) for res in result) @pytest.mark.parametrize("shots", shots_data) def test_sample_shot_vector(self, shots, subspace): """Test a simple circuit with a single sample measurement for shot vectors""" x = np.array(0.732) shots = qml.measurements.Shots(shots) qs = qml.tape.QuantumScript( [qml.TRY(x, wires=0, subspace=subspace)], [qml.sample(wires=range(2))], shots=shots ) result = simulate(qs) assert isinstance(result, tuple) assert len(result) == len(list(shots)) expected = self.sample_sum_of_TRY_circ(x, subspace) assert all(isinstance(res, np.ndarray) for res in result) assert all(res.shape == (s, 2) for res, s in zip(result, shots)) assert all( np.allclose(np.sum(res, axis=0).astype(np.float32) / s, expected, atol=0.1) for res, s in zip(result, shots) ) @pytest.mark.parametrize("shots", shots_data) def test_multi_measurement_shot_vector(self, shots, subspace): """Test a simple circuit containing multiple measurements for shot vectors""" x, y = np.array(0.732), np.array(0.488) shots = qml.measurements.Shots(shots) qs = qml.tape.QuantumScript( [ qml.TRX(x, wires=0, subspace=subspace), qml.TAdd(wires=[0, 1]), qml.TRY(y, wires=1, subspace=subspace), ], [ qml.expval(qml.GellMann(0, 3)), qml.counts(wires=range(2)), qml.sample(wires=range(2)), ], shots=shots, ) result = simulate(qs) assert isinstance(result, tuple) assert len(result) == len(list(shots)) for shot_res, s in zip(result, shots): assert isinstance(shot_res, tuple) assert len(shot_res) == 3 assert isinstance(shot_res[0], np.float64) assert isinstance(shot_res[1], dict) assert isinstance(shot_res[2], np.ndarray) assert np.allclose(shot_res[0], self.expval_of_TRY_circ(x, subspace), atol=0.1) expected_keys, expected_probs = self.probs_of_2_qutrit_circ(x, y, subspace) assert list(shot_res[1].keys()) == expected_keys assert np.allclose( np.array(list(shot_res[1].values())) / s, expected_probs, atol=0.1, ) assert shot_res[2].shape == (s, 2) def test_custom_wire_labels(self, subspace): """Test that custom wire labels works as expected""" num_shots = 10000 x, y = np.array(0.732), np.array(0.488) qs = qml.tape.QuantumScript( [ qml.TRX(x, wires="b", subspace=subspace), qml.TAdd(wires=["b", "a"]), qml.TRY(y, wires="a", subspace=subspace), ], [ qml.expval(qml.GellMann("b", 3)), qml.counts(wires=["a", "b"]), qml.sample(wires=["b", "a"]), ], shots=num_shots, ) result = simulate(qs) assert isinstance(result, tuple) assert len(result) == 3 assert isinstance(result[0], np.float64) assert isinstance(result[1], dict) assert isinstance(result[2], np.ndarray) assert np.allclose(result[0], self.expval_of_TRY_circ(x, subspace), atol=0.1) expected_keys, expected_probs = self.probs_of_2_qutrit_circ(x, y, subspace) assert list(result[1].keys()) == expected_keys assert np.allclose( np.array(list(result[1].values())) / num_shots, expected_probs, atol=0.1, ) assert result[2].shape == (num_shots, 2)
pennylane/tests/devices/qutrit_mixed/test_qutrit_mixed_simulate.py/0
{ "file_path": "pennylane/tests/devices/qutrit_mixed/test_qutrit_mixed_simulate.py", "repo_id": "pennylane", "token_count": 13033 }
77
# Copyright 2018-2024 Xanadu Quantum Technologies Inc. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for default qutrit mixed.""" from functools import partial, reduce import numpy as np import pytest import pennylane as qml from pennylane import math from pennylane import numpy as qnp from pennylane.devices import DefaultQutritMixed, ExecutionConfig class TestDeviceProperties: """Tests for general device properties.""" def test_name(self): """Tests the name of DefaultQutritMixed.""" assert DefaultQutritMixed().name == "default.qutrit.mixed" def test_shots(self): """Test the shots property of DefaultQutritMixed.""" assert DefaultQutritMixed().shots == qml.measurements.Shots(None) assert DefaultQutritMixed(shots=100).shots == qml.measurements.Shots(100) with pytest.raises(AttributeError): DefaultQutritMixed().shots = 10 def test_wires(self): """Test that a device can be created with wires.""" assert DefaultQutritMixed().wires is None assert DefaultQutritMixed(wires=2).wires == qml.wires.Wires([0, 1]) assert DefaultQutritMixed(wires=[0, 2]).wires == qml.wires.Wires([0, 2]) with pytest.raises(AttributeError): DefaultQutritMixed().wires = [0, 1] def test_debugger_attribute(self): """Test that DefaultQutritMixed has a debugger attribute and that it is `None`""" # pylint: disable=protected-access dev = DefaultQutritMixed() assert hasattr(dev, "_debugger") assert dev._debugger is None def test_applied_modifiers(self): """Test that DefaultQutritMixed has the `single_tape_support` and `simulator_tracking` modifiers applied. """ dev = DefaultQutritMixed() assert dev._applied_modifiers == [ # pylint: disable=protected-access qml.devices.modifiers.single_tape_support, qml.devices.modifiers.simulator_tracking, ] class TestSupportsDerivatives: """Test that DefaultQutritMixed states what kind of derivatives it supports.""" def test_supports_backprop(self): """Test that DefaultQutritMixed says that it supports backpropagation.""" dev = DefaultQutritMixed() assert dev.supports_derivatives() is True assert dev.supports_jvp() is False assert dev.supports_vjp() is False config = ExecutionConfig(gradient_method="backprop", interface="auto") assert dev.supports_derivatives(config) is True assert dev.supports_jvp(config) is False assert dev.supports_vjp(config) is False qs = qml.tape.QuantumScript([], [qml.state()]) assert dev.supports_derivatives(config, qs) is True assert dev.supports_jvp(config, qs) is False assert dev.supports_vjp(config, qs) is False config = ExecutionConfig(gradient_method="best", interface=None) assert dev.supports_derivatives(config) is True assert dev.supports_jvp(config) is False assert dev.supports_vjp(config) is False def test_doesnt_support_derivatives_with_invalid_tape(self): """Tests that DefaultQutritMixed does not support differentiation with invalid circuits.""" dev = DefaultQutritMixed() config = ExecutionConfig(gradient_method="backprop") circuit = qml.tape.QuantumScript([], [qml.sample()], shots=10) assert dev.supports_derivatives(config, circuit=circuit) is False @pytest.mark.parametrize( "gradient_method", ["parameter-shift", "finite-diff", "device", "adjoint"] ) def test_doesnt_support_other_gradient_methods(self, gradient_method): """Tests that DefaultQutritMixed currently does not support other gradient methods natively.""" dev = DefaultQutritMixed() config = ExecutionConfig(gradient_method=gradient_method) assert dev.supports_derivatives(config) is False assert dev.supports_jvp(config) is False assert dev.supports_vjp(config) is False class TestBasicCircuit: """Tests a basic circuit with one TRX gate and expectation values of four GellMann observables.""" @staticmethod def expected_trx_circ_expval_values(phi, subspace): """Find the expect-values of GellManns 2,3,5,8 on a circuit with a TRX gate on subspace (0,1) or (0,2).""" if subspace == (0, 1): return np.array([-np.sin(phi), np.cos(phi), 0, np.sqrt(1 / 3)]) if subspace == (0, 2): return np.array( [ 0, np.cos(phi / 2) ** 2, -np.sin(phi), np.sqrt(1 / 3) * (np.cos(phi) - np.sin(phi / 2) ** 2), ] ) pytest.skip(f"Test cases doesn't support subspace {subspace}") return None @staticmethod def expected_trx_circ_expval_jacobians(phi, subspace): """Find the Jacobians of expect-values of GellManns 2,3,5,8 on a circuit with a TRX gate on subspace (0,1) or (0,2).""" if subspace == (0, 1): return np.array([-np.cos(phi), -np.sin(phi), 0, 0]) if subspace == (0, 2): return np.array( [0, -np.sin(phi) / 2, -np.cos(phi), np.sqrt(1 / 3) * -(1.5 * np.sin(phi))] ) pytest.skip(f"Test cases doesn't support subspace {subspace}") return None @staticmethod def get_trx_quantum_script(phi, subspace): """Get the quantum script where TRX is applied then GellMann observables are measured""" ops = [qml.TRX(phi, wires=0, subspace=subspace)] obs = [qml.expval(qml.GellMann(0, index)) for index in [2, 3, 5, 8]] return qml.tape.QuantumScript(ops, obs) @pytest.mark.parametrize("subspace", [(0, 1), (0, 2)]) def test_basic_circuit_numpy(self, subspace): """Test execution with a basic circuit.""" phi = np.array(0.397) qs = self.get_trx_quantum_script(phi, subspace) dev = DefaultQutritMixed() result = dev.execute(qs) expected_measurements = self.expected_trx_circ_expval_values(phi, subspace) assert isinstance(result, tuple) assert len(result) == 4 assert np.allclose(result, expected_measurements) @pytest.mark.autograd @pytest.mark.parametrize("subspace", [(0, 1), (0, 2)]) def test_autograd_results_and_backprop(self, subspace): """Tests execution and gradients of a basic circuit using autograd.""" phi = qml.numpy.array(-0.52) dev = DefaultQutritMixed() def f(x): qs = self.get_trx_quantum_script(x, subspace) return qml.numpy.array(dev.execute(qs)) result = f(phi) expected = self.expected_trx_circ_expval_values(phi, subspace) assert qml.math.allclose(result, expected) g = qml.jacobian(f)(phi) expected = self.expected_trx_circ_expval_jacobians(phi, subspace) assert qml.math.allclose(g, expected) @pytest.mark.jax @pytest.mark.parametrize("use_jit", (True, False)) @pytest.mark.parametrize("subspace", [(0, 1), (0, 2)]) def test_jax_results_and_backprop(self, use_jit, subspace): """Tests execution and gradients of a basic circuit using jax.""" import jax phi = jax.numpy.array(0.678) dev = DefaultQutritMixed() def f(x): qs = self.get_trx_quantum_script(x, subspace) return dev.execute(qs) if use_jit: f = jax.jit(f) result = f(phi) expected = self.expected_trx_circ_expval_values(phi, subspace) assert qml.math.allclose(result, expected) g = jax.jacobian(f)(phi) expected = self.expected_trx_circ_expval_jacobians(phi, subspace) assert qml.math.allclose(g, expected) @pytest.mark.torch @pytest.mark.parametrize("subspace", [(0, 1), (0, 2)]) def test_torch_results_and_backprop(self, subspace): """Tests execution and gradients of a basic circuit using torch.""" import torch phi = torch.tensor(-0.526, requires_grad=True) dev = DefaultQutritMixed() def f(x): qs = self.get_trx_quantum_script(x, subspace) return dev.execute(qs) result = f(phi) expected = self.expected_trx_circ_expval_values(phi.detach().numpy(), subspace) result_detached = math.asarray(result, like="torch").detach().numpy() assert math.allclose(result_detached, expected) jacobian = math.asarray(torch.autograd.functional.jacobian(f, phi + 0j), like="torch") expected = self.expected_trx_circ_expval_jacobians(phi.detach().numpy(), subspace) assert math.allclose(jacobian.detach().numpy(), expected) @pytest.mark.tf @pytest.mark.parametrize("subspace", [(0, 1), (0, 2)]) def test_tf_results_and_backprop(self, subspace): """Tests execution and gradients of a basic circuit using tensorflow.""" import tensorflow as tf phi = tf.Variable(4.873, dtype="float64") dev = DefaultQutritMixed() with tf.GradientTape(persistent=True) as grad_tape: qs = self.get_trx_quantum_script(phi, subspace) result = dev.execute(qs) expected = self.expected_trx_circ_expval_values(phi, subspace) assert qml.math.allclose(result, expected) expected = self.expected_trx_circ_expval_jacobians(phi, subspace) assert math.all( [ math.allclose(grad_tape.jacobian(one_obs_result, [phi])[0], one_obs_expected) for one_obs_result, one_obs_expected in zip(result, expected) ] ) @pytest.mark.tf @pytest.mark.parametrize("op,param", [(qml.TRX, np.pi), (qml.QutritBasisState, [1])]) def test_qnode_returns_correct_interface(self, op, param): """Test that even if no interface parameters are given, result's type is the correct interface.""" dev = DefaultQutritMixed() @qml.qnode(dev, interface="tf") def circuit(p): op(p, wires=[0]) return qml.expval(qml.GellMann(0, 3)) res = circuit(param) assert qml.math.get_interface(res) == "tensorflow" assert qml.math.allclose(res, -1) def test_basis_state_wire_order(self): """Test that the wire order is correct with a basis state if the tape wires have a non-standard order.""" dev = DefaultQutritMixed() tape = qml.tape.QuantumScript( [qml.QutritBasisState([2], wires=1), qml.TClock(0)], [qml.state()] ) expected_vec = np.array([0, 0, 1, 0, 0, 0, 0, 0, 0], dtype=np.complex128) expected = np.outer(expected_vec, expected_vec) res = dev.execute(tape) assert qml.math.allclose(res, expected) @pytest.mark.parametrize("subspace", [(0, 1), (0, 2)]) class TestSampleMeasurements: """Tests circuits using sample-based measurements. This is a copy of the tests in `test_qutrit_mixed_simulate.py`, but using the device instead. """ @staticmethod def expval_of_TRY_circ(x, subspace): """Find the expval of GellMann_3 on simple TRY circuit.""" if subspace == (0, 1): return np.cos(x) if subspace == (0, 2): return np.cos(x / 2) ** 2 raise ValueError(f"Test cases doesn't support subspace {subspace}") @staticmethod def sample_sum_of_TRY_circ(x, subspace): """Find the expval of computational basis bitstring value for both wires on simple TRY circuit.""" if subspace == (0, 1): return [np.sin(x / 2) ** 2, 0] if subspace == (0, 2): return [2 * np.sin(x / 2) ** 2, 0] raise ValueError(f"Test cases doesn't support subspace {subspace}") @staticmethod def expval_of_2_qutrit_circ(x, subspace): """Gets the expval of GellMann 3 on wire=0 for the 2-qutrit circuit implemented below.""" if subspace == (0, 1): return np.cos(x) if subspace == (0, 2): return np.cos(x / 2) ** 2 raise ValueError(f"Test cases doesn't support subspace {subspace}") @staticmethod def probs_of_2_qutrit_circ(x, y, subspace): """Gets possible measurement values and probabilities for the 2-qutrit circuit implemented below.""" probs = np.array( [ np.cos(x / 2) * np.cos(y / 2), np.cos(x / 2) * np.sin(y / 2), np.sin(x / 2) * np.sin(y / 2), np.sin(x / 2) * np.cos(y / 2), ] ) probs **= 2 if subspace == (0, 1): keys = ["00", "01", "10", "11"] elif subspace == (0, 2): keys = ["00", "02", "20", "22"] else: raise ValueError(f"Test cases doesn't support subspace {subspace}") return keys, probs def test_single_expval(self, subspace): """Test a simple circuit with a single sample-based expval measurement.""" x = np.array(0.732) qs = qml.tape.QuantumScript( [qml.TRY(x, wires=0, subspace=subspace)], [qml.expval(qml.GellMann(0, 3))], shots=1000000, ) dev = DefaultQutritMixed() result = dev.execute(qs) assert isinstance(result, (float, np.ndarray)) assert result.shape == () assert np.allclose(result, self.expval_of_TRY_circ(x, subspace), atol=0.1) def test_single_sample(self, subspace): """Test a simple circuit with a single sample measurement.""" x = np.array(0.732) qs = qml.tape.QuantumScript( [qml.TRY(x, wires=0, subspace=subspace)], [qml.sample(wires=range(2))], shots=10000 ) dev = DefaultQutritMixed() result = dev.execute(qs) assert isinstance(result, (float, np.ndarray)) assert result.shape == (10000, 2) assert np.allclose( np.sum(result, axis=0).astype(np.float32) / 10000, self.sample_sum_of_TRY_circ(x, subspace), atol=0.1, ) def test_multi_measurements(self, subspace): """Test a simple circuit containing multiple sample-based measurements.""" num_shots = 10000 x, y = np.array(0.732), np.array(0.488) qs = qml.tape.QuantumScript( [ qml.TRX(x, wires=0, subspace=subspace), qml.TAdd(wires=[0, 1]), qml.TRY(y, wires=1, subspace=subspace), ], [ qml.expval(qml.GellMann(0, 3)), qml.counts(wires=range(2)), qml.sample(wires=range(2)), ], shots=num_shots, ) dev = DefaultQutritMixed() result = dev.execute(qs) assert isinstance(result, tuple) assert len(result) == 3 assert np.allclose(result[0], self.expval_of_2_qutrit_circ(x, subspace), atol=0.1) expected_keys, expected_probs = self.probs_of_2_qutrit_circ(x, y, subspace) assert list(result[1].keys()) == expected_keys assert np.allclose( np.array(list(result[1].values())) / num_shots, expected_probs, atol=0.1, ) assert result[2].shape == (10000, 2) shots_data = [ [10000, 10000], [(10000, 2)], [10000, 20000], [(10000, 2), 20000], [(10000, 3), 20000, (30000, 2)], ] @pytest.mark.parametrize("shots", shots_data) def test_expval_shot_vector(self, shots, subspace): """Test a simple circuit with a single sample-based expval measurement using shot vectors.""" x = np.array(0.732) shots = qml.measurements.Shots(shots) qs = qml.tape.QuantumScript( [qml.TRY(x, wires=0, subspace=subspace)], [qml.expval(qml.GellMann(0, 3))], shots=shots ) dev = DefaultQutritMixed() result = dev.execute(qs) assert isinstance(result, tuple) assert len(result) == len(list(shots)) expected = self.expval_of_TRY_circ(x, subspace) assert all(isinstance(res, np.float64) for res in result) assert all(res.shape == () for res in result) assert all(np.allclose(res, expected, atol=0.1) for res in result) @pytest.mark.parametrize("shots", shots_data) def test_sample_shot_vector(self, shots, subspace): """Test a simple circuit with a single sample measurement using shot vectors.""" x = np.array(0.732) shots = qml.measurements.Shots(shots) qs = qml.tape.QuantumScript( [qml.TRY(x, wires=0, subspace=subspace)], [qml.sample(wires=range(2))], shots=shots ) dev = DefaultQutritMixed() result = dev.execute(qs) assert isinstance(result, tuple) assert len(result) == len(list(shots)) expected = self.sample_sum_of_TRY_circ(x, subspace) assert all(isinstance(res, np.ndarray) for res in result) assert all(res.shape == (s, 2) for res, s in zip(result, shots)) assert all( np.allclose(np.sum(res, axis=0).astype(np.float32) / s, expected, atol=0.1) for res, s in zip(result, shots) ) @pytest.mark.parametrize("shots", shots_data) def test_multi_measurement_shot_vector(self, shots, subspace): """Test a simple circuit containing multiple measurements using shot vectors.""" x, y = np.array(0.732), np.array(0.488) shots = qml.measurements.Shots(shots) qs = qml.tape.QuantumScript( [ qml.TRX(x, wires=0, subspace=subspace), qml.TAdd(wires=[0, 1]), qml.TRY(y, wires=1, subspace=subspace), ], [ qml.expval(qml.GellMann(0, 3)), qml.counts(wires=range(2)), qml.sample(wires=range(2)), ], shots=shots, ) dev = DefaultQutritMixed() result = dev.execute(qs) assert isinstance(result, tuple) assert len(result) == len(list(shots)) for shot_res, s in zip(result, shots): assert isinstance(shot_res, tuple) assert len(shot_res) == 3 assert isinstance(shot_res[0], np.float64) assert isinstance(shot_res[1], dict) assert isinstance(shot_res[2], np.ndarray) assert np.allclose(shot_res[0], self.expval_of_TRY_circ(x, subspace), atol=0.1) expected_keys, expected_probs = self.probs_of_2_qutrit_circ(x, y, subspace) assert list(shot_res[1].keys()) == expected_keys assert np.allclose( np.array(list(shot_res[1].values())) / s, expected_probs, atol=0.1, ) assert shot_res[2].shape == (s, 2) def test_custom_wire_labels(self, subspace): """Test that custom wire labels works as expected.""" num_shots = 10000 x, y = np.array(0.732), np.array(0.488) qs = qml.tape.QuantumScript( [ qml.TRX(x, wires="b", subspace=subspace), qml.TAdd(wires=["b", "a"]), qml.TRY(y, wires="a", subspace=subspace), ], [ qml.expval(qml.GellMann("b", 3)), qml.counts(wires=["a", "b"]), qml.sample(wires=["b", "a"]), ], shots=num_shots, ) dev = DefaultQutritMixed() result = dev.execute(qs) assert isinstance(result, tuple) assert len(result) == 3 assert isinstance(result[0], np.float64) assert isinstance(result[1], dict) assert isinstance(result[2], np.ndarray) assert np.allclose(result[0], self.expval_of_TRY_circ(x, subspace), atol=0.1) expected_keys, expected_probs = self.probs_of_2_qutrit_circ(x, y, subspace) assert list(result[1].keys()) == expected_keys assert np.allclose( np.array(list(result[1].values())) / num_shots, expected_probs, atol=0.1, ) assert result[2].shape == (num_shots, 2) def test_batch_tapes(self, subspace): """Test that a batch of tapes with sampling works as expected.""" x = np.array(0.732) qs1 = qml.tape.QuantumScript( [qml.TRX(x, wires=0, subspace=subspace)], [qml.sample(wires=(0, 1))], shots=100 ) qs2 = qml.tape.QuantumScript( [qml.TRX(x, wires=0, subspace=subspace)], [qml.sample(wires=1)], shots=50 ) dev = DefaultQutritMixed() results = dev.execute((qs1, qs2)) assert isinstance(results, tuple) assert len(results) == 2 assert all(isinstance(res, (float, np.ndarray)) for res in results) assert results[0].shape == (100, 2) assert results[1].shape == (50,) @pytest.mark.parametrize("all_outcomes", [False, True]) def test_counts_obs(self, all_outcomes, subspace): """Test that a Counts measurement with an observable works as expected.""" x = np.array(np.pi / 2) qs = qml.tape.QuantumScript( [qml.TRY(x, wires=0, subspace=subspace)], [qml.counts(qml.GellMann(0, 3), all_outcomes=all_outcomes)], shots=10000, ) dev = DefaultQutritMixed(seed=123) result = dev.execute(qs) assert isinstance(result, dict) expected_keys = {1, -1} if subspace == (0, 1) else {1, 0} assert set(result.keys()) == expected_keys # check that the count values match the expected values = list(result.values()) assert np.allclose(values[0] / (values[0] + values[1]), 0.5, atol=0.01) class TestExecutingBatches: """Tests involving executing multiple circuits at the same time.""" @staticmethod def f(phi): """A function that executes a batch of scripts on DefaultQutritMixed without preprocessing.""" ops = [ qml.TShift("a"), qml.TShift("b"), qml.TShift("b"), qml.ControlledQutritUnitary( qml.TRX.compute_matrix(phi) @ qml.TRX.compute_matrix(phi, subspace=(1, 2)), control_wires=("a", "b", -3), wires="target", control_values="120", ), ] qs1 = qml.tape.QuantumScript( ops, [ qml.expval(qml.sum(qml.GellMann("target", 2), qml.GellMann("b", 8))), qml.expval(qml.s_prod(3, qml.GellMann("target", 3))), ], ) ops = [ qml.THadamard(0), qml.THadamard(1), qml.TAdd((0, 1)), qml.TRZ(phi, 1), qml.TRZ(phi, 1, subspace=(0, 2)), qml.TAdd((0, 1)), qml.TAdd((0, 1)), qml.THadamard(1), ] qs2 = qml.tape.QuantumScript(ops, [qml.probs(wires=(0, 1))]) return DefaultQutritMixed().execute((qs1, qs2)) @staticmethod def expected(phi): """Gets the expected output of function TestExecutingBatches.f.""" out1 = (-math.sin(phi) - 2 / math.sqrt(3), 3 * math.cos(phi)) x1 = 4 * math.cos(3 / 2 * phi) + 5 x2 = 2 - 2 * math.cos(3 * phi / 2) out2 = ( x1 * np.array([1, 0, 0, 1, 0, 0, 1, 0, 0]) + x2 * np.array([0, 1, 1, 0, 1, 1, 0, 1, 1]) ) / 27 return (out1, out2) @staticmethod def nested_compare(x1, x2): """Assert two ragged lists are equal.""" assert len(x1) == len(x2) assert len(x1[0]) == len(x2[0]) assert qml.math.allclose(x1[0][0], x2[0][0]) assert qml.math.allclose(x1[0][1], x2[0][1]) assert qml.math.allclose(x1[1], x2[1]) def test_numpy(self): """Test that results are expected when the parameter uses numpy interface.""" phi = 0.892 results = self.f(phi) expected = self.expected(phi) self.nested_compare(results, expected) @pytest.mark.autograd def test_autograd(self): """Test batches can be executed and have backprop derivatives using autograd.""" phi = qml.numpy.array(-0.629) results = self.f(phi) expected = self.expected(phi) self.nested_compare(results, expected) g0 = qml.jacobian(lambda x: qml.numpy.array(self.f(x)[0]))(phi) g0_expected = qml.jacobian(lambda x: qml.numpy.array(self.expected(x)[0]))(phi) assert qml.math.allclose(g0, g0_expected) g1 = qml.jacobian(lambda x: qml.numpy.array(self.f(x)[1]))(phi) g1_expected = qml.jacobian(lambda x: qml.numpy.array(self.expected(x)[1]))(phi) assert qml.math.allclose(g1, g1_expected) @pytest.mark.jax @pytest.mark.parametrize("use_jit", (True, False)) def test_jax(self, use_jit): """Test batches can be executed and have backprop derivatives using jax.""" import jax phi = jax.numpy.array(0.123) f = jax.jit(self.f) if use_jit else self.f results = f(phi) expected = self.expected(phi) self.nested_compare(results, expected) g = jax.jacobian(f)(phi) g_expected = jax.jacobian(self.expected)(phi) self.nested_compare(g, g_expected) @pytest.mark.torch def test_torch(self): """Test batches can be executed and have backprop derivatives using torch.""" import torch x = torch.tensor(9.6243) results = self.f(x) expected = self.expected(x) self.nested_compare(results, expected) jacobian_1 = torch.autograd.functional.jacobian(lambda y: self.f(y)[0], x) assert qml.math.allclose(jacobian_1[0], -qml.math.cos(x)) assert qml.math.allclose(jacobian_1[1], -3 * qml.math.sin(x)) jacobian_1 = torch.autograd.functional.jacobian(lambda y: self.f(y)[1], x) x1 = 2 * -math.sin(3 / 2 * x) x2 = math.sin(3 / 2 * x) jacobian_3 = math.array([x1, x2, x2, x1, x2, x2, x1, x2, x2]) / 9 assert qml.math.allclose(jacobian_1, jacobian_3) @pytest.mark.tf def test_tf(self): """Test batches can be executed and have backprop derivatives using tensorflow.""" import tensorflow as tf x = tf.Variable(5.2281, dtype="float64") with tf.GradientTape(persistent=True) as tape: results = self.f(x) expected = self.expected(x) self.nested_compare(results, expected) jacobian_00 = tape.gradient(results[0][0], x) assert qml.math.allclose(jacobian_00, -qml.math.cos(x)) jacobian_01 = tape.gradient(results[0][1], x) assert qml.math.allclose(jacobian_01, -3 * qml.math.sin(x)) jacobian_1 = tape.jacobian(results[1], x) x1 = 2 * -math.sin(3 / 2 * x) x2 = math.sin(3 / 2 * x) jacobian_3 = math.array([x1, x2, x2, x1, x2, x2, x1, x2, x2]) / 9 assert qml.math.allclose(jacobian_1, jacobian_3) @pytest.mark.usefixtures("use_legacy_and_new_opmath") class TestSumOfTermsDifferentiability: """Tests Hamiltonian and sum expvals are still differentiable. This is a copy of the tests in `test_qutrit_mixed_measure.py`, but using the device instead. """ x = 0.52 @staticmethod def f(scale, coeffs, num_wires=5, offset=0.1): """Function to differentiate that implements a circuit with a SumOfTerms operator.""" ops = [qml.TRX(offset + scale * i, wires=i, subspace=(0, 2)) for i in range(num_wires)] H = qml.Hamiltonian( coeffs, [ reduce(lambda x, y: x @ y, (qml.GellMann(i, 3) for i in range(num_wires))), reduce(lambda x, y: x @ y, (qml.GellMann(i, 5) for i in range(num_wires))), ], ) qs = qml.tape.QuantumScript(ops, [qml.expval(H)]) return DefaultQutritMixed().execute(qs) @staticmethod def expected(scale, coeffs, num_wires=5, offset=0.1, like="numpy"): """Gets the expected output of function TestSumOfTermsDifferentiability.f.""" phase = offset + scale * qml.math.asarray(range(num_wires), like=like) cosines = qml.math.cos(phase / 2) ** 2 sines = -qml.math.sin(phase) return coeffs[0] * qml.math.prod(cosines) + coeffs[1] * qml.math.prod(sines) @pytest.mark.autograd @pytest.mark.parametrize( "coeffs", [ (qml.numpy.array(2.5), qml.numpy.array(6.2)), (qml.numpy.array(2.5, requires_grad=False), qml.numpy.array(6.2, requires_grad=False)), ], ) def test_autograd_backprop(self, coeffs): """Test that backpropagation derivatives work in autograd with Hamiltonians using new and old math.""" x = qml.numpy.array(self.x) out = self.f(x, coeffs) expected_out = self.expected(x, coeffs) assert qml.math.allclose(out, expected_out) gradient = qml.grad(self.f)(x, coeffs) expected_gradient = qml.grad(self.expected)(x, coeffs) assert qml.math.allclose(expected_gradient, gradient) @pytest.mark.autograd def test_autograd_backprop_coeffs(self): """Test that backpropagation derivatives work in autograd with the coefficients of Hamiltonians using new and old math.""" coeffs = qml.numpy.array((2.5, 6.2), requires_grad=True) gradient = qml.grad(self.f, argnum=1)(self.x, coeffs) expected_gradient = qml.grad(self.expected)(self.x, coeffs) assert len(gradient) == 2 assert qml.math.allclose(expected_gradient, gradient) @pytest.mark.jax @pytest.mark.parametrize("use_jit", (True, False)) def test_jax_backprop(self, use_jit): """Test that backpropagation derivatives work with jax with Hamiltonians using new and old math.""" import jax jax.config.update("jax_enable_x64", True) x = jax.numpy.array(self.x, dtype=jax.numpy.float64) coeffs = (5.2, 6.7) f = jax.jit(self.f, static_argnums=(1, 2, 3, 4)) if use_jit else self.f out = f(x, coeffs) expected_out = self.expected(x, coeffs) assert qml.math.allclose(out, expected_out) gradient = jax.grad(f)(x, coeffs) expected_gradient = jax.grad(self.expected)(x, coeffs) assert qml.math.allclose(expected_gradient, gradient) @pytest.mark.jax def test_jax_backprop_coeffs(self): """Test that backpropagation derivatives work with jax with the coefficients of Hamiltonians using new and old math.""" import jax jax.config.update("jax_enable_x64", True) coeffs = jax.numpy.array((5.2, 6.7), dtype=jax.numpy.float64) gradient = jax.grad(self.f, argnums=1)(self.x, coeffs) expected_gradient = jax.grad(self.expected, argnums=1)(self.x, coeffs) assert len(gradient) == 2 assert qml.math.allclose(expected_gradient, gradient) @pytest.mark.torch def test_torch_backprop(self): """Test that backpropagation derivatives work with torch with Hamiltonians using new and old math.""" import torch coeffs = [ torch.tensor(9.2, requires_grad=False, dtype=torch.float64), torch.tensor(6.2, requires_grad=False, dtype=torch.float64), ] x = torch.tensor(-0.289, requires_grad=True, dtype=torch.float64) x2 = torch.tensor(-0.289, requires_grad=True, dtype=torch.float64) out = self.f(x, coeffs) expected_out = self.expected(x2, coeffs, like="torch") assert qml.math.allclose(out, expected_out) out.backward() expected_out.backward() assert qml.math.allclose(x.grad, x2.grad) @pytest.mark.torch def test_torch_backprop_coeffs(self): """Test that backpropagation derivatives work with torch with the coefficients of Hamiltonians using new and old math.""" import torch coeffs = torch.tensor((9.2, 6.2), requires_grad=True, dtype=torch.float64) coeffs_expected = torch.tensor((9.2, 6.2), requires_grad=True, dtype=torch.float64) x = torch.tensor(-0.289, requires_grad=False, dtype=torch.float64) out = self.f(x, coeffs) expected_out = self.expected(x, coeffs_expected, like="torch") assert qml.math.allclose(out, expected_out) out.backward() expected_out.backward() assert len(coeffs.grad) == 2 assert qml.math.allclose(coeffs.grad, coeffs_expected.grad) @pytest.mark.tf def test_tf_backprop(self): """Test that backpropagation derivatives work with tensorflow with Hamiltonians using new and old math.""" import tensorflow as tf x = tf.Variable(self.x, dtype="float64") coeffs = [8.3, 5.7] with tf.GradientTape() as tape1: out = self.f(x, coeffs) with tf.GradientTape() as tape2: expected_out = self.expected(x, coeffs) assert qml.math.allclose(out, expected_out) gradient = tape1.gradient(out, x) expected_gradient = tape2.gradient(expected_out, x) assert qml.math.allclose(expected_gradient, gradient) @pytest.mark.tf def test_tf_backprop_coeffs(self): """Test that backpropagation derivatives work with tensorflow with the coefficients of Hamiltonians using new and old math.""" import tensorflow as tf coeffs = tf.Variable([8.3, 5.7], dtype="float64") with tf.GradientTape() as tape1: out = self.f(self.x, coeffs) with tf.GradientTape() as tape2: expected_out = self.expected(self.x, coeffs) gradient = tape1.gradient(out, coeffs) expected_gradient = tape2.gradient(expected_out, coeffs) assert len(gradient) == 2 assert qml.math.allclose(expected_gradient, gradient) class TestRandomSeed: """Test that the device behaves correctly when provided with a random seed.""" measurements = [ [qml.sample(wires=0)], [qml.expval(qml.GellMann(0, 3))], [qml.counts(wires=0)], [qml.sample(wires=0), qml.expval(qml.GellMann(0, 8)), qml.counts(wires=0)], ] @pytest.mark.parametrize("measurements", measurements) def test_same_seed(self, measurements): """Test that different devices given the same random seed will produce the same results.""" qs = qml.tape.QuantumScript([qml.THadamard(0)], measurements, shots=1000) dev1 = DefaultQutritMixed(seed=123) result1 = dev1.execute(qs) dev2 = DefaultQutritMixed(seed=123) result2 = dev2.execute(qs) if len(measurements) == 1: result1, result2 = [result1], [result2] assert all(np.all(res1 == res2) for res1, res2 in zip(result1, result2)) @pytest.mark.slow def test_different_seed(self): """Test that different devices given different random seeds will produce different results (with almost certainty).""" qs = qml.tape.QuantumScript([qml.THadamard(0)], [qml.sample(wires=0)], shots=1000) dev1 = DefaultQutritMixed(seed=None) result1 = dev1.execute(qs) dev2 = DefaultQutritMixed(seed=123) result2 = dev2.execute(qs) dev3 = DefaultQutritMixed(seed=456) result3 = dev3.execute(qs) # assert results are pairwise different assert np.any(result1 != result2) assert np.any(result1 != result3) assert np.any(result2 != result3) @pytest.mark.parametrize("measurements", measurements) def test_different_executions(self, measurements): """Test that the same device will produce different results every execution.""" qs = qml.tape.QuantumScript([qml.THadamard(0)], measurements, shots=1000) dev = DefaultQutritMixed(seed=123) result1 = dev.execute(qs) result2 = dev.execute(qs) if len(measurements) == 1: result1, result2 = [result1], [result2] assert all(np.any(res1 != res2) for res1, res2 in zip(result1, result2)) @pytest.mark.parametrize("measurements", measurements) def test_global_seed_and_device_seed(self, measurements): """Test that a global seed does not affect the result of devices provided with a seed.""" qs = qml.tape.QuantumScript([qml.THadamard(0)], measurements, shots=1000) # expected result dev1 = DefaultQutritMixed(seed=123) result1 = dev1.execute(qs) # set a global seed both before initialization of the # device and before execution of the tape np.random.seed(456) dev2 = DefaultQutritMixed(seed=123) np.random.seed(789) result2 = dev2.execute(qs) if len(measurements) == 1: result1, result2 = [result1], [result2] assert all(np.all(res1 == res2) for res1, res2 in zip(result1, result2)) def test_global_seed_no_device_seed_by_default(self): """Test that the global numpy seed initializes the rng if device seed is None.""" np.random.seed(42) dev = DefaultQutritMixed() first_num = dev._rng.random() # pylint: disable=protected-access np.random.seed(42) dev2 = DefaultQutritMixed() second_num = dev2._rng.random() # pylint: disable=protected-access assert qml.math.allclose(first_num, second_num) np.random.seed(42) dev2 = DefaultQutritMixed(seed="global") third_num = dev2._rng.random() # pylint: disable=protected-access assert qml.math.allclose(third_num, first_num) def test_none_seed_not_using_global_rng(self): """Test that if the seed is None, it is uncorrelated with the global rng.""" np.random.seed(42) dev = DefaultQutritMixed(seed=None) first_nums = dev._rng.random(10) # pylint: disable=protected-access np.random.seed(42) dev2 = DefaultQutritMixed(seed=None) second_nums = dev2._rng.random(10) # pylint: disable=protected-access assert not qml.math.allclose(first_nums, second_nums) def test_rng_as_seed(self): """Test that a PRNG can be passed as a seed.""" rng1 = np.random.default_rng(42) first_num = rng1.random() rng = np.random.default_rng(42) dev = DefaultQutritMixed(seed=rng) second_num = dev._rng.random() # pylint: disable=protected-access assert qml.math.allclose(first_num, second_num) @pytest.mark.jax class TestPRNGKeySeed: """Test that the device behaves correctly when provided with a JAX PRNG key.""" def test_prng_key_as_seed(self): """Test that a jax PRNG can be passed as a seed.""" import jax jax.config.update("jax_enable_x64", True) from jax import random key1 = random.key(123) first_nums = random.uniform(key1, shape=(10,)) key = random.key(123) dev = DefaultQutritMixed(seed=key) second_nums = random.uniform(dev._prng_key, shape=(10,)) # pylint: disable=protected-access assert np.all(first_nums == second_nums) def test_same_device_prng_key(self): """Test a device with a given jax.random.PRNGKey will produce the same samples repeatedly.""" import jax qs = qml.tape.QuantumScript([qml.THadamard(0)], [qml.sample(wires=0)], shots=1000) config = ExecutionConfig(interface="jax") dev = DefaultQutritMixed(seed=jax.random.PRNGKey(123)) result1 = dev.execute(qs, config) for _ in range(10): result2 = dev.execute(qs, config) assert np.all(result1 == result2) def test_same_prng_key(self): """Test that different devices given the same random jax.random.PRNGKey as a seed will produce the same results for sample, even with different seeds""" import jax qs = qml.tape.QuantumScript([qml.THadamard(0)], [qml.sample(wires=0)], shots=1000) config = ExecutionConfig(interface="jax") dev1 = DefaultQutritMixed(seed=jax.random.PRNGKey(123)) result1 = dev1.execute(qs, config) dev2 = DefaultQutritMixed(seed=jax.random.PRNGKey(123)) result2 = dev2.execute(qs, config) assert np.all(result1 == result2) def test_different_prng_key(self): """Test that different devices given different jax.random.PRNGKey values will produce different results""" import jax qs = qml.tape.QuantumScript([qml.THadamard(0)], [qml.sample(wires=0)], shots=1000) config = ExecutionConfig(interface="jax") dev1 = DefaultQutritMixed(seed=jax.random.PRNGKey(246)) result1 = dev1.execute(qs, config) dev2 = DefaultQutritMixed(seed=jax.random.PRNGKey(123)) result2 = dev2.execute(qs, config) assert np.any(result1 != result2) def test_different_executions_same_prng_key(self): """Test that the same device will produce the same results every execution if the seed is a jax.random.PRNGKey""" import jax qs = qml.tape.QuantumScript([qml.THadamard(0)], [qml.sample(wires=0)], shots=1000) config = ExecutionConfig(interface="jax") dev = DefaultQutritMixed(seed=jax.random.PRNGKey(77)) result1 = dev.execute(qs, config) result2 = dev.execute(qs, config) assert np.all(result1 == result2) @pytest.mark.parametrize( "obs", [ qml.Hamiltonian([0.8, 0.5], [qml.GellMann(0, 3), qml.GellMann(0, 1)]), qml.s_prod(0.8, qml.GellMann(0, 3)) + qml.s_prod(0.5, qml.GellMann(0, 1)), ], ) @pytest.mark.usefixtures("use_legacy_and_new_opmath") class TestHamiltonianSamples: """Test that the measure_with_samples function works as expected for Hamiltonian and Sum observables. This is a copy of the tests in `test_qutrit_mixed_sampling.py`, but using the device instead. """ def test_hamiltonian_expval(self, obs): """Tests that sampling works well for Hamiltonian and Sum observables.""" if not qml.operation.active_new_opmath(): obs = qml.operation.convert_to_legacy_H(obs) x, y = np.array(0.67), np.array(0.95) ops = [qml.TRY(x, wires=0), qml.TRZ(y, wires=0)] dev = DefaultQutritMixed(seed=100) qs = qml.tape.QuantumScript(ops, [qml.expval(obs)], shots=10000) res = dev.execute(qs) expected = 0.8 * np.cos(x) + 0.5 * np.cos(y) * np.sin(x) assert np.allclose(res, expected, atol=0.01) def test_hamiltonian_expval_shot_vector(self, obs): """Test that sampling works well for Hamiltonian and Sum observables with a shot vector.""" if not qml.operation.active_new_opmath(): obs = qml.operation.convert_to_legacy_H(obs) shots = qml.measurements.Shots((10000, 100000)) x, y = np.array(0.67), np.array(0.95) ops = [qml.TRY(x, wires=0), qml.TRZ(y, wires=0)] dev = DefaultQutritMixed(seed=100) qs = qml.tape.QuantumScript(ops, [qml.expval(obs)], shots=shots) res = dev.execute(qs) expected = 0.8 * np.cos(x) + 0.5 * np.cos(y) * np.sin(x) assert len(res) == 2 assert isinstance(res, tuple) assert np.allclose(res[0], expected, atol=0.01) assert np.allclose(res[1], expected, atol=0.01) class TestIntegration: """Various integration tests""" @pytest.mark.parametrize("wires,expected", [(None, [1, 0]), (3, [0, 0, 1])]) def test_sample_uses_device_wires(self, wires, expected): """Test that if device wires are given, then they are used by sample.""" dev = qml.device("default.qutrit.mixed", wires=wires, shots=5) @qml.qnode(dev) def circuit(): qml.TShift(2) qml.Identity(0) return qml.sample() assert np.array_equal(circuit(), [expected] * 5) @pytest.mark.parametrize( "wires,expected", [ (None, [0] * 3 + [1] + [0] * 5), (3, [0, 1] + [0] * 25), ], ) def test_probs_uses_device_wires(self, wires, expected): """Test that if device wires are given, then they are used by probs.""" dev = qml.device("default.qutrit.mixed", wires=wires) @qml.qnode(dev) def circuit(): qml.TShift(2) qml.Identity(0) return qml.probs() assert np.array_equal(circuit(), expected) @pytest.mark.parametrize( "wires,expected", [ (None, {"10": 10}), (3, {"001": 10}), ], ) def test_counts_uses_device_wires(self, wires, expected): """Test that if device wires are given, then they are used by probs.""" dev = qml.device("default.qutrit.mixed", wires=wires, shots=10) @qml.qnode(dev, interface=None) def circuit(): qml.TShift(2) qml.Identity(0) return qml.counts() assert circuit() == expected @pytest.mark.jax @pytest.mark.parametrize("measurement_func", [qml.expval, qml.var]) def test_differentiate_jitted_qnode(self, measurement_func): """Test that a jitted qnode can be correctly differentiated""" import jax if measurement_func is qml.var and not qml.operation.active_new_opmath(): pytest.skip(reason="Variance for this test circuit not supported with legacy opmath") dev = qml.device("default.qutrit.mixed") def qfunc(x, y): qml.TRX(x, 0) return measurement_func(qml.Hamiltonian(y, [qml.GellMann(0, 3)])) qnode = qml.QNode(qfunc, dev, interface="jax") qnode_jit = jax.jit(qml.QNode(qfunc, dev, interface="jax")) x = jax.numpy.array(0.5) y = jax.numpy.array([0.5]) res = qnode(x, y) res_jit = qnode_jit(x, y) assert qml.math.allclose(res, res_jit) grad = jax.grad(qnode)(x, y) grad_jit = jax.grad(qnode_jit)(x, y) assert qml.math.allclose(grad, grad_jit) @pytest.mark.parametrize("num_wires", [2, 3]) class TestReadoutError: """Tests for measurement readout error""" setup_unitary = np.array( [ [1 / np.sqrt(2), 1 / np.sqrt(3), 1 / np.sqrt(6)], [np.sqrt(2 / 29), np.sqrt(3 / 29), -2 * np.sqrt(6 / 29)], [-5 / np.sqrt(58), 7 / np.sqrt(87), 1 / np.sqrt(174)], ] ).T def setup_state(self, num_wires): """Sets up a basic state used for testing.""" qml.QutritUnitary(self.setup_unitary, wires=0) qml.QutritUnitary(self.setup_unitary, wires=1) if num_wires == 3: qml.TAdd(wires=(0, 2)) @staticmethod def get_expected_dm(num_wires): """Gets the expected density matrix of the circuit for the first num_wires""" state = np.array([2, 3, 6], dtype=complex) ** -(1 / 2) if num_wires == 2: state = np.kron(state, state) if num_wires == 3: state = sum( [ state[i] * reduce(np.kron, [v, state, v]) for i, v in enumerate([[1, 0, 0], [0, 1, 0], [0, 0, 1]]) ] ) return np.outer(state, state) # Set up the sets of probabilities that are inputted as the readout errors. relax_and_misclass = [ [(0, 0, 0), (0, 0, 0)], [None, (1, 0, 0)], [None, (0, 1, 0)], [None, (0, 0, 1)], [(1, 0, 0), None], [(0, 1, 0), None], [(1, 0, 1), None], [(0, 1, 0), (0, 0, 1)], [None, (0.1, 0.2, 0.4)], [(0.2, 0.1, 0.3), None], [(0.2, 0.1, 0.4), (0.1, 0.2, 0.5)], ] # Expected probabilities of measuring each state after the above readout errors are applied. expected_probs = [ [1 / 2, 1 / 3, 1 / 6], [1 / 3, 1 / 2, 1 / 6], [1 / 6, 1 / 3, 1 / 2], [1 / 2, 1 / 6, 1 / 3], [5 / 6, 0, 1 / 6], [2 / 3, 1 / 3, 0], [5 / 6, 1 / 6, 0], [2 / 3, 0, 1 / 3], [5 / 12, 17 / 60, 0.3], [7 / 12, 19 / 60, 0.1], [11 / 24, 7 / 30, 37 / 120], ] @pytest.mark.parametrize( "relax_and_misclass, expected", zip(relax_and_misclass, expected_probs) ) def test_probs_with_readout_error(self, num_wires, relax_and_misclass, expected): """Tests the measurement results for probs""" dev = qml.device( "default.qutrit.mixed", wires=num_wires, readout_relaxation_probs=relax_and_misclass[0], readout_misclassification_probs=relax_and_misclass[1], ) @qml.qnode(dev) def circuit(): self.setup_state(num_wires) return qml.probs(wires=0) res = circuit() assert np.allclose(res, expected) # Expected expval list from circuit with diagonal observables after the readout errors # defined by relax_and_misclass are applied. expected_commuting_expvals = [ [1 / 6, 1 / (2 * np.sqrt(3)), 1 / 6], [-1 / 6, 1 / (2 * np.sqrt(3)), -1 / 6], [-1 / 6, -1 / (2 * np.sqrt(3)), -1 / 6], [1 / 3, 0, 1 / 3], [5 / 6, 1 / (2 * np.sqrt(3)), 5 / 6], [1 / 3, 1 / np.sqrt(3), 1 / 3], [2 / 3, 1 / np.sqrt(3), 2 / 3], [4 / 6, 0, 4 / 6], [2 / 15, 1 / (10 * np.sqrt(3)), 2 / 15], [4 / 15, 7 / (10 * np.sqrt(3)), 4 / 15], [9 / 40, 3 / (40 * np.sqrt(3)), 9 / 40], ] @pytest.mark.parametrize( "relax_and_misclass, expected", zip(relax_and_misclass, expected_commuting_expvals) ) def test_readout_expval_commuting(self, num_wires, relax_and_misclass, expected): """Tests the measurement results for expval of diagonal GellMann observables (3 and 8)""" dev = qml.device( "default.qutrit.mixed", wires=num_wires, readout_relaxation_probs=relax_and_misclass[0], readout_misclassification_probs=relax_and_misclass[1], ) @qml.qnode(dev) def circuit(): self.setup_state(num_wires) return ( qml.expval(qml.GellMann(0, 3)), qml.expval(qml.GellMann(0, 8)), qml.expval(qml.GellMann(1, 3)), ) res = circuit() assert np.allclose(res, expected) # Expected expval list from circuit with non-diagonal observables after the measurement errors # defined by relax_and_misclass are applied. The readout error is applied to the circuit shown # above so the pre measurement probabilities are the same. expected_noncommuting_expvals = [ [-1 / 3, -7 / 6, 1 / 6], [-1 / 6, -1, -1 / 6], [1 / 3, -1 / 6, -1 / 6], [-1 / 6, -5 / 6, 1 / 3], [-2 / 3, -3 / 2, 5 / 6], [-2 / 3, -5 / 3, 1 / 3], [-5 / 6, -11 / 6, 2 / 3], [-1 / 3, -1, 4 / 6], [-7 / 60, -49 / 60, 2 / 15], [-29 / 60, -83 / 60, 4 / 15], [-3 / 20, -101 / 120, 9 / 40], ] @pytest.mark.parametrize( "relax_and_misclass, expected", zip(relax_and_misclass, expected_noncommuting_expvals) ) def test_readout_expval_non_commuting(self, num_wires, relax_and_misclass, expected): """Tests the measurement results for expval of GellMann 1 observables""" dev = qml.device( "default.qutrit.mixed", wires=num_wires, readout_relaxation_probs=relax_and_misclass[0], readout_misclassification_probs=relax_and_misclass[1], ) # Create matrices for the observables with diagonalizing matrix :math:`THadamard^\dag` inv_sqrt_3_i = 1j / np.sqrt(3) non_commuting_obs_one = np.array( [ [0, -1 + inv_sqrt_3_i, -1 - inv_sqrt_3_i], [-1 - inv_sqrt_3_i, 0, -1 + inv_sqrt_3_i], [-1 + inv_sqrt_3_i, -1 - inv_sqrt_3_i, 0], ] ) non_commuting_obs_one /= 2 non_commuting_obs_two = np.array( [ [-2 / 3, -2 / 3 + inv_sqrt_3_i, -2 / 3 - inv_sqrt_3_i], [-2 / 3 - inv_sqrt_3_i, -2 / 3, -2 / 3 + inv_sqrt_3_i], [-2 / 3 + inv_sqrt_3_i, -2 / 3 - inv_sqrt_3_i, -2 / 3], ] ) @qml.qnode(dev) def circuit(): self.setup_state(num_wires) qml.THadamard(wires=0) qml.THadamard(wires=1, subspace=(0, 1)) return ( qml.expval(qml.THermitian(non_commuting_obs_one, 0)), qml.expval(qml.THermitian(non_commuting_obs_two, 0)), qml.expval(qml.GellMann(1, 1)), ) res = circuit() assert np.allclose(res, expected) state_relax_and_misclass = [ [(0, 0, 0), (0, 0, 0)], [(0.1, 0.15, 0.25), (0.1, 0.15, 0.25)], [(1, 0, 1), (1, 0, 0)], ] @pytest.mark.parametrize("relaxations, misclassifications", state_relax_and_misclass) def test_readout_state(self, num_wires, relaxations, misclassifications): """Tests the state output is not affected by readout error""" dev = qml.device( "default.qutrit.mixed", wires=num_wires, readout_relaxation_probs=relaxations, readout_misclassification_probs=misclassifications, ) @qml.qnode(dev) def circuit(): self.setup_state(num_wires) return qml.state() res = circuit() assert np.allclose(res, self.get_expected_dm(num_wires)) @pytest.mark.parametrize("relaxations, misclassifications", state_relax_and_misclass) def test_readout_density_matrix(self, num_wires, relaxations, misclassifications): """Tests the density matrix output is not affected by readout error""" dev = qml.device( "default.qutrit.mixed", wires=num_wires, readout_relaxation_probs=relaxations, readout_misclassification_probs=misclassifications, ) @qml.qnode(dev) def circuit(): self.setup_state(num_wires) return qml.density_matrix(wires=1) res = circuit() assert np.allclose(res, self.get_expected_dm(1)) @pytest.mark.parametrize( "relaxations, misclassifications, expected", [ ((0, 0, 0), (0, 0, 0), [(np.ones(2) * 2)] * 2), (None, (0, 0, 1), [np.ones(2)] * 2), ((0, 0, 1), None, [np.ones(2)] * 2), (None, (0, 1, 0), [np.zeros(2)] * 2), ((0, 1, 0), None, [np.zeros(2)] * 2), ], ) def test_readout_sample(self, num_wires, relaxations, misclassifications, expected): """Tests the sample output with readout error""" dev = qml.device( "default.qutrit.mixed", shots=2, wires=num_wires, readout_relaxation_probs=relaxations, readout_misclassification_probs=misclassifications, ) @qml.qnode(dev) def circuit(): qml.QutritBasisState([2] * num_wires, wires=range(num_wires)) return qml.sample(wires=[0, 1]) res = circuit() assert np.allclose(res, expected) @pytest.mark.parametrize( "relaxations, misclassifications, expected", [ ((0, 0, 0), (0, 0, 0), {"22": 100}), (None, (0, 0, 1), {"11": 100}), ((0, 0, 1), None, {"11": 100}), (None, (0, 1, 0), {"00": 100}), ((0, 1, 0), None, {"00": 100}), ], ) def test_readout_counts(self, num_wires, relaxations, misclassifications, expected): """Tests the counts output with readout error""" dev = qml.device( "default.qutrit.mixed", shots=100, wires=num_wires, readout_relaxation_probs=relaxations, readout_misclassification_probs=misclassifications, ) @qml.qnode(dev) def circuit(): qml.QutritBasisState([2] * num_wires, wires=range(num_wires)) return qml.counts(wires=[0, 1]) res = circuit() assert res == expected @pytest.mark.parametrize( "relaxations, misclassifications, expected", [ [None, (0.1, 0.2, 0.4), [5 / 12, 17 / 60, 0.3]], [(0.2, 0.1, 0.3), None, [7 / 12, 19 / 60, 0.1]], [(0.2, 0.1, 0.4), (0.1, 0.2, 0.5), [11 / 24, 7 / 30, 37 / 120]], ], ) def test_approximate_readout_counts(self, num_wires, relaxations, misclassifications, expected): """Tests the counts output with readout error""" num_shots = 10000 dev = qml.device( "default.qutrit.mixed", shots=num_shots, wires=num_wires, readout_relaxation_probs=relaxations, readout_misclassification_probs=misclassifications, seed=221349, ) @qml.qnode(dev) def circuit(): self.setup_state(num_wires) return qml.counts(wires=[0]) res = circuit() assert isinstance(res, dict) assert len(res) == 3 cases = ["0", "1", "2"] for case, expected_result in zip(cases, expected): assert np.isclose(res[case] / num_shots, expected_result, atol=0.05) @pytest.mark.parametrize( "relaxations,misclassifications", [ [(0.1, 0.2), None], [None, (0.1, 0.2, 0.3, 0.1)], [(0.1, 0.2, 0.3, 0.1), (0.1, 0.2, 0.3)], ], ) def test_measurement_error_validation(self, relaxations, misclassifications, num_wires): """Ensure error is raised for wrong number of arguments inputted in readout errors.""" with pytest.raises(qml.DeviceError, match="results in error:"): qml.device( "default.qutrit.mixed", wires=num_wires, readout_relaxation_probs=relaxations, readout_misclassification_probs=misclassifications, ) def test_prob_type(self, num_wires): """Tests that an error is raised for wrong data type in readout errors""" with pytest.raises(qml.DeviceError, match="results in error:"): qml.device( "default.qutrit.mixed", wires=num_wires, readout_relaxation_probs=[0.1, 0.2, "0.3"] ) with pytest.raises(qml.DeviceError, match="results in error:"): qml.device( "default.qutrit.mixed", wires=num_wires, readout_misclassification_probs=[0.1, 0.2, "0.3"], ) diff_parameters = [ [ None, [0.1, 0.2, 0.4], [ [ [1 / 3 - 1 / 2, 1 / 6 - 1 / 2, 0.0], [1 / 2 - 1 / 3, 0.0, 1 / 6 - 1 / 3], [0.0, 1 / 2 - 1 / 6, 1 / 3 - 1 / 6], ] ], ], [ [0.2, 0.1, 0.3], None, [ [ [1 / 3, 1 / 6, 0.0], [-1 / 3, 0.0, 1 / 6], [0.0, -1 / 6, -1 / 6], ] ], ], [ [0.2, 0.1, 0.3], [0.0, 0.0, 0.0], [ [[1 / 3, 1 / 6, 0.0], [-1 / 3, 0.0, 1 / 6], [0.0, -1 / 6, -1 / 6]], [ [19 / 60 - 7 / 12, 0.1 - 7 / 12, 0.0], [7 / 12 - 19 / 60, 0.0, 0.1 - 19 / 60], [0.0, 7 / 12 - 0.1, 19 / 60 - 0.1], ], ], ], ] def get_diff_function(self, interface, num_wires): """Get the function to differentiate for following differentiability interface tests""" def diff_func(relaxations, misclassifications): dev = qml.device( "default.qutrit.mixed", wires=num_wires, readout_relaxation_probs=relaxations, readout_misclassification_probs=misclassifications, ) @qml.qnode(dev, interface=interface) def circuit(): self.setup_state(num_wires) return qml.probs(0) return circuit() return diff_func @pytest.mark.autograd @pytest.mark.parametrize("relaxations, misclassifications, expected", diff_parameters) def test_differentiation_autograd(self, num_wires, relaxations, misclassifications, expected): """Tests the differentiation of readout errors using autograd""" if misclassifications is None: args_to_diff = (0,) relaxations = qnp.array(relaxations) elif relaxations is None: args_to_diff = (1,) misclassifications = qnp.array(misclassifications) else: args_to_diff = (0, 1) relaxations = qnp.array(relaxations) misclassifications = qnp.array(misclassifications) diff_func = self.get_diff_function("autograd", num_wires) jac = qml.jacobian(diff_func, args_to_diff)(relaxations, misclassifications) assert np.allclose(jac, expected) @pytest.mark.jax @pytest.mark.parametrize("relaxations, misclassifications, expected", diff_parameters) @pytest.mark.parametrize("use_jit", (True, False)) def test_differentiation_jax( # pylint: disable=too-many-arguments self, num_wires, relaxations, misclassifications, use_jit, expected ): """Tests the differentiation of readout errors using JAX""" import jax if misclassifications is None: args_to_diff = (0,) relaxations = jax.numpy.array(relaxations) elif relaxations is None: args_to_diff = (1,) misclassifications = jax.numpy.array(misclassifications) else: args_to_diff = (0, 1) relaxations = jax.numpy.array(relaxations) misclassifications = jax.numpy.array(misclassifications) diff_func = self.get_diff_function("jax", num_wires) if use_jit: diff_func = jax.jit(diff_func) jac = jax.jacobian(diff_func, args_to_diff)(relaxations, misclassifications) assert np.allclose(jac, expected) @pytest.mark.torch @pytest.mark.parametrize("relaxations, misclassifications, expected", diff_parameters) def test_differentiation_torch(self, num_wires, relaxations, misclassifications, expected): """Tests the differentiation of readout errors using PyTorch""" import torch if misclassifications is None: relaxations = torch.tensor(relaxations, requires_grad=True, dtype=torch.float64) diff_func = partial(self.get_diff_function("torch", num_wires), misclassifications=None) diff_variables = relaxations elif relaxations is None: misclassifications = torch.tensor( misclassifications, requires_grad=True, dtype=torch.float64 ) def diff_func(misclass): return self.get_diff_function("torch", num_wires)(None, misclass) diff_variables = misclassifications else: relaxations = torch.tensor(relaxations, requires_grad=True, dtype=torch.float64) misclassifications = torch.tensor( misclassifications, requires_grad=True, dtype=torch.float64 ) diff_variables = (relaxations, misclassifications) diff_func = self.get_diff_function("torch", num_wires) jac = torch.autograd.functional.jacobian(diff_func, diff_variables) if isinstance(jac, tuple): for j, expected_j in zip(jac, expected): np.allclose(j.detach().numpy(), expected_j) else: assert np.allclose(jac.detach().numpy(), expected) @pytest.mark.tf @pytest.mark.parametrize("relaxations, misclassifications, expected", diff_parameters) def test_differentiation_tensorflow(self, num_wires, relaxations, misclassifications, expected): """Tests the differentiation of readout errors using TensorFlow""" import tensorflow as tf if misclassifications is None: relaxations = tf.Variable(relaxations, dtype="float64") diff_variables = [relaxations] elif relaxations is None: misclassifications = tf.Variable(misclassifications, dtype="float64") diff_variables = [misclassifications] else: relaxations = tf.Variable(relaxations, dtype="float64") misclassifications = tf.Variable(misclassifications, dtype="float64") diff_variables = [relaxations, misclassifications] diff_func = self.get_diff_function("tf", num_wires) with tf.GradientTape() as grad_tape: probs = diff_func(relaxations, misclassifications) jac = grad_tape.jacobian(probs, diff_variables) assert np.allclose(jac, expected)
pennylane/tests/devices/test_default_qutrit_mixed.py/0
{ "file_path": "pennylane/tests/devices/test_default_qutrit_mixed.py", "repo_id": "pennylane", "token_count": 31478 }
78
# Copyright 2018-2024 Xanadu Quantum Technologies Inc. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ This file provides a dummy debugger for device tests. """ import pennylane as qml # pylint: disable=too-few-public-methods class Debugger: """A dummy debugger class""" def __init__(self): # Create a dummy object to act as the device # and add a dummy shots attribute to it self.device = type("", (), {})() self.device.shots = qml.measurements.Shots(None) self.active = True self.snapshots = {}
pennylane/tests/dummy_debugger.py/0
{ "file_path": "pennylane/tests/dummy_debugger.py", "repo_id": "pennylane", "token_count": 327 }
79
# Copyright 2022 Xanadu Quantum Technologies Inc. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Tests for the classical and quantum fisher information matrix in the pennylane.qinfo """ import numpy as np # pylint: disable=no-self-use, import-outside-toplevel, no-member, import-error, too-few-public-methods, bad-continuation import pytest import pennylane as qml import pennylane.numpy as pnp from pennylane.gradients.fisher import _compute_cfim, _make_probs, classical_fisher, quantum_fisher class TestMakeProbs: """Class to test the private function _make_probs.""" def test_make_probs_makes_probs(self): """Testing the correctness of _make_probs.""" dev = qml.device("default.qubit", wires=3) @qml.qnode(dev) def qnode(x): qml.RX(x, 0) qml.CNOT(wires=[0, 1]) return qml.expval(qml.PauliX(0)) x = pnp.array(0.5) new_qnode = _make_probs(qnode) res = new_qnode(x) assert isinstance(res, np.ndarray) assert res.shape == (4,) assert np.isclose(sum(res), 1) @pytest.mark.parametrize("shots", [None, 100]) def test_make_probs(self, shots): """Testing the private _make_probs transform""" with qml.queuing.AnnotatedQueue() as q: qml.PauliX(0) qml.PauliZ(1) qml.PauliY(2) tape = qml.tape.QuantumScript.from_queue(q, shots=shots) new_tape, fn = _make_probs(tape) assert len(new_tape) == 1 assert np.isclose(fn([1]), 1) assert new_tape[0].shots == tape.shots class TestComputeClassicalFisher: """Testing that given p and dp, _compute_cfim() computes the correct outputs""" @pytest.mark.parametrize("n_params", np.arange(1, 10)) @pytest.mark.parametrize("n_wires", np.arange(1, 5)) def test_construction_of_compute_cfim(self, n_params, n_wires): """Test that the construction in _compute_cfim is correct""" dp = np.arange(2**n_wires * n_params, dtype=float).reshape(2**n_wires, n_params) p = np.ones(2**n_wires) res = _compute_cfim(p, dp) assert np.allclose(res, res.T) assert all( res[i, j] == np.sum(dp[:, i] * dp[:, j] / p) for i in range(n_params) for j in range(n_params) ) @pytest.mark.parametrize("n_params", np.arange(1, 10)) @pytest.mark.parametrize("n_wires", np.arange(1, 5)) def test_compute_cfim_trivial_distribution(self, n_params, n_wires): """Test that the classical fisher information matrix (CFIM) is constructed correctly for the trivial distirbution p=(1,0,0,...) and some dummy gradient dp""" # implicitly also does the unit test for the correct output shape dp = np.ones(2**n_wires * n_params, dtype=float).reshape(2**n_wires, n_params) p = np.zeros(2**n_wires) p[0] = 1 res = _compute_cfim(p, dp) assert np.allclose(res, np.ones((n_params, n_params))) class TestIntegration: """Integration test of classical and quantum fisher information matrices""" @pytest.mark.parametrize("n_wires", np.arange(1, 5)) @pytest.mark.parametrize("n_params", np.arange(1, 5)) def test_different_sizes(self, n_wires, n_params): """Testing that for any number of wires and parameters, the correct size and values are computed""" dev = qml.device("default.qubit", wires=n_wires) @qml.qnode(dev) def circ(params): for i in range(n_wires): qml.Hadamard(wires=i) for x in params: for j in range(n_wires): qml.RX(x, wires=j) qml.RY(x, wires=j) qml.RZ(x, wires=j) return qml.probs(wires=range(n_wires)) params = pnp.zeros(n_params, requires_grad=True) res = classical_fisher(circ)(params) assert np.allclose(res, n_wires * np.ones((n_params, n_params))) def test_hardware_compatibility_classical_fisher(self): """Testing that classical_fisher can be computed with finite shots""" n_wires = 3 n_params = 3 dev = qml.device("default.qubit", wires=n_wires, shots=10000) @qml.qnode(dev) def circ(params): for i in range(n_wires): qml.Hadamard(wires=i) for x in params: for j in range(n_wires): qml.RX(x, wires=j) qml.RY(x, wires=j) qml.RZ(x, wires=j) return qml.probs(wires=range(n_wires)) params = pnp.zeros(n_params, requires_grad=True) res = classical_fisher(circ)(params) assert np.allclose(res, n_wires * np.ones((n_params, n_params)), atol=1) @pytest.mark.parametrize( "dev", ( qml.device("default.qubit"), qml.device("default.mixed", wires=3), qml.device("lightning.qubit", wires=3), ), ) def test_quantum_fisher_info(self, dev): """Integration test of quantum fisher information matrix CFIM. This is just calling ``qml.metric_tensor`` or ``qml.adjoint_metric_tensor`` and multiplying by a factor of 4""" n_wires = 2 rng = pnp.random.default_rng(200) dev_hard = qml.device("default.qubit", wires=n_wires + 1, shots=1000, seed=rng) def qfunc(params): qml.RX(params[0], wires=0) qml.RX(params[1], wires=0) qml.CNOT(wires=(0, 1)) return qml.probs(wires=[0, 1]) params = rng.random(2, requires_grad=True) circ_hard = qml.QNode(qfunc, dev_hard) QFIM_hard = quantum_fisher(circ_hard)(params) QFIM1_hard = 4.0 * qml.metric_tensor(circ_hard)(params) circ = qml.QNode(qfunc, dev) QFIM = quantum_fisher(circ)(params) QFIM1 = 4.0 * qml.adjoint_metric_tensor(circ)(params) assert np.allclose(QFIM, QFIM1) assert np.allclose(QFIM_hard, QFIM1_hard, atol=1e-1) class TestInterfacesClassicalFisher: """Integration tests for the classical fisher information matrix CFIM""" @pytest.mark.autograd @pytest.mark.parametrize("n_wires", np.arange(1, 5)) def test_cfim_allnonzero_autograd(self, n_wires): """Integration test of classical_fisher() with autograd for examples where all probabilities are all nonzero""" dev = qml.device("default.qubit", wires=n_wires) @qml.qnode(dev) def circ(params): for i in range(n_wires): qml.RX(params[0], wires=i) for i in range(n_wires): qml.RY(params[1], wires=i) return qml.probs(wires=range(n_wires)) params = np.pi / 4 * pnp.ones(2, requires_grad=True) cfim = classical_fisher(circ)(params) assert np.allclose(cfim, (n_wires / 3.0) * np.ones((2, 2))) @pytest.mark.autograd @pytest.mark.parametrize("n_wires", np.arange(2, 5)) def test_cfim_contains_zeros_autograd(self, n_wires): """Integration test of classical_fisher() with autograd for examples that have 0s in the probabilities and non-zero gradient""" dev = qml.device("default.qubit", wires=n_wires) @qml.qnode(dev) def circ(params): qml.RZ(params[0], wires=0) qml.RX(params[1], wires=1) qml.RX(params[0], wires=1) return qml.probs(wires=range(n_wires)) params = np.pi / 4 * pnp.ones(2, requires_grad=True) cfim = classical_fisher(circ)(params) assert np.allclose(cfim, np.ones((2, 2))) @pytest.mark.jax @pytest.mark.parametrize("n_wires", np.arange(1, 5)) def test_cfim_allnonzero_jax(self, n_wires): """Integration test of classical_fisher() with jax for examples where all probabilities are all nonzero""" import jax.numpy as jnp dev = qml.device("default.qubit", wires=n_wires) @qml.qnode(dev) def circ(params): for i in range(n_wires): qml.RX(params[0], wires=i) for i in range(n_wires): qml.RY(params[1], wires=i) return qml.probs(wires=range(n_wires)) params = np.pi / 4 * jnp.ones(2) cfim = classical_fisher(circ)(params) assert np.allclose(cfim, (n_wires / 3.0) * np.ones((2, 2))) @pytest.mark.jax @pytest.mark.parametrize("n_wires", np.arange(2, 5)) def test_cfim_contains_zeros_jax(self, n_wires): """Integration test of classical_fisher() with jax for examples that have 0s in the probabilities and non-zero gradient""" import jax.numpy as jnp dev = qml.device("default.qubit", wires=n_wires) @qml.qnode(dev) def circ(params): qml.RZ(params[0], wires=0) qml.RX(params[1], wires=1) qml.RX(params[0], wires=1) return qml.probs(wires=range(n_wires)) params = np.pi / 4 * jnp.ones(2) cfim = classical_fisher(circ)(params) assert np.allclose(cfim, np.ones((2, 2))) @pytest.mark.jax def test_cfim_multiple_args_jax(self): """Testing multiple args to be differentiated using jax""" import jax.numpy as jnp n_wires = 3 dev = qml.device("default.qubit", wires=n_wires) @qml.qnode(dev) def circ(x, y, z): for xi in x: qml.RX(xi, wires=0) qml.RX(xi, wires=1) for yi in y: qml.RY(yi, wires=0) qml.RY(yi, wires=1) for zi in z: qml.RZ(zi, wires=0) qml.RZ(zi, wires=1) return qml.probs(wires=range(n_wires)) x = jnp.pi / 8 * jnp.ones(2) y = jnp.pi / 8 * jnp.ones(10) z = jnp.ones(1) cfim = classical_fisher(circ, argnums=(0, 1, 2))(x, y, z) assert qml.math.allclose(cfim[0], 2.0 / 3.0 * np.ones((2, 2))) assert qml.math.allclose(cfim[1], 2.0 / 3.0 * np.ones((10, 10))) assert qml.math.allclose(cfim[2], np.zeros((1, 1))) @pytest.mark.torch @pytest.mark.parametrize("n_wires", np.arange(1, 5)) def test_cfim_allnonzero_torch(self, n_wires): """Integration test of classical_fisher() with torch for examples where all probabilities are all nonzero""" import torch dev = qml.device("default.qubit", wires=n_wires) @qml.qnode(dev) def circ(params): for i in range(n_wires): qml.RX(params[0], wires=i) for i in range(n_wires): qml.RY(params[1], wires=i) return qml.probs(wires=range(n_wires)) params = np.pi / 4 * torch.tensor([1.0, 1.0], requires_grad=True) cfim = classical_fisher(circ)(params) assert np.allclose(cfim.detach().numpy(), (n_wires / 3.0) * np.ones((2, 2))) @pytest.mark.torch @pytest.mark.parametrize("n_wires", np.arange(2, 5)) def test_cfim_contains_zeros_torch(self, n_wires): """Integration test of classical_fisher() with torch for examples that have 0s in the probabilities and non-zero gradient""" import torch dev = qml.device("default.qubit", wires=n_wires) @qml.qnode(dev) def circ(params): qml.RZ(params[0], wires=0) qml.RX(params[1], wires=1) qml.RX(params[0], wires=1) return qml.probs(wires=range(n_wires)) params = np.pi / 4 * torch.tensor([1.0, 1.0], requires_grad=True) cfim = classical_fisher(circ)(params) assert np.allclose(cfim.detach().numpy(), np.ones((2, 2))) @pytest.mark.torch def test_cfim_multiple_args_torch(self): """Testing multiple args to be differentiated using torch""" import torch n_wires = 3 dev = qml.device("default.qubit", wires=n_wires) @qml.qnode(dev) def circ(x, y, z): for xi in x: qml.RX(xi, wires=0) qml.RX(xi, wires=1) for yi in y: qml.RY(yi, wires=0) qml.RY(yi, wires=1) for zi in z: qml.RZ(zi, wires=0) qml.RZ(zi, wires=1) return qml.probs(wires=range(n_wires)) x = np.pi / 8 * torch.ones(2, requires_grad=True) y = np.pi / 8 * torch.ones(10, requires_grad=True) z = torch.ones(1, requires_grad=True) cfim = classical_fisher(circ)(x, y, z) assert np.allclose(cfim[0].detach().numpy(), 2.0 / 3.0 * np.ones((2, 2))) assert np.allclose(cfim[1].detach().numpy(), 2.0 / 3.0 * np.ones((10, 10))) assert np.allclose(cfim[2].detach().numpy(), np.zeros((1, 1))) @pytest.mark.tf @pytest.mark.parametrize("n_wires", np.arange(1, 5)) def test_cfim_allnonzero_tf(self, n_wires): """Integration test of classical_fisher() with tf for examples where all probabilities are all nonzero""" import tensorflow as tf dev = qml.device("default.qubit", wires=n_wires) @qml.qnode(dev) def circ(params): for i in range(n_wires): qml.RX(params[0], wires=i) for i in range(n_wires): qml.RY(params[1], wires=i) return qml.probs(wires=range(n_wires)) params = tf.Variable([np.pi / 4, np.pi / 4]) cfim = classical_fisher(circ)(params) assert np.allclose(cfim, (n_wires / 3.0) * np.ones((2, 2))) @pytest.mark.tf @pytest.mark.parametrize("n_wires", np.arange(2, 5)) def test_cfim_contains_zeros_tf(self, n_wires): """Integration test of classical_fisher() with tf for examples that have 0s in the probabilities and non-zero gradient""" import tensorflow as tf dev = qml.device("default.qubit", wires=n_wires) @qml.qnode(dev) def circ(params): qml.RZ(params[0], wires=0) qml.RX(params[1], wires=1) qml.RX(params[0], wires=1) return qml.probs(wires=range(n_wires)) params = tf.Variable([np.pi / 4, np.pi / 4]) cfim = classical_fisher(circ)(params) assert np.allclose(cfim, np.ones((2, 2))) @pytest.mark.tf def test_cfim_multiple_args_tf(self): """Testing multiple args to be differentiated using tf""" import tensorflow as tf n_wires = 3 dev = qml.device("default.qubit", wires=n_wires) @qml.qnode(dev) def circ(x, y, z): for xi in tf.unstack(x): qml.RX(xi, wires=0) qml.RX(xi, wires=1) for yi in tf.unstack(y): qml.RY(yi, wires=0) qml.RY(yi, wires=1) for zi in tf.unstack(z): qml.RZ(zi, wires=0) qml.RZ(zi, wires=1) return qml.probs(wires=range(n_wires)) x = tf.Variable(np.pi / 8 * np.ones(2), trainable=True) y = tf.Variable(np.pi / 8 * np.ones(10), trainable=True) z = tf.Variable([1.0], trainable=True) cfim = classical_fisher(circ)(x, y, z) assert np.allclose(cfim[0], 2.0 / 3.0 * np.ones((2, 2))) assert np.allclose(cfim[1], 2.0 / 3.0 * np.ones((10, 10))) assert np.allclose(cfim[2], np.zeros((1, 1))) class TestDiffCFIM: """Testing differentiability of classical fisher info matrix (CFIM)""" @pytest.mark.autograd def test_diffability_autograd(self): """Testing diffability with an analytic example for autograd. The CFIM of this single qubit is constant, so the gradient should be zero.""" dev = qml.device("default.qubit", wires=1) @qml.qnode(dev) def circ(params): qml.RY(params, wires=0) return qml.probs(wires=range(1)) params = pnp.array(np.pi / 4, requires_grad=True) assert np.allclose(classical_fisher(circ)(params), 1) result = np.zeros((1, 1, 1), dtype="float64") result_calc = qml.jacobian(classical_fisher(circ))(params) assert np.allclose(result, result_calc, atol=1e-6) @pytest.mark.jax def test_diffability_jax(self): """Testing diffability with an analytic example for jax. The CFIM of this single qubit is constant, so the gradient should be zero.""" import jax import jax.numpy as jnp dev = qml.device("default.qubit", wires=1) @qml.qnode(dev) def circ(params): qml.RY(params, wires=0) return qml.probs(wires=range(1)) # no matter what the input the CFIM here is always constant = 1 # so the derivative should be 0 params = jnp.array(np.pi / 4) assert qml.math.allclose(classical_fisher(circ)(params), 1.0) result = np.zeros((1, 1, 1), dtype="float64") result_calc = jax.jacobian(classical_fisher(circ))(params) assert np.allclose(result, result_calc, atol=1e-6) @pytest.mark.tf def test_diffability_tf(self): """Testing diffability with an analytic example for tf. The CFIM of this single qubit is constant, so the gradient should be zero.""" import tensorflow as tf dev = qml.device("default.qubit", wires=1) @qml.qnode(dev) def circ(params): qml.RY(params, wires=0) return qml.probs(wires=range(1)) params = tf.Variable(np.pi / 4) assert np.allclose(classical_fisher(circ)(params), 1) result = np.zeros((1, 1, 1), dtype="float64") with tf.GradientTape() as tape: loss = classical_fisher(circ)(params) result_calc = tape.jacobian(loss, params) assert np.allclose(result, result_calc, atol=1e-6) @pytest.mark.torch def test_diffability_torch(self): """Testing diffability with an analytic example for torch. The CFIM of this single qubit is constant, so the gradient should be zero.""" import torch dev = qml.device("default.qubit", wires=1) @qml.qnode(dev) def circ(params): qml.RY(params, wires=0) return qml.probs(wires=range(1)) params = torch.tensor(np.pi / 4, requires_grad=True) assert np.allclose(classical_fisher(circ)(params).detach().numpy(), 1) result = np.zeros((1, 1, 1), dtype="float64") result_calc = torch.autograd.functional.jacobian(classical_fisher(circ), params) assert np.allclose(result, result_calc, atol=1e-6) @pytest.mark.all_interfaces def test_consistency(self): """Testing that the derivative of the cfim is giving consistently the same results for all interfaces. Currently failing as (jax and autograd) and (torch and tf) are giving two different results. """ import jax import jax.numpy as jnp import tensorflow as tf import torch dev = qml.device("default.qubit", wires=3) def qfunc(weights): qml.RX(weights[0], wires=0) qml.RX(weights[1], wires=1) qml.RX(weights[2], wires=2) qml.CNOT(wires=[0, 1]) qml.RY(weights[4], wires=0) qml.RY(weights[5], wires=1) qml.RY(weights[6], wires=2) qml.CNOT(wires=[1, 2]) qml.CRX(weights[7], wires=[0, 1]) qml.CRY(weights[8], wires=[1, 2]) qml.CRZ(weights[9], wires=[2, 0]) return qml.expval(qml.PauliZ(0) @ qml.PauliZ(1)) # Compute gradients of CFIM for different interfaces circuit = qml.QNode(qfunc, dev) weights = torch.tensor( [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0], requires_grad=True ) grad_torch = torch.autograd.functional.jacobian(classical_fisher(circuit), weights) circuit = qml.QNode(qfunc, dev) weights = pnp.array([0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0], requires_grad=True) grad_autograd = qml.jacobian(classical_fisher(circuit))(weights) circuit = qml.QNode(qfunc, dev) weights = jnp.array([0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0]) grad_jax = jax.jacobian(classical_fisher(circuit))(weights) circuit = qml.QNode(qfunc, dev) weights = tf.Variable([0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0]) with tf.GradientTape() as tape: loss = classical_fisher(circuit)(weights) grad_tf = tape.jacobian(loss, weights) # Evaluate and compare grads = [grad_autograd, grad_tf, grad_torch, grad_jax] is_same = np.zeros((4, 4)) for i, g1 in enumerate(grads): for j, g2 in enumerate(grads): is_same[i, j] = np.allclose(g1, g2, atol=1e-6) assert np.allclose(is_same, np.ones((4, 4)))
pennylane/tests/gradients/core/test_fisher.py/0
{ "file_path": "pennylane/tests/gradients/core/test_fisher.py", "repo_id": "pennylane", "token_count": 10418 }
80
# Copyright 2018-2021 Xanadu Quantum Technologies Inc. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for the gradients.parameter_shift_cv module.""" # pylint: disable=protected-access, no-self-use, not-callable, no-value-for-parameter from unittest import mock import pytest import pennylane as qml from pennylane import numpy as np from pennylane.gradients import param_shift_cv from pennylane.gradients.gradient_transform import choose_trainable_params from pennylane.gradients.parameter_shift_cv import ( _find_gradient_methods_cv, _grad_method_cv, _transform_observable, ) hbar = 2 class TestGradAnalysis: """Tests for parameter gradient methods""" def test_non_differentiable(self): """Test that a non-differentiable parameter is correctly marked""" with qml.queuing.AnnotatedQueue() as q: qml.FockState(1, wires=0) qml.Displacement(0.543, 0, wires=[1]) qml.Beamsplitter(0, 0, wires=[0, 1]) qml.expval(qml.QuadX(wires=[0])) tape = qml.tape.QuantumScript.from_queue(q) assert _grad_method_cv(tape, 0) is None assert _grad_method_cv(tape, 1) == "A" assert _grad_method_cv(tape, 2) == "A" assert _grad_method_cv(tape, 3) == "A" assert _grad_method_cv(tape, 4) == "A" trainable_params = choose_trainable_params(tape, None) diff_methods = _find_gradient_methods_cv(tape, trainable_params) assert diff_methods[0] is None assert diff_methods[1] == "A" assert diff_methods[2] == "A" assert diff_methods[3] == "A" assert diff_methods[4] == "A" def test_independent(self): """Test that an independent variable is properly marked as having a zero gradient""" with qml.queuing.AnnotatedQueue() as q: qml.Rotation(0.543, wires=[0]) qml.Rotation(-0.654, wires=[1]) qml.expval(qml.QuadP(0)) tape = qml.tape.QuantumScript.from_queue(q) assert _grad_method_cv(tape, 0) == "A" assert _grad_method_cv(tape, 1) == "0" trainable_params = choose_trainable_params(tape, None) diff_methods = _find_gradient_methods_cv(tape, trainable_params) assert diff_methods[0] == "A" assert diff_methods[1] == "0" def test_finite_diff(self, monkeypatch): """If an op has grad_method=F, this should be respected by the qml.tape.QuantumScript""" monkeypatch.setattr(qml.Rotation, "grad_method", "F") with qml.queuing.AnnotatedQueue() as q: qml.Rotation(0.543, wires=[0]) qml.Squeezing(0.543, 0, wires=[0]) qml.expval(qml.QuadP(0)) tape = qml.tape.QuantumScript.from_queue(q) assert _grad_method_cv(tape, 0) == "F" assert _grad_method_cv(tape, 1) == "A" assert _grad_method_cv(tape, 2) == "A" def test_non_gaussian_operation(self): """Test that a non-Gaussian operation succeeding a differentiable Gaussian operation results in numeric differentiation.""" with qml.queuing.AnnotatedQueue() as q: qml.Rotation(1.0, wires=[0]) qml.Rotation(1.0, wires=[1]) # Non-Gaussian qml.Kerr(1.0, wires=[1]) qml.expval(qml.QuadP(0)) qml.expval(qml.QuadX(1)) tape = qml.tape.QuantumScript.from_queue(q) # First rotation gate has no succeeding non-Gaussian operation assert _grad_method_cv(tape, 0) == "A" # Second rotation gate does no succeeding non-Gaussian operation assert _grad_method_cv(tape, 1) == "F" # Kerr gate does not support the parameter-shift rule assert _grad_method_cv(tape, 2) == "F" with qml.queuing.AnnotatedQueue() as q: qml.Rotation(1.0, wires=[0]) qml.Rotation(1.0, wires=[1]) # entangle the modes qml.Beamsplitter(1.0, 0.0, wires=[0, 1]) # Non-Gaussian qml.Kerr(1.0, wires=[1]) qml.expval(qml.QuadP(0)) qml.expval(qml.QuadX(1)) tape = qml.tape.QuantumScript.from_queue(q) # After entangling the modes, the Kerr gate now succeeds # both initial rotations assert _grad_method_cv(tape, 0) == "F" assert _grad_method_cv(tape, 1) == "F" assert _grad_method_cv(tape, 2) == "F" def test_probability(self): """Probability is the expectation value of a higher order observable, and thus only supports numerical differentiation""" with qml.queuing.AnnotatedQueue() as q: qml.Rotation(0.543, wires=[0]) qml.Squeezing(0.543, 0, wires=[0]) qml.probs(wires=0) tape = qml.tape.QuantumScript.from_queue(q) assert _grad_method_cv(tape, 0) == "F" assert _grad_method_cv(tape, 1) == "F" assert _grad_method_cv(tape, 2) == "F" def test_variance(self): """If the variance of the observable is first order, then parameter-shift is supported. If the observable is second order, however, only finite-differences is supported.""" with qml.queuing.AnnotatedQueue() as q: qml.Rotation(1.0, wires=[0]) qml.var(qml.QuadP(0)) # first order tape = qml.tape.QuantumScript.from_queue(q) assert _grad_method_cv(tape, 0) == "A" with qml.queuing.AnnotatedQueue() as q: qml.Rotation(1.0, wires=[0]) qml.var(qml.NumberOperator(0)) # second order tape = qml.tape.QuantumScript.from_queue(q) assert _grad_method_cv(tape, 0) == "F" with qml.queuing.AnnotatedQueue() as q: qml.Rotation(1.0, wires=[0]) qml.Rotation(1.0, wires=[1]) qml.Beamsplitter(0.5, 0.0, wires=[0, 1]) qml.var(qml.NumberOperator(0)) # fourth order qml.expval(qml.NumberOperator(1)) tape = qml.tape.QuantumScript.from_queue(q) assert _grad_method_cv(tape, 0) == "F" assert _grad_method_cv(tape, 1) == "F" assert _grad_method_cv(tape, 2) == "F" assert _grad_method_cv(tape, 3) == "F" def test_second_order_expectation(self): """Test that the expectation of a second-order observable forces the gradient method to use the second-order parameter-shift rule""" with qml.queuing.AnnotatedQueue() as q: qml.Rotation(1.0, wires=[0]) qml.expval(qml.NumberOperator(0)) # second order tape = qml.tape.QuantumScript.from_queue(q) assert _grad_method_cv(tape, 0) == "A2" def test_unknown_op_grad_method(self, monkeypatch): """Test that an exception is raised if an operator has a grad method defined that the CV parameter-shift tape doesn't recognize""" monkeypatch.setattr(qml.Rotation, "grad_method", "B") with qml.queuing.AnnotatedQueue() as q: qml.Rotation(1.0, wires=0) qml.expval(qml.QuadX(0)) tape = qml.tape.QuantumScript.from_queue(q) with pytest.raises(ValueError, match="unknown gradient method"): _grad_method_cv(tape, 0) class TestTransformObservable: """Tests for the _transform_observable method""" def test_incorrect_heisenberg_size(self, monkeypatch): """The number of dimensions of a CV observable Heisenberg representation does not match the ev_order attribute.""" monkeypatch.setattr(qml.QuadP, "ev_order", 2) with pytest.raises(ValueError, match="Mismatch between the polynomial order"): _transform_observable(qml.QuadP(0), np.identity(3), device_wires=[0]) def test_higher_order_observable(self, monkeypatch): """An exception should be raised if the observable is higher than 2nd order.""" monkeypatch.setattr(qml.QuadP, "ev_order", 3) with pytest.raises(NotImplementedError, match="order > 2 not implemented"): _transform_observable(qml.QuadP(0), np.identity(3), device_wires=[0]) def test_first_order_transform(self, tol): """Test that a first order observable is transformed correctly""" # create a symmetric transformation Z = np.arange(3**2).reshape(3, 3) Z = Z.T + Z obs = qml.QuadX(0) res = _transform_observable(obs, Z, device_wires=[0]) # The Heisenberg representation of the X # operator is simply... X expected = np.array([0, 1, 0]) @ Z assert isinstance(res, qml.PolyXP) assert res.wires.labels == (0,) assert np.allclose(res.data[0], expected, atol=tol, rtol=0) def test_second_order_transform(self, tol): """Test that a second order observable is transformed correctly""" # create a symmetric transformation Z = np.arange(3**2).reshape(3, 3) Z = Z.T + Z obs = qml.NumberOperator(0) res = _transform_observable(obs, Z, device_wires=[0]) # The Heisenberg representation of the number operator # is (X^2 + P^2) / (2*hbar) - 1/2 A = np.array([[-0.5, 0, 0], [0, 0.25, 0], [0, 0, 0.25]]) expected = A @ Z + Z @ A assert isinstance(res, qml.PolyXP) assert res.wires.labels == (0,) assert np.allclose(res.data[0], expected, atol=tol, rtol=0) def test_device_wire_expansion(self, tol): """Test that the transformation works correctly for the case where the transformation applies to more wires than the observable.""" # create a 3-mode symmetric transformation wires = qml.wires.Wires([0, "a", 2]) ndim = 1 + 2 * len(wires) Z = np.arange(ndim**2).reshape(ndim, ndim) Z = Z.T + Z obs = qml.NumberOperator(0) res = _transform_observable(obs, Z, device_wires=wires) # The Heisenberg representation of the number operator # is (X^2 + P^2) / (2*hbar) - 1/2. We use the ordering # I, X0, Xa, X2, P0, Pa, P2. A = np.diag([-0.5, 0.25, 0.25, 0, 0, 0, 0]) expected = A @ Z + Z @ A assert isinstance(res, qml.PolyXP) assert res.wires == wires assert np.allclose(res.data[0], expected, atol=tol, rtol=0) class TestParameterShiftLogic: """Test for the dispatching logic of the parameter shift method""" @pytest.mark.autograd def test_no_trainable_params_qnode_autograd(self): """Test that the correct ouput and warning is generated in the absence of any trainable parameters""" dev = qml.device("default.gaussian", wires=2) @qml.qnode(device=dev, interface="autograd") def circuit(weights): qml.Displacement(weights[0], 0.0, wires=[0]) qml.Rotation(weights[1], wires=[0]) return qml.expval(qml.QuadX(0)) weights = [0.1, 0.2] with pytest.raises(qml.QuantumFunctionError, match="No trainable parameters."): qml.gradients.param_shift_cv(circuit)(weights) @pytest.mark.torch def test_no_trainable_params_qnode_torch(self): """Test that the correct ouput and warning is generated in the absence of any trainable parameters""" dev = qml.device("default.gaussian", wires=2) @qml.qnode(dev, interface="torch") def circuit(weights): qml.Displacement(weights[0], 0.0, wires=[0]) qml.Rotation(weights[1], wires=[0]) return qml.expval(qml.QuadX(0)) weights = [0.1, 0.2] with pytest.raises(qml.QuantumFunctionError, match="No trainable parameters."): qml.gradients.param_shift_cv(circuit)(weights) @pytest.mark.tf def test_no_trainable_params_qnode_tf(self): """Test that the correct ouput and warning is generated in the absence of any trainable parameters""" dev = qml.device("default.gaussian", wires=2) @qml.qnode(dev, interface="tf") def circuit(weights): qml.Displacement(weights[0], 0.0, wires=[0]) qml.Rotation(weights[1], wires=[0]) return qml.expval(qml.QuadX(0)) weights = [0.1, 0.2] with pytest.raises(qml.QuantumFunctionError, match="No trainable parameters."): qml.gradients.param_shift_cv(circuit)(weights) @pytest.mark.jax def test_no_trainable_params_qnode_jax(self): """Test that the correct ouput and warning is generated in the absence of any trainable parameters""" dev = qml.device("default.gaussian", wires=2) @qml.qnode(device=dev, interface="jax") def circuit(weights): qml.Displacement(weights[0], 0.0, wires=[0]) qml.Rotation(weights[1], wires=[0]) return qml.expval(qml.QuadX(0)) weights = [0.1, 0.2] with pytest.raises(qml.QuantumFunctionError, match="No trainable parameters."): qml.gradients.param_shift_cv(circuit)(weights) def test_no_trainable_params_tape(self): """Test that the correct ouput and warning is generated in the absence of any trainable parameters""" dev = qml.device("default.gaussian", wires=2) weights = [0.1, 0.2] with qml.queuing.AnnotatedQueue() as q: qml.Displacement(weights[0], 0.0, wires=[0]) qml.Rotation(weights[1], wires=[0]) qml.expval(qml.QuadX(0)) tape = qml.tape.QuantumScript.from_queue(q) # TODO: remove once #2155 is resolved tape.trainable_params = [] with pytest.warns(UserWarning, match="gradient of a tape with no trainable parameters"): g_tapes, post_processing = qml.gradients.param_shift_cv(tape, dev) res = post_processing(qml.execute(g_tapes, dev, None)) assert g_tapes == [] assert res.shape == (0,) def test_all_zero_diff_methods(self): """Test that the transform works correctly when the diff method for every parameter is identified to be 0, and that no tapes were generated.""" dev = qml.device("default.gaussian", wires=2) @qml.qnode(dev) def circuit(params): qml.Rotation(params[0], wires=0) return qml.expval(qml.QuadX(1)) params = np.array([0.5, 0.5, 0.5], requires_grad=True) result = qml.gradients.param_shift_cv(circuit, dev)(params) assert np.allclose(result, np.zeros((2, 3)), atol=0, rtol=0) def test_state_non_differentiable_error(self): """Test error raised if attempting to differentiate with respect to a state""" with qml.queuing.AnnotatedQueue() as q: qml.state() tape = qml.tape.QuantumScript.from_queue(q) with pytest.raises(ValueError, match=r"return the state is not supported"): qml.gradients.param_shift_cv(tape, None) def test_force_order2(self, mocker): """Test that if the force_order2 keyword argument is provided, the second order parameter shift rule is forced""" spy = mocker.spy(qml.gradients.parameter_shift_cv, "second_order_param_shift") dev = qml.device("default.gaussian", wires=1) with qml.queuing.AnnotatedQueue() as q: qml.Displacement(1.0, 0.0, wires=[0]) qml.Rotation(2.0, wires=[0]) qml.expval(qml.QuadX(0)) tape = qml.tape.QuantumScript.from_queue(q) tape.trainable_params = {0, 1, 2} qml.gradients.param_shift_cv(tape, dev, force_order2=False) spy.assert_not_called() qml.gradients.param_shift_cv(tape, dev, force_order2=True) spy.assert_called() def test_force_order2_dim_2(self, mocker, monkeypatch): """Test that if the force_order2 keyword argument is provided, the second order parameter shift rule is forced for an observable with 2-dimensional parameters""" spy = mocker.spy(qml.gradients.parameter_shift_cv, "second_order_param_shift") def _mock_transform_observable(obs, Z, device_wires): # pylint: disable=unused-argument """A mock version of the _transform_observable internal function such that an operator ``transformed_obs`` of two-dimensions is returned. This function is created such that when definining ``A = transformed_obs.parameters[0]`` the condition ``len(A.nonzero()[0]) == 1 and A.ndim == 2 and A[0, 0] != 0`` is ``True``.""" iden = qml.Identity(0) iden.data = (np.array([[1, 0], [0, 0]]),) return iden monkeypatch.setattr( qml.gradients.parameter_shift_cv, "_transform_observable", _mock_transform_observable, ) dev = qml.device("default.gaussian", wires=1) with qml.queuing.AnnotatedQueue() as q: qml.Displacement(1.0, 0.0, wires=[0]) qml.Rotation(2.0, wires=[0]) qml.expval(qml.QuadX(0)) tape = qml.tape.QuantumScript.from_queue(q) tape.trainable_params = {0, 1, 2} qml.gradients.param_shift_cv(tape, dev, force_order2=False) spy.assert_not_called() qml.gradients.param_shift_cv(tape, dev, force_order2=True) spy.assert_called() def test_no_poly_xp_support(self, mocker, monkeypatch): """Test that if a device does not support PolyXP and the second-order parameter-shift rule is required, we fallback to finite differences.""" spy_second_order = mocker.spy(qml.gradients.parameter_shift_cv, "second_order_param_shift") dev = qml.device("default.gaussian", wires=1) monkeypatch.delitem(dev._observable_map, "PolyXP") with qml.queuing.AnnotatedQueue() as q: qml.Rotation(1.0, wires=[0]) qml.expval(qml.NumberOperator(0)) tape = qml.tape.QuantumScript.from_queue(q) tape.trainable_params = {0} with pytest.warns(UserWarning, match="does not support the PolyXP observable"): qml.gradients.param_shift_cv(tape, dev) spy_second_order.assert_not_called() def test_no_poly_xp_support_variance(self, mocker, monkeypatch): """Test that if a device does not support PolyXP and the variance parameter-shift rule is required, we fallback to finite differences.""" spy = mocker.spy(qml.gradients.parameter_shift_cv, "var_param_shift") dev = qml.device("default.gaussian", wires=1) monkeypatch.delitem(dev._observable_map, "PolyXP") with qml.queuing.AnnotatedQueue() as q: qml.Rotation(1.0, wires=[0]) qml.var(qml.QuadX(0)) tape = qml.tape.QuantumScript.from_queue(q) tape.trainable_params = {0} with pytest.warns(UserWarning, match="does not support the PolyXP observable"): qml.gradients.param_shift_cv(tape, dev) spy.assert_not_called() def test_independent_parameters_analytic(self): """Test the case where expectation values are independent of some parameters. For those parameters, the gradient should be evaluated to zero without executing the device.""" dev = qml.device("default.gaussian", wires=2) with qml.queuing.AnnotatedQueue() as q: qml.Displacement(1.0, 0.0, wires=[1]) qml.Displacement(1.0, 0.0, wires=[0]) qml.expval(qml.QuadX(0)) tape = qml.tape.QuantumScript.from_queue(q) tape.trainable_params = {0, 2} tapes, fn = qml.gradients.param_shift_cv(tape, dev) # We should only be executing the device to differentiate 1 parameter # (first order, so 2 executions) assert len(tapes) == 2 res = fn(dev.batch_execute(tapes)) assert np.allclose(res, [0, 2]) tape.trainable_params = {0, 2} tapes, fn = qml.gradients.param_shift_cv(tape, dev, force_order2=True) # We should only be executing the device to differentiate 1 parameter # (second order, so 0 executions) assert len(tapes) == 0 res = fn(dev.batch_execute(tapes)) assert np.allclose(res, [0, 2]) def test_all_independent(self): """Test the case where expectation values are independent of all parameters.""" dev = qml.device("default.gaussian", wires=2) with qml.queuing.AnnotatedQueue() as q: qml.Displacement(1, 0, wires=[1]) qml.Displacement(1, 0, wires=[1]) qml.expval(qml.QuadX(0)) tape = qml.tape.QuantumScript.from_queue(q) tape.trainable_params = {0, 2} tapes, fn = qml.gradients.param_shift_cv(tape, dev) assert len(tapes) == 0 grad = fn(dev.batch_execute(tapes)) assert np.allclose(grad, [0, 0]) class TestExpectationQuantumGradients: """Tests for the quantum gradients of various gates with expectation value output""" @pytest.mark.parametrize( "gradient_recipes", [None, ([[1 / np.sqrt(2), 1, np.pi / 4], [-1 / np.sqrt(2), 1, -np.pi / 4]],)], ) def test_rotation_gradient(self, gradient_recipes, mocker, tol): """Test the gradient of the rotation gate""" dev = qml.device("default.gaussian", wires=2, hbar=hbar) alpha = 0.5643 theta = 0.23354 with qml.queuing.AnnotatedQueue() as q: qml.Displacement(alpha, 0.0, wires=[0]) qml.Rotation(theta, wires=[0]) qml.expval(qml.QuadX(0)) tape = qml.tape.QuantumScript.from_queue(q) tape.trainable_params = {2} spy2 = mocker.spy(qml.gradients.parameter_shift_cv, "second_order_param_shift") tapes, fn = param_shift_cv(tape, dev, gradient_recipes=gradient_recipes) grad_A = fn(dev.batch_execute(tapes)) spy2.assert_not_called() tapes, fn = param_shift_cv(tape, dev, gradient_recipes=gradient_recipes, force_order2=True) grad_A2 = fn(dev.batch_execute(tapes)) spy2.assert_called() expected = -hbar * alpha * np.sin(theta) assert np.allclose(grad_A, expected, atol=tol, rtol=0) assert np.allclose(grad_A2, expected, atol=tol, rtol=0) def test_beamsplitter_gradient(self, mocker, tol): """Test the gradient of the beamsplitter gate""" dev = qml.device("default.gaussian", wires=2, hbar=hbar) alpha = 0.5643 theta = 0.23354 with qml.queuing.AnnotatedQueue() as q: qml.Displacement(alpha, 0.0, wires=[0]) qml.Beamsplitter(theta, 0.0, wires=[0, 1]) qml.expval(qml.QuadX(0)) tape = qml.tape.QuantumScript.from_queue(q) tape.trainable_params = {2} spy2 = mocker.spy(qml.gradients.parameter_shift_cv, "second_order_param_shift") tapes, fn = param_shift_cv(tape, dev) grad_A = fn(dev.batch_execute(tapes)) spy2.assert_not_called() tapes, fn = param_shift_cv(tape, dev, force_order2=True) grad_A2 = fn(dev.batch_execute(tapes)) spy2.assert_called() expected = -hbar * alpha * np.sin(theta) assert np.allclose(grad_A, expected, atol=tol, rtol=0) assert np.allclose(grad_A2, expected, atol=tol, rtol=0) def test_displacement_gradient(self, mocker, tol): """Test the gradient of the displacement gate""" dev = qml.device("default.gaussian", wires=2, hbar=hbar) r = 0.5643 phi = 0.23354 with qml.queuing.AnnotatedQueue() as q: qml.Displacement(r, phi, wires=[0]) qml.expval(qml.QuadX(0)) tape = qml.tape.QuantumScript.from_queue(q) tape.trainable_params = {0, 1} spy2 = mocker.spy(qml.gradients.parameter_shift_cv, "second_order_param_shift") tapes, fn = param_shift_cv(tape, dev) grad_A = fn(dev.batch_execute(tapes)) spy2.assert_not_called() tapes, fn = param_shift_cv(tape, dev, force_order2=True) grad_A2 = fn(dev.batch_execute(tapes)) spy2.assert_called() expected = [hbar * np.cos(phi), -hbar * r * np.sin(phi)] assert np.allclose(grad_A, expected, atol=tol, rtol=0) assert np.allclose(grad_A2, expected, atol=tol, rtol=0) def test_squeezed_gradient(self, mocker, tol): """Test the gradient of the squeezed gate. We also ensure that the gradient is correct even when an operation with no Heisenberg representation is a descendent.""" dev = qml.device("default.gaussian", wires=2, hbar=hbar) # pylint: disable=too-few-public-methods class Rotation(qml.operation.CVOperation): """Dummy operation that does not support heisenberg representation""" num_wires = 1 par_domain = "R" grad_method = "A" alpha = 0.5643 r = 0.23354 with qml.queuing.AnnotatedQueue() as q: qml.Displacement(alpha, 0.0, wires=[0]) qml.Squeezing(r, 0.0, wires=[0]) # The following two gates have no effect # on the circuit gradient and expectation value qml.Beamsplitter(0.0, 0.0, wires=[0, 1]) Rotation(0.543, wires=[1]) qml.expval(qml.QuadX(0)) tape = qml.tape.QuantumScript.from_queue(q) tape.trainable_params = {2} spy2 = mocker.spy(qml.gradients.parameter_shift_cv, "second_order_param_shift") tapes, fn = param_shift_cv(tape, dev) grad_A = fn(dev.batch_execute(tapes)) spy2.assert_not_called() tapes, fn = param_shift_cv(tape, dev, force_order2=True) grad_A2 = fn(dev.batch_execute(tapes)) spy2.assert_called() expected = -np.exp(-r) * hbar * alpha assert np.allclose(grad_A, expected, atol=tol, rtol=0) assert np.allclose(grad_A2, expected, atol=tol, rtol=0) def test_squeezed_number_state_gradient(self, mocker, tol): """Test the numerical gradient of the squeeze gate with with number state expectation is correct""" dev = qml.device("default.gaussian", wires=2, hbar=hbar) r = 0.23354 with qml.queuing.AnnotatedQueue() as q: qml.Squeezing(r, 0.0, wires=[0]) # the fock state projector is a 'non-Gaussian' observable qml.expval(qml.FockStateProjector(np.array([2, 0]), wires=[0, 1])) tape = qml.tape.QuantumScript.from_queue(q) tape.trainable_params = {0} spy = mocker.spy(qml.gradients.parameter_shift_cv, "second_order_param_shift") spy2 = mocker.spy(qml.gradients.parameter_shift_cv, "_find_gradient_methods_cv") tapes, fn = param_shift_cv(tape, dev) grad = fn(dev.batch_execute(tapes)) spy.assert_not_called() assert spy2.spy_return == {0: "F"} # (d/dr) |<2|S(r)>|^2 = 0.5 tanh(r)^3 (2 csch(r)^2 - 1) sech(r) expected = 0.5 * np.tanh(r) ** 3 * (2 / (np.sinh(r) ** 2) - 1) / np.cosh(r) assert np.allclose(grad, expected, atol=tol, rtol=0) def test_multiple_squeezing_gradient(self, mocker, tol): """Test that the gradient of a circuit with two squeeze gates is correct.""" dev = qml.device("default.gaussian", wires=2, hbar=hbar) r0, phi0, r1, phi1 = [0.4, -0.3, -0.7, 0.2] with qml.queuing.AnnotatedQueue() as q: qml.Squeezing(r0, phi0, wires=[0]) qml.Squeezing(r1, phi1, wires=[0]) qml.expval(qml.NumberOperator(0)) # second order tape = qml.tape.QuantumScript.from_queue(q) spy2 = mocker.spy(qml.gradients.parameter_shift_cv, "second_order_param_shift") tapes, fn = param_shift_cv(tape, dev, force_order2=True) grad_A2 = fn(dev.batch_execute(tapes)) spy2.assert_called() # check against the known analytic formula expected = np.zeros([4]) expected[0] = np.cosh(2 * r1) * np.sinh(2 * r0) + np.cos(phi0 - phi1) * np.cosh( 2 * r0 ) * np.sinh(2 * r1) expected[1] = -0.5 * np.sin(phi0 - phi1) * np.sinh(2 * r0) * np.sinh(2 * r1) expected[2] = np.cos(phi0 - phi1) * np.cosh(2 * r1) * np.sinh(2 * r0) + np.cosh( 2 * r0 ) * np.sinh(2 * r1) expected[3] = 0.5 * np.sin(phi0 - phi1) * np.sinh(2 * r0) * np.sinh(2 * r1) assert np.allclose(grad_A2, expected, atol=tol, rtol=0) def test_multiple_second_order_observables(self): """Test that the gradient of a circuit with multiple second order observables is correct""" dev = qml.device("default.gaussian", wires=2, hbar=hbar) r = [0.4, -0.7, 0.1, 0.2] p = [0.1, 0.2, 0.3, 0.4] with qml.queuing.AnnotatedQueue() as q: qml.Squeezing(r[0], p[0], wires=[0]) qml.Squeezing(r[1], p[1], wires=[0]) qml.Squeezing(r[2], p[2], wires=[1]) qml.Squeezing(r[3], p[3], wires=[1]) qml.expval(qml.NumberOperator(0)) # second order qml.expval(qml.NumberOperator(1)) # second order tape = qml.tape.QuantumScript.from_queue(q) with pytest.raises( ValueError, match="Computing the gradient of CV circuits that return more" ): param_shift_cv(tape, dev) @pytest.mark.parametrize("obs", [qml.QuadP, qml.Identity]) @pytest.mark.parametrize( "op", [qml.Displacement(0.1, 0.2, wires=0), qml.TwoModeSqueezing(0.1, 0.2, wires=[0, 1])] ) def test_gradients_gaussian_circuit(self, mocker, op, obs, tol): """Tests that the gradients of circuits of gaussian gates match between the finite difference and analytic methods.""" tol = 1e-2 with qml.queuing.AnnotatedQueue() as q: qml.Displacement(0.5, 0, wires=0) qml.apply(op) qml.Beamsplitter(1.3, -2.3, wires=[0, 1]) qml.Displacement(-0.5, 0.1, wires=0) qml.Squeezing(0.5, -1.5, wires=0) qml.Rotation(-1.1, wires=0) qml.expval(obs(wires=0)) tape = qml.tape.QuantumScript.from_queue(q) dev = qml.device("default.gaussian", wires=2) tape.trainable_params = set(range(2, 2 + op.num_params)) spy = mocker.spy(qml.gradients.parameter_shift_cv, "_find_gradient_methods_cv") tapes, fn = qml.gradients.finite_diff(tape) grad_F = fn(dev.batch_execute(tapes)) tapes, fn = param_shift_cv(tape, dev, force_order2=True) grad_A2 = fn(dev.batch_execute(tapes)) for method in spy.spy_return.values(): assert method == "A" assert np.allclose(grad_A2, grad_F, atol=tol, rtol=0) if obs.ev_order == 1: tapes, fn = param_shift_cv(tape, dev) grad_A = fn(dev.batch_execute(tapes)) assert np.allclose(grad_A, grad_F, atol=tol, rtol=0) @pytest.mark.parametrize("t", [0, 1]) def test_interferometer_unitary(self, mocker, t, tol): """An integration test for CV gates that support analytic differentiation if succeeding the gate to be differentiated, but cannot be differentiated themselves (for example, they may be Gaussian but accept no parameters, or may accept a numerical array parameter.). This ensures that, assuming their _heisenberg_rep is defined, the quantum gradient analytic method can still be used, and returns the correct result. Currently, the only such operation is qml.InterferometerUnitary. In the future, we may consider adding a qml.GaussianTransfom operator. """ if t == 1: pytest.xfail( "There is a bug in the second order CV parameter-shift rule; " "phase arguments return the incorrect derivative." ) # Note: this bug currently affects PL core as well: # # dev = qml.device("default.gaussian", wires=2) # # U = np.array([[ 0.51310276+0.81702166j, 0.13649626+0.22487759j], # [ 0.26300233+0.00556194j, -0.96414101-0.03508489j]]) # # @qml.qnode(dev) # def circuit(r, phi): # qml.Displacement(r, phi, wires=0) # qml.InterferometerUnitary(U, wires=[0, 1]) # return qml.expval(qml.QuadX(0)) # # r = 0.543 # phi = 0. # # >>> print(circuit.jacobian([r, phi], options={"force_order2":False})) # [[ 1.02620552 0.14823494]] # >>> print(circuit.jacobian([r, phi], options={"force_order2":True})) # [[ 1.02620552 -0.88728552]] U = np.array( [ [0.51310276 + 0.81702166j, 0.13649626 + 0.22487759j], [0.26300233 + 0.00556194j, -0.96414101 - 0.03508489j], ], requires_grad=False, ) with qml.queuing.AnnotatedQueue() as q: qml.Displacement(0.543, 0, wires=0) qml.InterferometerUnitary(U, wires=[0, 1]) qml.expval(qml.QuadX(0)) tape = qml.tape.QuantumScript.from_queue(q) tape.trainable_params = {t} dev = qml.device("default.gaussian", wires=2) spy = mocker.spy(qml.gradients.parameter_shift_cv, "_find_gradient_methods_cv") tapes, fn = qml.gradients.finite_diff(tape) grad_F = fn(dev.batch_execute(tapes)) tapes, fn = param_shift_cv(tape, dev) grad_A = fn(dev.batch_execute(tapes)) tapes, fn = param_shift_cv(tape, dev, force_order2=True) grad_A2 = fn(dev.batch_execute(tapes)) assert spy.spy_return[0] == "A" # the different methods agree assert np.allclose(grad_A, grad_F, atol=tol, rtol=0) assert np.allclose(grad_A2, grad_F, atol=tol, rtol=0) class TestVarianceQuantumGradients: """Tests for the quantum gradients of various gates with variance measurements""" def test_first_order_observable(self, tol): """Test variance of a first order CV observable""" dev = qml.device("default.gaussian", wires=1) r = 0.543 phi = -0.654 with qml.queuing.AnnotatedQueue() as q: qml.Squeezing(r, 0, wires=0) qml.Rotation(phi, wires=0) qml.var(qml.QuadX(0)) tape = qml.tape.QuantumScript.from_queue(q) tape.trainable_params = {0, 2} res = qml.execute([tape], dev, None) expected = np.exp(2 * r) * np.sin(phi) ** 2 + np.exp(-2 * r) * np.cos(phi) ** 2 assert np.allclose(res, expected, atol=tol, rtol=0) # circuit jacobians tapes, fn = qml.gradients.finite_diff(tape) grad_F = fn(dev.batch_execute(tapes)) tapes, fn = param_shift_cv(tape, dev) grad_A = fn(dev.batch_execute(tapes)) expected = np.array( [ [ 2 * np.exp(2 * r) * np.sin(phi) ** 2 - 2 * np.exp(-2 * r) * np.cos(phi) ** 2, 2 * np.sinh(2 * r) * np.sin(2 * phi), ] ] ) assert np.allclose(grad_A, expected, atol=tol, rtol=0) assert np.allclose(grad_F, expected, atol=tol, rtol=0) def test_second_order_cv(self, tol): """Test variance of a second order CV expectation value""" dev = qml.device("default.gaussian", wires=1) n = 0.12 a = 0.765 with qml.queuing.AnnotatedQueue() as q: qml.ThermalState(n, wires=0) qml.Displacement(a, 0, wires=0) qml.var(qml.NumberOperator(0)) tape = qml.tape.QuantumScript.from_queue(q) tape.trainable_params = {0, 1} res = qml.execute([tape], dev, None) expected = n**2 + n + np.abs(a) ** 2 * (1 + 2 * n) assert np.allclose(res, expected, atol=tol, rtol=0) # circuit jacobians tapes, fn = qml.gradients.finite_diff(tape) grad_F = fn(dev.batch_execute(tapes)) expected = np.array([[2 * a**2 + 2 * n + 1, 2 * a * (2 * n + 1)]]) assert np.allclose(grad_F, expected, atol=tol, rtol=0) def test_expval_and_variance(self): """Test that the gradient works for a combination of CV expectation values and variances""" dev = qml.device("default.gaussian", wires=3) a, b = [0.54, -0.423] with qml.queuing.AnnotatedQueue() as q: qml.Displacement(0.5, 0, wires=0) qml.Squeezing(a, 0, wires=0) qml.Squeezing(b, 0, wires=1) qml.Beamsplitter(0.6, -0.3, wires=[0, 1]) qml.Squeezing(-0.3, 0, wires=2) qml.Beamsplitter(1.4, 0.5, wires=[1, 2]) qml.var(qml.QuadX(0)) qml.expval(qml.QuadX(1)) qml.var(qml.QuadX(2)) tape = qml.tape.QuantumScript.from_queue(q) tape.trainable_params = {2, 4} with pytest.raises( ValueError, match="Computing the gradient of CV circuits that return more" ): param_shift_cv(tape, dev) def test_error_analytic_second_order(self): """Test exception raised if attempting to use a second order observable to compute the variance derivative analytically""" dev = qml.device("default.gaussian", wires=1) with qml.queuing.AnnotatedQueue() as q: qml.Displacement(1.0, 0, wires=0) qml.var(qml.NumberOperator(0)) tape = qml.tape.QuantumScript.from_queue(q) tape.trainable_params = {0} with pytest.raises(ValueError, match=r"cannot be used with the parameter\(s\) \[0\]"): param_shift_cv(tape, dev, fallback_fn=None) @mock.patch("pennylane.gradients.parameter_shift_cv._grad_method_cv", return_value="A") def test_error_unsupported_grad_recipe(self, _): """Test exception raised if attempting to use the second order rule for computing the gradient analytically of an expectation value that contains an operation with more than two terms in the gradient recipe""" # pylint: disable=too-few-public-methods class DummyOp(qml.operation.CVOperation): """Dummy op""" num_wires = 1 par_domain = "R" grad_method = "A" grad_recipe = ([[1, 1, 1], [1, 1, 1], [1, 1, 1]],) dev = qml.device("default.gaussian", wires=1) dev.operations.add(DummyOp) with qml.queuing.AnnotatedQueue() as q: DummyOp(1, wires=[0]) qml.expval(qml.QuadX(0)) tape = qml.tape.QuantumScript.from_queue(q) with pytest.raises( NotImplementedError, match=r"analytic gradient for order-2 operators is unsupported" ): param_shift_cv(tape, dev, force_order2=True) @pytest.mark.parametrize("obs", [qml.QuadX, qml.NumberOperator]) @pytest.mark.parametrize( "op", [qml.Squeezing(0.1, 0.2, wires=0), qml.Beamsplitter(0.1, 0.2, wires=[0, 1])] ) def test_gradients_gaussian_circuit(self, mocker, op, obs, tol): """Tests that the gradients of circuits of selected gaussian gates match between the finite difference and analytic methods.""" tol = 1e-2 with qml.queuing.AnnotatedQueue() as q: qml.Displacement(0.5, 0, wires=0) qml.apply(op) qml.Beamsplitter(1.3, -2.3, wires=[0, 1]) qml.Displacement(-0.5, 0.1, wires=0) qml.Squeezing(0.5, -1.5, wires=0) qml.Rotation(-1.1, wires=0) qml.var(obs(wires=0)) tape = qml.tape.QuantumScript.from_queue(q) dev = qml.device("default.gaussian", wires=2) tape.trainable_params = set(range(2, 2 + op.num_params)) spy = mocker.spy(qml.gradients.parameter_shift_cv, "_find_gradient_methods_cv") # jacobians must match tapes, fn = qml.gradients.finite_diff(tape) grad_F = fn(dev.batch_execute(tapes)) tapes, fn = param_shift_cv(tape, dev) grad_A = fn(dev.batch_execute(tapes)) tapes, fn = param_shift_cv(tape, dev, force_order2=True) grad_A2 = fn(dev.batch_execute(tapes)) assert np.allclose(grad_A2, grad_F, atol=tol, rtol=0) assert np.allclose(grad_A, grad_F, atol=tol, rtol=0) if obs != qml.NumberOperator: assert all(m == "A" for m in spy.spy_return.values()) def test_squeezed_mean_photon_variance(self, tol): """Test gradient of the photon variance of a displaced thermal state""" dev = qml.device("default.gaussian", wires=1) r = 0.12 phi = 0.105 with qml.queuing.AnnotatedQueue() as q: qml.Squeezing(r, 0, wires=0) qml.Rotation(phi, wires=0) qml.var(qml.QuadX(wires=[0])) tape = qml.tape.QuantumScript.from_queue(q) tape.trainable_params = {0, 2} tapes, fn = param_shift_cv(tape, dev) grad = fn(dev.batch_execute(tapes)) expected = np.array( [ 2 * np.exp(2 * r) * np.sin(phi) ** 2 - 2 * np.exp(-2 * r) * np.cos(phi) ** 2, 2 * np.sinh(2 * r) * np.sin(2 * phi), ] ) assert np.allclose(grad, expected, atol=tol, rtol=0) def test_displaced_thermal_mean_photon_variance(self, tol): """Test gradient of the photon variance of a displaced thermal state""" dev = qml.device("default.gaussian", wires=1) n = 0.12 a = 0.105 with qml.queuing.AnnotatedQueue() as q: qml.ThermalState(n, wires=0) qml.Displacement(a, 0, wires=0) qml.var(qml.TensorN(wires=[0])) tape = qml.tape.QuantumScript.from_queue(q) tape.trainable_params = {0, 1} tapes, fn = param_shift_cv(tape, dev) grad = fn(dev.batch_execute(tapes)) expected = np.array([2 * a**2 + 2 * n + 1, 2 * a * (2 * n + 1)]) assert np.allclose(grad, expected, atol=tol, rtol=0) class TestParamShiftInterfaces: """Test that the transform is differentiable""" @pytest.mark.autograd def test_autograd_gradient(self, tol): """Tests that the output of the parameter-shift CV transform can be differentiated using autograd.""" dev = qml.device("default.gaussian", wires=1) r = 0.12 phi = 0.105 @qml.qnode(device=dev, interface="autograd", max_diff=2) def cost_fn(x): qml.Squeezing(x[0], 0, wires=0) qml.Rotation(x[1], wires=0) return qml.var(qml.QuadX(wires=[0])) params = np.array([r, phi], requires_grad=True) grad = qml.jacobian(cost_fn)(params) expected = np.array( [ 2 * np.exp(2 * r) * np.sin(phi) ** 2 - 2 * np.exp(-2 * r) * np.cos(phi) ** 2, 2 * np.sinh(2 * r) * np.sin(2 * phi), ] ) assert np.allclose(grad, expected, atol=tol, rtol=0) @pytest.mark.tf def test_tf(self, tol): """Tests that the output of the parameter-shift CV transform can be executed using TF""" import tensorflow as tf dev = qml.device("default.gaussian", wires=1) params = tf.Variable([0.543, -0.654], dtype=tf.float64) with tf.GradientTape() as t: with qml.queuing.AnnotatedQueue() as q: qml.Squeezing(params[0], 0, wires=0) qml.Rotation(params[1], wires=0) qml.var(qml.QuadX(wires=[0])) tape = qml.tape.QuantumScript.from_queue(q) tape.trainable_params = {0, 2} tapes, fn = param_shift_cv(tape, dev) jac = fn( qml.execute( tapes, dev, param_shift_cv, gradient_kwargs={"dev": dev}, interface="tf" ) ) res = jac[1] r, phi = 1.0 * params expected = np.array( [ 2 * np.exp(2 * r) * np.sin(phi) ** 2 - 2 * np.exp(-2 * r) * np.cos(phi) ** 2, 2 * np.sinh(2 * r) * np.sin(2 * phi), ] ) assert np.allclose(jac, expected, atol=tol, rtol=0) grad = t.jacobian(res, params) expected = np.array( [4 * np.cosh(2 * r) * np.sin(2 * phi), 4 * np.cos(2 * phi) * np.sinh(2 * r)] ) assert np.allclose(grad, expected, atol=tol, rtol=0) @pytest.mark.torch def test_torch(self, tol): """Tests that the output of the parameter-shift CV transform can be executed using Torch.""" import torch dev = qml.device("default.gaussian", wires=1) params = torch.tensor([0.543, -0.654], dtype=torch.float64, requires_grad=True) with qml.queuing.AnnotatedQueue() as q: qml.Squeezing(params[0], 0, wires=0) qml.Rotation(params[1], wires=0) qml.var(qml.QuadX(wires=[0])) tape = qml.tape.QuantumScript.from_queue(q) tape.trainable_params = {0, 2} tapes, fn = qml.gradients.param_shift_cv(tape, dev) jac = fn( qml.execute(tapes, dev, param_shift_cv, gradient_kwargs={"dev": dev}, interface="torch") ) r, phi = params.detach().numpy() expected = np.array( [ 2 * np.exp(2 * r) * np.sin(phi) ** 2 - 2 * np.exp(-2 * r) * np.cos(phi) ** 2, 2 * np.sinh(2 * r) * np.sin(2 * phi), ] ) assert np.allclose(jac[0].detach().numpy(), expected[0], atol=tol, rtol=0) assert np.allclose(jac[1].detach().numpy(), expected[1], atol=tol, rtol=0) cost = jac[1] cost.backward() hess = params.grad expected = np.array( [4 * np.cosh(2 * r) * np.sin(2 * phi), 4 * np.cos(2 * phi) * np.sinh(2 * r)] ) assert np.allclose(hess.detach().numpy(), expected, atol=0.1, rtol=0) @pytest.mark.jax def test_jax(self, tol): """Tests that the output of the parameter-shift CV transform can be differentiated using JAX, yielding second derivatives.""" import jax from jax import numpy as jnp dev = qml.device("default.gaussian", wires=1) params = jnp.array([0.543, -0.654]) def cost_fn(x): with qml.queuing.AnnotatedQueue() as q: qml.Squeezing(x[0], 0, wires=0) qml.Rotation(x[1], wires=0) qml.var(qml.QuadX(wires=[0])) tape = qml.tape.QuantumScript.from_queue(q) tape.trainable_params = {0, 2} tapes, fn = qml.gradients.param_shift_cv(tape, dev) jac = fn( qml.execute( tapes, dev, param_shift_cv, gradient_kwargs={"dev": dev}, interface="jax" ) ) return jac r, phi = params res = cost_fn(params) expected = np.array( [ 2 * np.exp(2 * r) * np.sin(phi) ** 2 - 2 * np.exp(-2 * r) * np.cos(phi) ** 2, 2 * np.sinh(2 * r) * np.sin(2 * phi), ] ) assert np.allclose(res, expected, atol=tol, rtol=0) res = jax.jacobian(cost_fn)(params) expected = np.array( [4 * np.cosh(2 * r) * np.sin(2 * phi), 4 * np.cos(2 * phi) * np.sinh(2 * r)] ) assert np.allclose(res[1], expected, atol=tol, rtol=0)
pennylane/tests/gradients/parameter_shift/test_parameter_shift_cv.py/0
{ "file_path": "pennylane/tests/gradients/parameter_shift/test_parameter_shift_cv.py", "repo_id": "pennylane", "token_count": 23010 }
81
# Copyright 2018-2020 Xanadu Quantum Technologies Inc. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Integration tests for using the TensorFlow interface with a QNode""" import numpy as np import pytest import pennylane as qml from pennylane import qnode # pylint: disable=too-many-arguments,too-few-public-methods, use-dict-literal, use-implicit-booleaness-not-comparison pytestmark = pytest.mark.tf tf = pytest.importorskip("tensorflow") qubit_device_and_diff_method = [ ["default.qubit.legacy", "finite-diff", False], ["default.qubit.legacy", "parameter-shift", False], ["default.qubit.legacy", "backprop", True], ["default.qubit.legacy", "adjoint", True], ["default.qubit.legacy", "adjoint", False], ["default.qubit.legacy", "spsa", False], ["default.qubit.legacy", "hadamard", False], ] TOL_FOR_SPSA = 1.0 SEED_FOR_SPSA = 32651 H_FOR_SPSA = 0.01 interface_and_qubit_device_and_diff_method = [ ["auto"] + inner_list for inner_list in qubit_device_and_diff_method ] + [["tf"] + inner_list for inner_list in qubit_device_and_diff_method] @pytest.mark.parametrize( "interface,dev_name,diff_method,grad_on_execution", interface_and_qubit_device_and_diff_method ) class TestQNode: """Test that using the QNode with TensorFlow integrates with the PennyLane stack""" def test_execution_with_interface(self, dev_name, diff_method, grad_on_execution, interface): """Test execution works with the interface""" if diff_method == "backprop": pytest.skip("Test does not support backprop") num_wires = 1 if diff_method == "hadamard": num_wires = 2 dev = qml.device(dev_name, wires=num_wires) @qnode( dev, interface=interface, diff_method=diff_method, grad_on_execution=grad_on_execution ) def circuit(a): qml.RY(a, wires=0) qml.RX(0.2, wires=0) return qml.expval(qml.PauliZ(0)) a = tf.Variable(0.1) circuit(a) # if executing outside a gradient tape, the number of trainable parameters # cannot be determined by TensorFlow assert circuit.qtape.trainable_params == [] with tf.GradientTape() as tape: res = circuit(a) assert circuit.interface == interface # with the interface, the tape returns tensorflow tensors assert isinstance(res, tf.Tensor) assert res.shape == tuple() # the tape is able to deduce trainable parameters assert circuit.qtape.trainable_params == [0] # gradients should work grad = tape.gradient(res, a) assert isinstance(grad, tf.Tensor) assert grad.shape == tuple() def test_interface_swap(self, dev_name, diff_method, grad_on_execution, tol, interface): """Test that the TF interface can be applied to a QNode with a pre-existing interface""" if diff_method == "backprop": pytest.skip("Test does not support backprop") num_wires = 1 if diff_method == "hadamard": num_wires = 2 dev = qml.device(dev_name, wires=num_wires) @qnode( dev, interface="autograd", diff_method=diff_method, grad_on_execution=grad_on_execution ) def circuit(a): qml.RY(a, wires=0) qml.RX(0.2, wires=0) return qml.expval(qml.PauliZ(0)) from pennylane import numpy as anp a = anp.array(0.1, requires_grad=True) res1 = circuit(a) grad_fn = qml.grad(circuit) grad1 = grad_fn(a) # switch to TF interface circuit.interface = interface a = tf.Variable(0.1, dtype=tf.float64) with tf.GradientTape() as tape: res2 = circuit(a) grad2 = tape.gradient(res2, a) assert np.allclose(res1, res2, atol=tol, rtol=0) assert np.allclose(grad1, grad2, atol=tol, rtol=0) def test_drawing(self, dev_name, diff_method, grad_on_execution, interface): """Test circuit drawing when using the TF interface""" x = tf.Variable(0.1, dtype=tf.float64) y = tf.Variable([0.2, 0.3], dtype=tf.float64) z = tf.Variable(0.4, dtype=tf.float64) num_wires = 2 if diff_method == "hadamard": num_wires = 3 dev = qml.device(dev_name, wires=num_wires) @qnode( dev, interface=interface, diff_method=diff_method, grad_on_execution=grad_on_execution ) def circuit(p1, p2=y, **kwargs): qml.RX(p1, wires=0) qml.RY(p2[0] * p2[1], wires=1) qml.RX(kwargs["p3"], wires=0) qml.CNOT(wires=[0, 1]) return qml.expval(qml.PauliZ(0)), qml.expval(qml.PauliZ(1)) result = qml.draw(circuit)(p1=x, p3=z) expected = "0: ──RX(0.10)──RX(0.40)─╭●─┤ <Z>\n1: ──RY(0.06)───────────╰X─┤ <Z>" assert result == expected def test_jacobian(self, dev_name, diff_method, grad_on_execution, tol, interface): """Test jacobian calculation""" kwargs = dict( diff_method=diff_method, grad_on_execution=grad_on_execution, interface=interface ) if diff_method == "spsa": kwargs["sampler_rng"] = np.random.default_rng(SEED_FOR_SPSA) tol = TOL_FOR_SPSA num_wires = 2 if diff_method == "hadamard": num_wires = 3 dev = qml.device(dev_name, wires=num_wires) a = tf.Variable(0.1, dtype=tf.float64) b = tf.Variable(0.2, dtype=tf.float64) @qnode(dev, **kwargs) def circuit(a, b): qml.RY(a, wires=0) qml.RX(b, wires=1) qml.CNOT(wires=[0, 1]) return qml.expval(qml.PauliZ(0)), qml.expval(qml.PauliY(1)) with tf.GradientTape() as tape: res = circuit(a, b) res = tf.stack(res) assert circuit.qtape.trainable_params == [0, 1] assert isinstance(res, tf.Tensor) assert res.shape == (2,) expected = [tf.cos(a), -tf.cos(a) * tf.sin(b)] assert np.allclose(res, expected, atol=tol, rtol=0) res = tape.jacobian(res, [a, b]) expected = [[-tf.sin(a), tf.sin(a) * tf.sin(b)], [0, -tf.cos(a) * tf.cos(b)]] assert np.allclose(res, expected, atol=tol, rtol=0) def test_jacobian_dtype(self, dev_name, diff_method, grad_on_execution, interface): """Test calculating the jacobian with a different datatype""" if diff_method == "backprop": pytest.skip("Test does not support backprop") a = tf.Variable(0.1, dtype=tf.float32) b = tf.Variable(0.2, dtype=tf.float32) num_wires = 2 if diff_method == "hadamard": num_wires = 3 dev = qml.device(dev_name, wires=num_wires, r_dtype=np.float32) @qnode( dev, diff_method=diff_method, grad_on_execution=grad_on_execution, interface=interface ) def circuit(a, b): qml.RY(a, wires=0) qml.RX(b, wires=1) qml.CNOT(wires=[0, 1]) return [qml.expval(qml.PauliZ(0)), qml.expval(qml.PauliY(1))] with tf.GradientTape() as tape: res = circuit(a, b) res = tf.stack(res) assert circuit.qtape.trainable_params == [0, 1] assert isinstance(res, tf.Tensor) assert res.shape == (2,) assert res.dtype is tf.float32 res = tape.jacobian(res, [a, b]) assert [r.dtype is tf.float32 for r in res] def test_jacobian_options(self, dev_name, diff_method, grad_on_execution, interface): """Test setting finite-difference jacobian options""" if diff_method not in {"finite-diff", "spsa"}: pytest.skip("Test only works with finite diff and spsa.") a = tf.Variable([0.1, 0.2]) num_wires = 1 if diff_method == "hadamard": num_wires = 2 dev = qml.device(dev_name, wires=num_wires) @qnode( dev, interface=interface, h=1e-8, approx_order=2, diff_method=diff_method, grad_on_execution=grad_on_execution, ) def circuit(a): qml.RY(a[0], wires=0) qml.RX(a[1], wires=0) return qml.expval(qml.PauliZ(0)) with tf.GradientTape() as tape: res = circuit(a) tape.jacobian(res, a) def test_changing_trainability(self, dev_name, diff_method, grad_on_execution, tol, interface): """Test changing the trainability of parameters changes the number of differentiation requests made""" if diff_method in ["backprop", "adjoint", "spsa"]: pytest.skip("Test does not support backprop, adjoint or spsa method") a = tf.Variable(0.1, dtype=tf.float64) b = tf.Variable(0.2, dtype=tf.float64) num_wires = 2 diff_kwargs = {} if diff_method == "hadamard": num_wires = 3 elif diff_method == "finite-diff": diff_kwargs = {"approx_order": 2, "strategy": "center"} dev = qml.device(dev_name, wires=num_wires) @qnode( dev, interface=interface, diff_method=diff_method, grad_on_execution=grad_on_execution, **diff_kwargs, ) def circuit(a, b): qml.RY(a, wires=0) qml.RX(b, wires=1) qml.CNOT(wires=[0, 1]) return qml.expval(qml.PauliZ(0)), qml.expval(qml.PauliY(1)) with tf.GradientTape() as tape: res = circuit(a, b) res = tf.stack(res) # the tape has reported both gate arguments as trainable assert circuit.qtape.trainable_params == [0, 1] expected = [tf.cos(a), -tf.cos(a) * tf.sin(b)] assert np.allclose(res, expected, atol=tol, rtol=0) jac = tape.jacobian(res, [a, b]) expected = [ [-tf.sin(a), tf.sin(a) * tf.sin(b)], [0, -tf.cos(a) * tf.cos(b)], ] assert np.allclose(jac, expected, atol=tol, rtol=0) # make the second QNode argument a constant a = tf.Variable(0.54, dtype=tf.float64) b = tf.constant(0.8, dtype=tf.float64) with tf.GradientTape() as tape: res = circuit(a, b) res = tf.stack(res) # the tape has reported only the first argument as trainable assert circuit.qtape.trainable_params == [0] expected = [tf.cos(a), -tf.cos(a) * tf.sin(b)] assert np.allclose(res, expected, atol=tol, rtol=0) jac = tape.jacobian(res, a) expected = [-tf.sin(a), tf.sin(a) * tf.sin(b)] assert np.allclose(jac, expected, atol=tol, rtol=0) def test_classical_processing(self, dev_name, diff_method, grad_on_execution, interface): """Test classical processing within the quantum tape""" a = tf.Variable(0.1, dtype=tf.float64) b = tf.constant(0.2, dtype=tf.float64) c = tf.Variable(0.3, dtype=tf.float64) num_wires = 1 if diff_method == "hadamard": num_wires = 2 dev = qml.device(dev_name, wires=num_wires) @qnode( dev, diff_method=diff_method, grad_on_execution=grad_on_execution, interface=interface ) def circuit(x, y, z): qml.RY(x * z, wires=0) qml.RZ(y, wires=0) qml.RX(z + z**2 + tf.sin(a), wires=0) return qml.expval(qml.PauliZ(0)) with tf.GradientTape() as tape: res = circuit(a, b, c) if diff_method == "finite-diff": assert circuit.qtape.trainable_params == [0, 2] assert circuit.qtape.get_parameters() == [a * c, c + c**2 + tf.sin(a)] res = tape.jacobian(res, [a, b, c]) assert isinstance(res[0], tf.Tensor) assert res[1] is None assert isinstance(res[2], tf.Tensor) def test_no_trainable_parameters(self, dev_name, diff_method, grad_on_execution, interface): """Test evaluation if there are no trainable parameters""" num_wires = 2 if diff_method == "hadamard": num_wires = 3 dev = qml.device(dev_name, wires=num_wires) @qnode( dev, diff_method=diff_method, grad_on_execution=grad_on_execution, interface=interface ) def circuit(a, b): qml.RY(a, wires=0) qml.RX(b, wires=0) qml.CNOT(wires=[0, 1]) return qml.expval(qml.PauliZ(0)), qml.expval(qml.PauliZ(1)) a = 0.1 b = tf.constant(0.2, dtype=tf.float64) with tf.GradientTape() as tape: res = circuit(a, b) res = tf.stack(res) if diff_method == "finite-diff": assert circuit.qtape.trainable_params == [] assert res.shape == (2,) assert isinstance(res, tf.Tensor) # can't take the gradient with respect to "a" since it's a Python scalar grad = tape.jacobian(res, b) assert grad is None @pytest.mark.parametrize("U", [tf.constant([[0, 1], [1, 0]]), np.array([[0, 1], [1, 0]])]) def test_matrix_parameter(self, dev_name, diff_method, grad_on_execution, U, tol, interface): """Test that the TF interface works correctly with a matrix parameter""" a = tf.Variable(0.1, dtype=tf.float64) num_wires = 2 if diff_method == "hadamard": num_wires = 3 dev = qml.device(dev_name, wires=num_wires) @qnode( dev, diff_method=diff_method, grad_on_execution=grad_on_execution, interface=interface ) def circuit(U, a): qml.QubitUnitary(U, wires=0) qml.RY(a, wires=0) return qml.expval(qml.PauliZ(0)) with tf.GradientTape() as tape: res = circuit(U, a) if diff_method == "finite-diff": assert circuit.qtape.trainable_params == [1] assert np.allclose(res, -tf.cos(a), atol=tol, rtol=0) res = tape.jacobian(res, a) assert np.allclose(res, tf.sin(a), atol=tol, rtol=0) def test_differentiable_expand(self, dev_name, diff_method, grad_on_execution, tol, interface): """Test that operation and nested tapes expansion is differentiable""" kwargs = dict( diff_method=diff_method, grad_on_execution=grad_on_execution, interface=interface ) if diff_method == "spsa": spsa_kwargs = dict(sampler_rng=np.random.default_rng(SEED_FOR_SPSA), num_directions=10) kwargs = {**kwargs, **spsa_kwargs} tol = TOL_FOR_SPSA class U3(qml.U3): def decomposition(self): theta, phi, lam = self.data wires = self.wires return [ qml.Rot(lam, theta, -lam, wires=wires), qml.PhaseShift(phi + lam, wires=wires), ] num_wires = 1 if diff_method == "hadamard": num_wires = 2 dev = qml.device(dev_name, wires=num_wires) a = np.array(0.1) p = tf.Variable([0.1, 0.2, 0.3], dtype=tf.float64) @qnode(dev, **kwargs) def circuit(a, p): qml.RX(a, wires=0) U3(p[0], p[1], p[2], wires=0) return qml.expval(qml.PauliX(0)) with tf.GradientTape() as tape: res = circuit(a, p) expected = tf.cos(a) * tf.cos(p[1]) * tf.sin(p[0]) + tf.sin(a) * ( tf.cos(p[2]) * tf.sin(p[1]) + tf.cos(p[0]) * tf.cos(p[1]) * tf.sin(p[2]) ) assert np.allclose(res, expected, atol=tol, rtol=0) res = tape.jacobian(res, p) expected = np.array( [ tf.cos(p[1]) * (tf.cos(a) * tf.cos(p[0]) - tf.sin(a) * tf.sin(p[0]) * tf.sin(p[2])), tf.cos(p[1]) * tf.cos(p[2]) * tf.sin(a) - tf.sin(p[1]) * (tf.cos(a) * tf.sin(p[0]) + tf.cos(p[0]) * tf.sin(a) * tf.sin(p[2])), tf.sin(a) * (tf.cos(p[0]) * tf.cos(p[1]) * tf.cos(p[2]) - tf.sin(p[1]) * tf.sin(p[2])), ] ) assert np.allclose(res, expected, atol=tol, rtol=0) @pytest.mark.parametrize("interface", ["auto", "tf"]) class TestShotsIntegration: """Test that the QNode correctly changes shot value, and differentiates it.""" def test_changing_shots(self, mocker, tol, interface): """Test that changing shots works on execution""" dev = qml.device("default.qubit.legacy", wires=2, shots=None) a, b = [0.543, -0.654] weights = tf.Variable([a, b], dtype=tf.float64) @qnode(dev, interface=interface, diff_method=qml.gradients.param_shift) def circuit(weights): qml.RY(weights[0], wires=0) qml.RX(weights[1], wires=1) qml.CNOT(wires=[0, 1]) return qml.expval(qml.PauliY(1)) spy = mocker.spy(dev.target_device, "sample") # execute with device default shots (None) res = circuit(weights) assert np.allclose(res, -np.cos(a) * np.sin(b), atol=tol, rtol=0) spy.assert_not_called() # execute with shots=100 circuit(weights, shots=100) # pylint: disable=unexpected-keyword-arg spy.assert_called_once() assert spy.spy_return.shape == (100,) # device state has been unaffected assert not dev.shots res = circuit(weights) assert np.allclose(res, -np.cos(a) * np.sin(b), atol=tol, rtol=0) spy.assert_called_once() def test_gradient_integration(self, interface): """Test that temporarily setting the shots works for gradient computations""" # pylint: disable=unexpected-keyword-arg dev = qml.device("default.qubit.legacy", wires=2, shots=None) a, b = [0.543, -0.654] weights = tf.Variable([a, b], dtype=tf.float64) @qnode(dev, interface=interface, diff_method=qml.gradients.param_shift) def circuit(weights): qml.RY(weights[0], wires=0) qml.RX(weights[1], wires=1) qml.CNOT(wires=[0, 1]) return qml.expval(qml.PauliY(1)) with tf.GradientTape() as tape: res = circuit(weights, shots=[10000, 10000, 10000]) res = tf.transpose(tf.stack(res)) assert not dev.shots assert len(res) == 3 jacobian = tape.jacobian(res, weights) expected = [np.sin(a) * np.sin(b), -np.cos(a) * np.cos(b)] assert np.allclose(np.mean(jacobian, axis=0), expected, atol=0.1, rtol=0) def test_multiple_gradient_integration(self, tol, interface): """Test that temporarily setting the shots works for gradient computations, even if the QNode has been re-evaluated with a different number of shots in the meantime.""" dev = qml.device("default.qubit.legacy", wires=2, shots=None) a, b = [0.543, -0.654] weights = tf.Variable([a, b], dtype=tf.float64) @qnode(dev, interface=interface, diff_method=qml.gradients.param_shift) def circuit(weights): qml.RY(weights[0], wires=0) qml.RX(weights[1], wires=1) qml.CNOT(wires=[0, 1]) return qml.expval(qml.PauliY(1)) with tf.GradientTape() as tape: res1 = circuit(weights) assert qml.math.shape(res1) == tuple() res2 = circuit(weights, shots=[(1, 1000)]) # pylint: disable=unexpected-keyword-arg assert qml.math.shape(res2) == (1000,) grad = tape.gradient(res1, weights) expected = [np.sin(a) * np.sin(b), -np.cos(a) * np.cos(b)] assert np.allclose(grad, expected, atol=tol, rtol=0) def test_update_diff_method(self, mocker, interface): """Test that temporarily setting the shots updates the diff method""" dev = qml.device("default.qubit.legacy", wires=2, shots=100) weights = tf.Variable([0.543, -0.654], dtype=tf.float64) spy = mocker.spy(qml, "execute") @qnode(dev, interface=interface) def circuit(weights): qml.RY(weights[0], wires=0) qml.RX(weights[1], wires=1) qml.CNOT(wires=[0, 1]) return qml.expval(qml.PauliY(1)) # since we are using finite shots, parameter-shift will # be chosen circuit(weights) assert circuit.gradient_fn is qml.gradients.param_shift circuit(weights) assert spy.call_args[1]["gradient_fn"] is qml.gradients.param_shift assert circuit.gradient_fn is qml.gradients.param_shift # if we set the shots to None, backprop can now be used circuit(weights, shots=None) # pylint: disable=unexpected-keyword-arg assert spy.call_args[1]["gradient_fn"] == "backprop" assert circuit.gradient_fn == "backprop" circuit(weights) assert circuit.gradient_fn is qml.gradients.param_shift assert spy.call_args[1]["gradient_fn"] is qml.gradients.param_shift @pytest.mark.parametrize("interface", ["auto", "tf"]) class TestAdjoint: """Specific integration tests for the adjoint method""" def test_reuse_state(self, mocker, interface): """Tests that the TF interface reuses the device state for adjoint differentiation""" dev = qml.device("default.qubit.legacy", wires=2) @qnode(dev, diff_method="adjoint", interface=interface) def circ(x): qml.RX(x[0], wires=0) qml.RY(x[1], wires=1) qml.CNOT(wires=(0, 1)) return qml.expval(qml.PauliZ(0)), qml.expval(qml.PauliX(1)) spy = mocker.spy(dev.target_device, "adjoint_jacobian") weights = tf.Variable([0.1, 0.2], dtype=tf.float64) x, y = 1.0 * weights with tf.GradientTape() as tape: res = tf.reduce_sum(circ(weights)) grad = tape.gradient(res, weights) expected_grad = [-tf.sin(x), tf.cos(y)] assert np.allclose(grad, expected_grad) assert circ.device.num_executions == 1 spy.assert_called_with(mocker.ANY, use_device_state=mocker.ANY) def test_reuse_state_multiple_evals(self, mocker, tol, interface): """Tests that the TF interface reuses the device state for adjoint differentiation, even where there are intermediate evaluations.""" dev = qml.device("default.qubit.legacy", wires=2) x_val = 0.543 y_val = -0.654 x = tf.Variable(x_val, dtype=tf.float64) y = tf.Variable(y_val, dtype=tf.float64) @qnode(dev, diff_method="adjoint", interface=interface) def circuit(x, y): qml.RX(x, wires=[0]) qml.RY(y, wires=[1]) qml.CNOT(wires=[0, 1]) return qml.expval(qml.PauliZ(0)) spy = mocker.spy(dev.target_device, "adjoint_jacobian") with tf.GradientTape() as tape: res1 = circuit(x, y) assert np.allclose(res1, np.cos(x_val), atol=tol, rtol=0) # intermediate evaluation with different values circuit(tf.math.tan(x), tf.math.cosh(y)) # the adjoint method will continue to compute the correct derivative grad = tape.gradient(res1, x) assert np.allclose(grad, -np.sin(x_val), atol=tol, rtol=0) assert dev.num_executions == 2 spy.assert_called_with(mocker.ANY, use_device_state=mocker.ANY) @pytest.mark.parametrize( "interface,dev_name,diff_method,grad_on_execution", interface_and_qubit_device_and_diff_method ) class TestQubitIntegration: """Tests that ensure various qubit circuits integrate correctly""" def test_probability_differentiation( self, dev_name, diff_method, grad_on_execution, tol, interface ): """Tests correct output shape and evaluation for a tape with multiple probs outputs""" kwargs = dict( diff_method=diff_method, grad_on_execution=grad_on_execution, interface=interface ) if diff_method == "adjoint": pytest.skip("The adjoint method does not currently support returning probabilities") elif diff_method == "spsa": kwargs["sampler_rng"] = np.random.default_rng(SEED_FOR_SPSA) tol = TOL_FOR_SPSA num_wires = 2 if diff_method == "hadamard": num_wires = 3 dev = qml.device(dev_name, wires=num_wires) x = tf.Variable(0.543, dtype=tf.float64) y = tf.Variable(-0.654, dtype=tf.float64) @qnode(dev, **kwargs) def circuit(x, y): qml.RX(x, wires=[0]) qml.RY(y, wires=[1]) qml.CNOT(wires=[0, 1]) return qml.probs(wires=[0]), qml.probs(wires=[1]) with tf.GradientTape() as tape: res = circuit(x, y) res = tf.stack(res) expected = np.array( [ [tf.cos(x / 2) ** 2, tf.sin(x / 2) ** 2], [(1 + tf.cos(x) * tf.cos(y)) / 2, (1 - tf.cos(x) * tf.cos(y)) / 2], ] ) assert np.allclose(res, expected, atol=tol, rtol=0) res = tape.jacobian(res, [x, y]) expected = np.array( [ [ [-tf.sin(x) / 2, tf.sin(x) / 2], [-tf.sin(x) * tf.cos(y) / 2, tf.cos(y) * tf.sin(x) / 2], ], [ [0, 0], [-tf.cos(x) * tf.sin(y) / 2, tf.cos(x) * tf.sin(y) / 2], ], ] ) assert np.allclose(res, expected, atol=tol, rtol=0) def test_ragged_differentiation(self, dev_name, diff_method, grad_on_execution, tol, interface): """Tests correct output shape and evaluation for a tape with prob and expval outputs""" kwargs = dict( diff_method=diff_method, grad_on_execution=grad_on_execution, interface=interface ) if diff_method == "adjoint": pytest.skip("The adjoint method does not currently support returning probabilities") elif diff_method == "spsa": kwargs["sampler_rng"] = np.random.default_rng(SEED_FOR_SPSA) tol = TOL_FOR_SPSA num_wires = 2 if diff_method == "hadamard": num_wires = 3 dev = qml.device(dev_name, wires=num_wires) x = tf.Variable(0.543, dtype=tf.float64) y = tf.Variable(-0.654, dtype=tf.float64) @qnode(dev, **kwargs) def circuit(x, y): qml.RX(x, wires=[0]) qml.RY(y, wires=[1]) qml.CNOT(wires=[0, 1]) return qml.expval(qml.PauliZ(0)), qml.probs(wires=[1]) with tf.GradientTape() as tape: res = circuit(x, y) res = tf.experimental.numpy.hstack(res) expected = np.array( [ tf.cos(x), (1 + tf.cos(x) * tf.cos(y)) / 2, (1 - tf.cos(x) * tf.cos(y)) / 2, ] ) assert np.allclose(res, expected, atol=tol, rtol=0) res = tape.jacobian(res, [x, y]) expected = np.array( [ [-tf.sin(x), -tf.sin(x) * tf.cos(y) / 2, tf.cos(y) * tf.sin(x) / 2], [0, -tf.cos(x) * tf.sin(y) / 2, tf.cos(x) * tf.sin(y) / 2], ] ) assert np.allclose(res, expected, atol=tol, rtol=0) def test_second_derivative(self, dev_name, diff_method, grad_on_execution, tol, interface): """Test second derivative calculation of a scalar valued QNode""" if diff_method not in {"parameter-shift", "backprop", "hadamard"}: pytest.skip("Test only supports parameter-shift or backprop") num_wires = 1 if diff_method == "hadamard": num_wires = 3 dev = qml.device(dev_name, wires=num_wires) @qnode( dev, diff_method=diff_method, grad_on_execution=grad_on_execution, max_diff=2, interface=interface, ) def circuit(x): qml.RY(x[0], wires=0) qml.RX(x[1], wires=0) return qml.expval(qml.PauliZ(0)) x = tf.Variable([1.0, 2.0], dtype=tf.float64) with tf.GradientTape() as tape1: with tf.GradientTape() as tape2: res = circuit(x) g = tape2.gradient(res, x) res2 = tf.reduce_sum(g) g2 = tape1.gradient(res2, x) a, b = x * 1.0 expected_res = tf.cos(a) * tf.cos(b) assert np.allclose(res, expected_res, atol=tol, rtol=0) expected_g = [-tf.sin(a) * tf.cos(b), -tf.cos(a) * tf.sin(b)] assert np.allclose(g, expected_g, atol=tol, rtol=0) expected_g2 = [ -tf.cos(a) * tf.cos(b) + tf.sin(a) * tf.sin(b), tf.sin(a) * tf.sin(b) - tf.cos(a) * tf.cos(b), ] assert np.allclose(g2, expected_g2, atol=tol, rtol=0) def test_hessian(self, dev_name, diff_method, grad_on_execution, tol, interface): """Test hessian calculation of a scalar valued QNode""" if diff_method not in {"parameter-shift", "backprop", "hadamard"}: pytest.skip("Test only supports parameter-shift or backprop") num_wires = 1 if diff_method == "hadamard": num_wires = 3 dev = qml.device(dev_name, wires=num_wires) @qnode( dev, diff_method=diff_method, grad_on_execution=grad_on_execution, max_diff=2, interface=interface, ) def circuit(x): qml.RY(x[0], wires=0) qml.RX(x[1], wires=0) return qml.expval(qml.PauliZ(0)) x = tf.Variable([1.0, 2.0], dtype=tf.float64) with tf.GradientTape() as tape1: with tf.GradientTape() as tape2: res = circuit(x) g = tape2.gradient(res, x) hess = tape1.jacobian(g, x) a, b = x * 1.0 expected_res = tf.cos(a) * tf.cos(b) assert np.allclose(res, expected_res, atol=tol, rtol=0) expected_g = [-tf.sin(a) * tf.cos(b), -tf.cos(a) * tf.sin(b)] assert np.allclose(g, expected_g, atol=tol, rtol=0) expected_hess = [ [-tf.cos(a) * tf.cos(b), tf.sin(a) * tf.sin(b)], [tf.sin(a) * tf.sin(b), -tf.cos(a) * tf.cos(b)], ] assert np.allclose(hess, expected_hess, atol=tol, rtol=0) def test_hessian_vector_valued(self, dev_name, diff_method, grad_on_execution, tol, interface): """Test hessian calculation of a vector valued QNode""" if diff_method not in {"parameter-shift", "backprop", "hadamard"}: pytest.skip("Test only supports parameter-shift or backprop") num_wires = 1 if diff_method == "hadamard": num_wires = 3 dev = qml.device(dev_name, wires=num_wires) @qnode( dev, diff_method=diff_method, grad_on_execution=grad_on_execution, max_diff=2, interface=interface, ) def circuit(x): qml.RY(x[0], wires=0) qml.RX(x[1], wires=0) return qml.probs(wires=0) x = tf.Variable([1.0, 2.0], dtype=tf.float64) with tf.GradientTape() as tape1: with tf.GradientTape(persistent=True) as tape2: res = circuit(x) g = tape2.jacobian(res, x, experimental_use_pfor=False) hess = tape1.jacobian(g, x) a, b = x * 1.0 expected_res = [ 0.5 + 0.5 * tf.cos(a) * tf.cos(b), 0.5 - 0.5 * tf.cos(a) * tf.cos(b), ] assert np.allclose(res, expected_res, atol=tol, rtol=0) expected_g = [ [-0.5 * tf.sin(a) * tf.cos(b), -0.5 * tf.cos(a) * tf.sin(b)], [0.5 * tf.sin(a) * tf.cos(b), 0.5 * tf.cos(a) * tf.sin(b)], ] assert np.allclose(g, expected_g, atol=tol, rtol=0) expected_hess = [ [ [-0.5 * tf.cos(a) * tf.cos(b), 0.5 * tf.sin(a) * tf.sin(b)], [0.5 * tf.sin(a) * tf.sin(b), -0.5 * tf.cos(a) * tf.cos(b)], ], [ [0.5 * tf.cos(a) * tf.cos(b), -0.5 * tf.sin(a) * tf.sin(b)], [-0.5 * tf.sin(a) * tf.sin(b), 0.5 * tf.cos(a) * tf.cos(b)], ], ] np.testing.assert_allclose(hess, expected_hess, atol=tol, rtol=0, verbose=True) def test_hessian_vector_valued_postprocessing( self, dev_name, diff_method, grad_on_execution, tol, interface ): """Test hessian calculation of a vector valued QNode with post-processing""" if diff_method not in {"parameter-shift", "backprop", "hadamard"}: pytest.skip("Test only supports parameter-shift or backprop") num_wires = 1 if diff_method == "hadamard": num_wires = 3 dev = qml.device(dev_name, wires=num_wires) @qnode( dev, diff_method=diff_method, grad_on_execution=grad_on_execution, max_diff=2, interface=interface, ) def circuit(x): qml.RX(x[0], wires=0) qml.RY(x[1], wires=0) return [qml.expval(qml.PauliZ(0)), qml.expval(qml.PauliZ(0))] x = tf.Variable([0.76, -0.87], dtype=tf.float64) with tf.GradientTape() as tape1: with tf.GradientTape(persistent=True) as tape2: res = tf.tensordot(x, circuit(x), axes=[0, 0]) g = tape2.jacobian(res, x, experimental_use_pfor=False) hess = tape1.jacobian(g, x) a, b = x * 1.0 expected_res = a * tf.cos(a) * tf.cos(b) + b * tf.cos(a) * tf.cos(b) assert np.allclose(res, expected_res, atol=tol, rtol=0) expected_g = [ tf.cos(b) * (tf.cos(a) - (a + b) * tf.sin(a)), tf.cos(a) * (tf.cos(b) - (a + b) * tf.sin(b)), ] assert np.allclose(g, expected_g, atol=tol, rtol=0) expected_hess = [ [ -(tf.cos(b) * ((a + b) * tf.cos(a) + 2 * tf.sin(a))), -(tf.cos(b) * tf.sin(a)) + (-tf.cos(a) + (a + b) * tf.sin(a)) * tf.sin(b), ], [ -(tf.cos(b) * tf.sin(a)) + (-tf.cos(a) + (a + b) * tf.sin(a)) * tf.sin(b), -(tf.cos(a) * ((a + b) * tf.cos(b) + 2 * tf.sin(b))), ], ] assert np.allclose(hess, expected_hess, atol=tol, rtol=0) def test_hessian_ragged(self, dev_name, diff_method, grad_on_execution, tol, interface): """Test hessian calculation of a ragged QNode""" if diff_method not in {"parameter-shift", "backprop", "hadamard"}: pytest.skip("Test only supports parameter-shift or backprop") num_wires = 2 if diff_method == "hadamard": num_wires = 4 dev = qml.device(dev_name, wires=num_wires) @qnode( dev, diff_method=diff_method, grad_on_execution=grad_on_execution, max_diff=2, interface=interface, ) def circuit(x): qml.RY(x[0], wires=0) qml.RX(x[1], wires=0) qml.RY(x[0], wires=1) qml.RX(x[1], wires=1) return qml.expval(qml.PauliZ(0)), qml.probs(wires=1) x = tf.Variable([1.0, 2.0], dtype=tf.float64) res = circuit(x) with tf.GradientTape() as tape1: with tf.GradientTape(persistent=True) as tape2: res = circuit(x) res = tf.experimental.numpy.hstack(res) g = tape2.jacobian(res, x, experimental_use_pfor=False) hess = tape1.jacobian(g, x) a, b = x * 1.0 expected_res = [ tf.cos(a) * tf.cos(b), 0.5 + 0.5 * tf.cos(a) * tf.cos(b), 0.5 - 0.5 * tf.cos(a) * tf.cos(b), ] assert np.allclose(res, expected_res, atol=tol, rtol=0) expected_g = [ [-tf.sin(a) * tf.cos(b), -tf.cos(a) * tf.sin(b)], [-0.5 * tf.sin(a) * tf.cos(b), -0.5 * tf.cos(a) * tf.sin(b)], [0.5 * tf.sin(a) * tf.cos(b), 0.5 * tf.cos(a) * tf.sin(b)], ] assert np.allclose(g, expected_g, atol=tol, rtol=0) expected_hess = [ [ [-tf.cos(a) * tf.cos(b), tf.sin(a) * tf.sin(b)], [tf.sin(a) * tf.sin(b), -tf.cos(a) * tf.cos(b)], ], [ [-0.5 * tf.cos(a) * tf.cos(b), 0.5 * tf.sin(a) * tf.sin(b)], [0.5 * tf.sin(a) * tf.sin(b), -0.5 * tf.cos(a) * tf.cos(b)], ], [ [0.5 * tf.cos(a) * tf.cos(b), -0.5 * tf.sin(a) * tf.sin(b)], [-0.5 * tf.sin(a) * tf.sin(b), 0.5 * tf.cos(a) * tf.cos(b)], ], ] np.testing.assert_allclose(hess, expected_hess, atol=tol, rtol=0, verbose=True) def test_state(self, dev_name, diff_method, grad_on_execution, tol, interface): """Test that the state can be returned and differentiated""" if diff_method == "adjoint": pytest.skip("Adjoint does not support states") num_wires = 2 if diff_method == "hadamard": num_wires = 3 dev = qml.device(dev_name, wires=num_wires) x = tf.Variable(0.543, dtype=tf.float64) y = tf.Variable(-0.654, dtype=tf.float64) @qnode( dev, diff_method=diff_method, interface=interface, grad_on_execution=grad_on_execution ) def circuit(x, y): qml.RX(x, wires=[0]) qml.RY(y, wires=[1]) qml.CNOT(wires=[0, 1]) return qml.state() def cost_fn(x, y): res = circuit(x, y) assert res.dtype is tf.complex128 probs = tf.math.abs(res) ** 2 return probs[0] + probs[2] with tf.GradientTape() as tape: res = cost_fn(x, y) if diff_method not in {"backprop"}: pytest.skip("Test only supports backprop") grad = tape.gradient(res, [x, y]) expected = [-np.sin(x) * np.cos(y) / 2, -np.cos(x) * np.sin(y) / 2] assert np.allclose(grad, expected, atol=tol, rtol=0) @pytest.mark.parametrize("state", [[1], [0, 1]]) # Basis state and state vector def test_projector(self, state, dev_name, diff_method, grad_on_execution, tol, interface): """Test that the variance of a projector is correctly returned""" kwargs = dict( diff_method=diff_method, grad_on_execution=grad_on_execution, interface=interface ) if diff_method == "adjoint": pytest.skip("Adjoint does not support projectors") elif diff_method == "hadamard": pytest.skip("Variance not implemented yet.") elif diff_method == "spsa": kwargs["sampler_rng"] = np.random.default_rng(SEED_FOR_SPSA) tol = TOL_FOR_SPSA dev = qml.device(dev_name, wires=2) P = tf.constant(state) x, y = 0.765, -0.654 weights = tf.Variable([x, y], dtype=tf.float64) @qnode(dev, **kwargs) def circuit(weights): qml.RX(weights[0], wires=0) qml.RY(weights[1], wires=1) qml.CNOT(wires=[0, 1]) return qml.var(qml.Projector(P, wires=0) @ qml.PauliX(1)) with tf.GradientTape() as tape: res = circuit(weights) expected = 0.25 * np.sin(x / 2) ** 2 * (3 + np.cos(2 * y) + 2 * np.cos(x) * np.sin(y) ** 2) assert np.allclose(res, expected, atol=tol, rtol=0) grad = tape.gradient(res, weights) expected = [ 0.5 * np.sin(x) * (np.cos(x / 2) ** 2 + np.cos(2 * y) * np.sin(x / 2) ** 2), -2 * np.cos(y) * np.sin(x / 2) ** 4 * np.sin(y), ] assert np.allclose(grad, expected, atol=tol, rtol=0) @pytest.mark.parametrize( "diff_method,kwargs", [ ["finite-diff", {}], ["spsa", {"num_directions": 100, "h": 0.05}], ("parameter-shift", {}), ("parameter-shift", {"force_order2": True}), ], ) class TestCV: """Tests for CV integration""" def test_first_order_observable(self, diff_method, kwargs, tol): """Test variance of a first order CV observable""" dev = qml.device("default.gaussian", wires=1) if diff_method == "spsa": kwargs["sampler_rng"] = np.random.default_rng(SEED_FOR_SPSA) tol = TOL_FOR_SPSA r = tf.Variable(0.543, dtype=tf.float64) phi = tf.Variable(-0.654, dtype=tf.float64) @qnode(dev, diff_method=diff_method, **kwargs) def circuit(r, phi): qml.Squeezing(r, 0, wires=0) qml.Rotation(phi, wires=0) return qml.var(qml.QuadX(0)) with tf.GradientTape() as tape: res = circuit(r, phi) expected = np.exp(2 * r) * np.sin(phi) ** 2 + np.exp(-2 * r) * np.cos(phi) ** 2 assert np.allclose(res, expected, atol=tol, rtol=0) # circuit jacobians grad = tape.gradient(res, [r, phi]) expected = [ 2 * np.exp(2 * r) * np.sin(phi) ** 2 - 2 * np.exp(-2 * r) * np.cos(phi) ** 2, 2 * np.sinh(2 * r) * np.sin(2 * phi), ] assert np.allclose(grad, expected, atol=tol, rtol=0) def test_second_order_observable(self, diff_method, kwargs, tol): """Test variance of a second order CV expectation value""" dev = qml.device("default.gaussian", wires=1) if diff_method == "spsa": kwargs["sampler_rng"] = np.random.default_rng(SEED_FOR_SPSA) tol = TOL_FOR_SPSA n = tf.Variable(0.12, dtype=tf.float64) a = tf.Variable(0.765, dtype=tf.float64) @qnode(dev, diff_method=diff_method, **kwargs) def circuit(n, a): qml.ThermalState(n, wires=0) qml.Displacement(a, 0, wires=0) return qml.var(qml.NumberOperator(0)) with tf.GradientTape() as tape: res = circuit(n, a) expected = n**2 + n + np.abs(a) ** 2 * (1 + 2 * n) assert np.allclose(res, expected, atol=tol, rtol=0) # circuit jacobians grad = tape.gradient(res, [n, a]) expected = [2 * a**2 + 2 * n + 1, 2 * a * (2 * n + 1)] assert np.allclose(grad, expected, atol=tol, rtol=0) @pytest.mark.parametrize( "interface,dev_name,diff_method,grad_on_execution", interface_and_qubit_device_and_diff_method ) class TestTapeExpansion: """Test that tape expansion within the QNode integrates correctly with the TF interface""" def test_gradient_expansion(self, dev_name, diff_method, grad_on_execution, interface): """Test that a *supported* operation with no gradient recipe is expanded for both parameter-shift and finite-differences, but not for execution.""" if diff_method not in ("parameter-shift", "finite-diff", "spsa", "hadamard"): pytest.skip("Only supports gradient transforms") num_wires = 1 if diff_method == "hadamard": num_wires = 2 dev = qml.device(dev_name, wires=num_wires) class PhaseShift(qml.PhaseShift): grad_method = None def decomposition(self): return [qml.RY(3 * self.data[0], wires=self.wires)] @qnode( dev, diff_method=diff_method, grad_on_execution=grad_on_execution, max_diff=2, interface=interface, ) def circuit(x): qml.Hadamard(wires=0) PhaseShift(x, wires=0) return qml.expval(qml.PauliX(0)) x = tf.Variable(0.5, dtype=tf.float64) with tf.GradientTape() as t2: with tf.GradientTape() as t1: loss = circuit(x) res = t1.gradient(loss, x) assert np.allclose(res, -3 * np.sin(3 * x)) if diff_method == "parameter-shift": # test second order derivatives res = t2.gradient(res, x) assert np.allclose(res, -9 * np.cos(3 * x)) @pytest.mark.parametrize("max_diff", [1, 2]) def test_gradient_expansion_trainable_only( self, dev_name, diff_method, grad_on_execution, max_diff, interface ): """Test that a *supported* operation with no gradient recipe is only expanded for parameter-shift and finite-differences when it is trainable.""" if diff_method not in ("parameter-shift", "finite-diff", "spsa", "hadamard"): pytest.skip("Only supports gradient transforms") num_wires = 1 if diff_method == "hadamard": num_wires = 2 dev = qml.device(dev_name, wires=num_wires) class PhaseShift(qml.PhaseShift): grad_method = None def decomposition(self): return [qml.RY(3 * self.data[0], wires=self.wires)] @qnode( dev, diff_method=diff_method, grad_on_execution=grad_on_execution, max_diff=max_diff, interface=interface, ) def circuit(x, y): qml.Hadamard(wires=0) PhaseShift(x, wires=0) PhaseShift(2 * y, wires=0) return qml.expval(qml.PauliX(0)) x = tf.Variable(0.5, dtype=tf.float64) y = tf.constant(0.7, dtype=tf.float64) with tf.GradientTape() as t: res = circuit(x, y) t.gradient(res, [x, y]) @pytest.mark.parametrize("max_diff", [1, 2]) def test_hamiltonian_expansion_analytic( self, dev_name, diff_method, grad_on_execution, max_diff, tol, interface ): """Test that if there are non-commuting groups and the number of shots is None the first and second order gradients are correctly evaluated""" kwargs = dict( diff_method=diff_method, grad_on_execution=grad_on_execution, max_diff=max_diff, interface=interface, ) if diff_method in ["adjoint", "hadamard"]: pytest.skip("The adjoint/hadamard method does not yet support Hamiltonians") elif diff_method == "spsa": tol = TOL_FOR_SPSA spsa_kwargs = dict(sampler_rng=np.random.default_rng(SEED_FOR_SPSA), num_directions=10) kwargs = {**kwargs, **spsa_kwargs} dev = qml.device(dev_name, wires=3, shots=None) obs = [qml.PauliX(0), qml.PauliX(0) @ qml.PauliZ(1), qml.PauliZ(0) @ qml.PauliZ(1)] @qnode(dev, **kwargs) def circuit(data, weights, coeffs): weights = tf.reshape(weights, [1, -1]) qml.templates.AngleEmbedding(data, wires=[0, 1]) qml.templates.BasicEntanglerLayers(weights, wires=[0, 1]) return qml.expval(qml.Hamiltonian(coeffs, obs)) d = tf.constant([0.1, 0.2], dtype=tf.float64) w = tf.Variable([0.654, -0.734], dtype=tf.float64) c = tf.Variable([-0.6543, 0.24, 0.54], dtype=tf.float64) # test output with tf.GradientTape(persistent=True) as t2: with tf.GradientTape() as t1: res = circuit(d, w, c) expected = c[2] * np.cos(d[1] + w[1]) - c[1] * np.sin(d[0] + w[0]) * np.sin(d[1] + w[1]) assert np.allclose(res, expected, atol=tol) # test gradients grad = t1.gradient(res, [d, w, c]) expected_w = [ -c[1] * np.cos(d[0] + w[0]) * np.sin(d[1] + w[1]), -c[1] * np.cos(d[1] + w[1]) * np.sin(d[0] + w[0]) - c[2] * np.sin(d[1] + w[1]), ] expected_c = [0, -np.sin(d[0] + w[0]) * np.sin(d[1] + w[1]), np.cos(d[1] + w[1])] assert np.allclose(grad[1], expected_w, atol=tol) assert np.allclose(grad[2], expected_c, atol=tol) # test second-order derivatives if diff_method in ("parameter-shift", "backprop") and max_diff == 2: grad2_c = t2.jacobian(grad[2], c) assert grad2_c is None or np.allclose(grad2_c, 0, atol=tol) grad2_w_c = t2.jacobian(grad[1], c) expected = [0, -np.cos(d[0] + w[0]) * np.sin(d[1] + w[1]), 0], [ 0, -np.cos(d[1] + w[1]) * np.sin(d[0] + w[0]), -np.sin(d[1] + w[1]), ] assert np.allclose(grad2_w_c, expected, atol=tol) @pytest.mark.parametrize("max_diff", [1, 2]) def test_hamiltonian_expansion_finite_shots( self, dev_name, diff_method, grad_on_execution, max_diff, mocker, interface ): """Test that the Hamiltonian is expanded if there are non-commuting groups and the number of shots is finite and the first and second order gradients are correctly evaluated""" gradient_kwargs = {} tol = 0.3 if diff_method in ("adjoint", "backprop", "hadamard"): pytest.skip("The adjoint and backprop methods do not yet support sampling") elif diff_method == "spsa": gradient_kwargs = { "h": H_FOR_SPSA, "sampler_rng": np.random.default_rng(SEED_FOR_SPSA), "num_directions": 20, } tol = TOL_FOR_SPSA elif diff_method == "finite-diff": gradient_kwargs = {"h": 0.05} dev = qml.device(dev_name, wires=3, shots=50000) spy = mocker.spy(qml.transforms, "split_non_commuting") obs = [qml.PauliX(0), qml.PauliX(0) @ qml.PauliZ(1), qml.PauliZ(0) @ qml.PauliZ(1)] @qnode( dev, diff_method=diff_method, grad_on_execution=grad_on_execution, max_diff=max_diff, interface=interface, **gradient_kwargs, ) def circuit(data, weights, coeffs): weights = tf.reshape(weights, [1, -1]) qml.templates.AngleEmbedding(data, wires=[0, 1]) qml.templates.BasicEntanglerLayers(weights, wires=[0, 1]) H = qml.Hamiltonian(coeffs, obs) H.compute_grouping() return qml.expval(H) d = tf.constant([0.1, 0.2], dtype=tf.float64) w = tf.Variable([0.654, -0.734], dtype=tf.float64) c = tf.Variable([-0.6543, 0.24, 0.54], dtype=tf.float64) # test output with tf.GradientTape(persistent=True) as t2: with tf.GradientTape() as t1: res = circuit(d, w, c) expected = c[2] * np.cos(d[1] + w[1]) - c[1] * np.sin(d[0] + w[0]) * np.sin(d[1] + w[1]) assert np.allclose(res, expected, atol=tol) spy.assert_called() # test gradients grad = t1.gradient(res, [d, w, c]) expected_w = [ -c[1] * np.cos(d[0] + w[0]) * np.sin(d[1] + w[1]), -c[1] * np.cos(d[1] + w[1]) * np.sin(d[0] + w[0]) - c[2] * np.sin(d[1] + w[1]), ] expected_c = [0, -np.sin(d[0] + w[0]) * np.sin(d[1] + w[1]), np.cos(d[1] + w[1])] assert np.allclose(grad[1], expected_w, atol=tol) assert np.allclose(grad[2], expected_c, atol=tol) # test second-order derivatives if diff_method == "parameter-shift" and max_diff == 2: grad2_c = t2.jacobian(grad[2], c) assert grad2_c is None or np.allclose(grad2_c, 0, atol=tol) grad2_w_c = t2.jacobian(grad[1], c) expected = [0, -np.cos(d[0] + w[0]) * np.sin(d[1] + w[1]), 0], [ 0, -np.cos(d[1] + w[1]) * np.sin(d[0] + w[0]), -np.sin(d[1] + w[1]), ] assert np.allclose(grad2_w_c, expected, atol=tol) class TestSample: """Tests for the sample integration""" def test_sample_dimension(self): """Test sampling works as expected""" dev = qml.device("default.qubit.legacy", wires=2, shots=10) @qnode(dev, diff_method="parameter-shift", interface="tf") def circuit(): qml.Hadamard(wires=[0]) qml.CNOT(wires=[0, 1]) return qml.sample(qml.PauliZ(0)), qml.sample(qml.PauliX(1)) res = circuit() assert isinstance(res, tuple) assert len(res) == 2 assert res[0].shape == (10,) assert res[1].shape == (10,) assert isinstance(res[0], tf.Tensor) assert isinstance(res[1], tf.Tensor) def test_sampling_expval(self): """Test sampling works as expected if combined with expectation values""" dev = qml.device("default.qubit.legacy", wires=2, shots=10) @qnode(dev, diff_method="parameter-shift", interface="tf") def circuit(): qml.Hadamard(wires=[0]) qml.CNOT(wires=[0, 1]) return qml.sample(qml.PauliZ(0)), qml.expval(qml.PauliX(1)) res = circuit() assert len(res) == 2 assert isinstance(res, tuple) assert res[0].shape == (10,) assert res[1].shape == () assert isinstance(res[0], tf.Tensor) assert isinstance(res[1], tf.Tensor) def test_sample_combination(self): """Test the output of combining expval, var and sample""" n_sample = 10 dev = qml.device("default.qubit.legacy", wires=3, shots=n_sample) @qnode(dev, diff_method="parameter-shift", interface="tf") def circuit(): qml.RX(0.54, wires=0) return qml.sample(qml.PauliZ(0)), qml.expval(qml.PauliX(1)), qml.var(qml.PauliY(2)) result = circuit() assert len(result) == 3 assert result[0].shape == (n_sample,) assert result[1].shape == () assert result[2].shape == () assert isinstance(result[0], tf.Tensor) assert isinstance(result[1], tf.Tensor) assert isinstance(result[2], tf.Tensor) assert result[0].dtype is tf.float64 assert result[1].dtype is tf.float64 assert result[2].dtype is tf.float64 def test_single_wire_sample(self): """Test the return type and shape of sampling a single wire""" n_sample = 10 dev = qml.device("default.qubit.legacy", wires=1, shots=n_sample) @qnode(dev, diff_method="parameter-shift", interface="tf") def circuit(): qml.RX(0.54, wires=0) return qml.sample(qml.PauliZ(0)) result = circuit() assert isinstance(result, tf.Tensor) assert np.array_equal(result.shape, (n_sample,)) def test_multi_wire_sample_regular_shape(self): """Test the return type and shape of sampling multiple wires where a rectangular array is expected""" n_sample = 10 dev = qml.device("default.qubit.legacy", wires=3, shots=n_sample) @qnode(dev, diff_method="parameter-shift", interface="tf") def circuit(): return qml.sample(qml.PauliZ(0)), qml.sample(qml.PauliZ(1)), qml.sample(qml.PauliZ(2)) result = circuit() result = tf.stack(result) # If all the dimensions are equal the result will end up to be a proper rectangular array assert isinstance(result, tf.Tensor) assert np.array_equal(result.shape, (3, n_sample)) assert result.dtype == tf.float64 def test_counts(self): """Test counts works as expected for TF""" dev = qml.device("default.qubit.legacy", wires=2, shots=100) @qnode(dev, interface="tf") def circuit(): qml.Hadamard(wires=[0]) qml.CNOT(wires=[0, 1]) return qml.counts(qml.PauliZ(0)) res = circuit() assert isinstance(res, dict) assert list(res.keys()) == [-1, 1] assert isinstance(res[-1], tf.Tensor) assert isinstance(res[1], tf.Tensor) assert res[-1].shape == () assert res[1].shape == () @pytest.mark.parametrize( "decorator, interface", [(tf.function, "auto"), (tf.function, "tf"), (lambda x: x, "tf-autograph")], ) class TestAutograph: """Tests for Autograph mode. This class is parametrized over the combination: 1. interface=interface with the QNode decoratored with @tf.function, and 2. interface="tf-autograph" with no QNode decorator. Option (1) checks that if the user enables autograph functionality in TensorFlow, the new `tf-autograph` interface is automatically applied. Option (2) ensures that the tf-autograph interface can be manually applied, even if in eager execution mode. """ def test_autograph_gradients(self, decorator, interface, tol): """Test that a parameter-shift QNode can be compiled using @tf.function, and differentiated""" dev = qml.device("default.qubit.legacy", wires=2) x = tf.Variable(0.543, dtype=tf.float64) y = tf.Variable(-0.654, dtype=tf.float64) @decorator @qnode(dev, diff_method="parameter-shift", interface=interface) def circuit(x, y): qml.RX(x, wires=[0]) qml.RY(y, wires=[1]) qml.CNOT(wires=[0, 1]) return qml.probs(wires=[0]), qml.probs(wires=[1]) with tf.GradientTape() as tape: p0, p1 = circuit(x, y) loss = p0[0] + p1[1] expected = tf.cos(x / 2) ** 2 + (1 - tf.cos(x) * tf.cos(y)) / 2 assert np.allclose(loss, expected, atol=tol, rtol=0) grad = tape.gradient(loss, [x, y]) expected = [-tf.sin(x) * tf.sin(y / 2) ** 2, tf.cos(x) * tf.sin(y) / 2] assert np.allclose(grad, expected, atol=tol, rtol=0) def test_autograph_jacobian(self, decorator, interface, tol): """Test that a parameter-shift vector-valued QNode can be compiled using @tf.function, and differentiated""" dev = qml.device("default.qubit.legacy", wires=2) x = tf.Variable(0.543, dtype=tf.float64) y = tf.Variable(-0.654, dtype=tf.float64) @decorator @qnode(dev, diff_method="parameter-shift", max_diff=1, interface=interface) def circuit(x, y): qml.RX(x, wires=[0]) qml.RY(y, wires=[1]) qml.CNOT(wires=[0, 1]) return qml.probs(wires=[0]), qml.probs(wires=[1]) with tf.GradientTape() as tape: res = circuit(x, y) res = tf.stack(res) expected = np.array( [ [tf.cos(x / 2) ** 2, tf.sin(x / 2) ** 2], [(1 + tf.cos(x) * tf.cos(y)) / 2, (1 - tf.cos(x) * tf.cos(y)) / 2], ] ) assert np.allclose(res, expected, atol=tol, rtol=0) res = tape.jacobian(res, [x, y]) expected = np.array( [ [ [-tf.sin(x) / 2, tf.sin(x) / 2], [-tf.sin(x) * tf.cos(y) / 2, tf.cos(y) * tf.sin(x) / 2], ], [ [0, 0], [-tf.cos(x) * tf.sin(y) / 2, tf.cos(x) * tf.sin(y) / 2], ], ] ) assert np.allclose(res, expected, atol=tol, rtol=0) @pytest.mark.parametrize("grad_on_execution", [True, False]) def test_autograph_adjoint_single_param(self, grad_on_execution, decorator, interface, tol): """Test that a parameter-shift QNode can be compiled using @tf.function, and differentiated to second order""" dev = qml.device("default.qubit.legacy", wires=1) @decorator @qnode(dev, diff_method="adjoint", interface=interface, grad_on_execution=grad_on_execution) def circuit(x): qml.RY(x, wires=0) return qml.expval(qml.PauliZ(0)) x = tf.Variable(1.0, dtype=tf.float64) with tf.GradientTape() as tape: res = circuit(x) g = tape.gradient(res, x) expected_res = tf.cos(x) assert np.allclose(res, expected_res, atol=tol, rtol=0) expected_g = -tf.sin(x) assert np.allclose(g, expected_g, atol=tol, rtol=0) @pytest.mark.parametrize("grad_on_execution", [True, False]) def test_autograph_adjoint_multi_params(self, grad_on_execution, decorator, interface, tol): """Test that a parameter-shift QNode can be compiled using @tf.function, and differentiated to second order""" dev = qml.device("default.qubit.legacy", wires=1) @decorator @qnode(dev, diff_method="adjoint", interface=interface, grad_on_execution=grad_on_execution) def circuit(x): qml.RY(x[0], wires=0) qml.RX(x[1], wires=0) return qml.expval(qml.PauliZ(0)) x = tf.Variable([1.0, 2.0], dtype=tf.float64) with tf.GradientTape() as tape: res = circuit(x) g = tape.gradient(res, x) a, b = x * 1.0 expected_res = tf.cos(a) * tf.cos(b) assert np.allclose(res, expected_res, atol=tol, rtol=0) expected_g = [-tf.sin(a) * tf.cos(b), -tf.cos(a) * tf.sin(b)] assert np.allclose(g, expected_g, atol=tol, rtol=0) def test_autograph_ragged_differentiation(self, decorator, interface, tol): """Tests correct output shape and evaluation for a tape with prob and expval outputs""" dev = qml.device("default.qubit.legacy", wires=2) x = tf.Variable(0.543, dtype=tf.float64) y = tf.Variable(-0.654, dtype=tf.float64) @decorator @qnode(dev, diff_method="parameter-shift", max_diff=1, interface=interface) def circuit(x, y): qml.RX(x, wires=[0]) qml.RY(y, wires=[1]) qml.CNOT(wires=[0, 1]) return qml.expval(qml.PauliZ(0)), qml.probs(wires=[1]) with tf.GradientTape() as tape: res = circuit(x, y) res = tf.experimental.numpy.hstack(res) expected = np.array( [ tf.cos(x), (1 + tf.cos(x) * tf.cos(y)) / 2, (1 - tf.cos(x) * tf.cos(y)) / 2, ] ) assert np.allclose(res, expected, atol=tol, rtol=0) res = tape.jacobian(res, [x, y]) expected = np.array( [ [-tf.sin(x), -tf.sin(x) * tf.cos(y) / 2, tf.cos(y) * tf.sin(x) / 2], [0, -tf.cos(x) * tf.sin(y) / 2, tf.cos(x) * tf.sin(y) / 2], ] ) assert np.allclose(res, expected, atol=tol, rtol=0) def test_autograph_hessian(self, decorator, interface, tol): """Test that a parameter-shift QNode can be compiled using @tf.function, and differentiated to second order""" dev = qml.device("default.qubit.legacy", wires=1) a = tf.Variable(0.543, dtype=tf.float64) b = tf.Variable(-0.654, dtype=tf.float64) @decorator @qnode(dev, diff_method="parameter-shift", max_diff=2, interface=interface) def circuit(x, y): qml.RY(x, wires=0) qml.RX(y, wires=0) return qml.expval(qml.PauliZ(0)) with tf.GradientTape() as tape1: with tf.GradientTape() as tape2: res = circuit(a, b) g = tape2.gradient(res, [a, b]) g = tf.stack(g) hess = tf.stack(tape1.gradient(g, [a, b])) expected_res = tf.cos(a) * tf.cos(b) assert np.allclose(res, expected_res, atol=tol, rtol=0) expected_g = [-tf.sin(a) * tf.cos(b), -tf.cos(a) * tf.sin(b)] assert np.allclose(g, expected_g, atol=tol, rtol=0) expected_hess = [ [-tf.cos(a) * tf.cos(b) + tf.sin(a) * tf.sin(b)], [tf.sin(a) * tf.sin(b) - tf.cos(a) * tf.cos(b)], ] assert np.allclose(hess, expected_hess, atol=tol, rtol=0) def test_autograph_sample(self, decorator, interface): """Test that a QNode returning raw samples can be compiled using @tf.function""" dev = qml.device("default.qubit", wires=2, shots=100) x = tf.Variable(0.543, dtype=tf.float64) y = tf.Variable(-0.654, dtype=tf.float64) @decorator @qnode(dev, diff_method="parameter-shift", interface=interface) def circuit(x, y): qml.RX(x, wires=[0]) qml.RY(y, wires=[1]) qml.CNOT(wires=[0, 1]) return qml.sample() result = circuit(x, y) result = np.array(result).flatten() assert np.all([r in [1, 0] for r in result]) def test_autograph_state(self, decorator, interface, tol): """Test that a parameter-shift QNode returning a state can be compiled using @tf.function""" dev = qml.device("default.qubit.legacy", wires=2) x = tf.Variable(0.543, dtype=tf.float64) y = tf.Variable(-0.654, dtype=tf.float64) # TODO: fix this for diff_method=None @decorator @qnode(dev, diff_method="parameter-shift", interface=interface) def circuit(x, y): qml.RX(x, wires=[0]) qml.RY(y, wires=[1]) qml.CNOT(wires=[0, 1]) return qml.state() with tf.GradientTape(): state = circuit(x, y) probs = tf.abs(state) ** 2 loss = probs[0] expected = tf.cos(x / 2) ** 2 * tf.cos(y / 2) ** 2 assert np.allclose(loss, expected, atol=tol, rtol=0) def test_autograph_dimension(self, decorator, interface): """Test sampling works as expected""" dev = qml.device("default.qubit.legacy", wires=2, shots=10) @decorator @qnode(dev, diff_method="parameter-shift", interface=interface) def circuit(): qml.Hadamard(wires=[0]) qml.CNOT(wires=[0, 1]) return qml.sample(qml.PauliZ(0)), qml.sample(qml.PauliX(1)) res = circuit() res = tf.stack(res) assert res.shape == (2, 10) assert isinstance(res, tf.Tensor) @pytest.mark.parametrize( "interface,dev_name,diff_method,grad_on_execution", interface_and_qubit_device_and_diff_method ) class TestReturn: """Class to test the shape of the Grad/Jacobian/Hessian with different return types.""" def test_grad_single_measurement_param( self, dev_name, diff_method, grad_on_execution, interface ): """For one measurement and one param, the gradient is a float.""" num_wires = 1 if diff_method == "hadamard": num_wires = 2 dev = qml.device(dev_name, wires=num_wires) @qnode( dev, interface=interface, diff_method=diff_method, grad_on_execution=grad_on_execution ) def circuit(a): qml.RY(a, wires=0) qml.RX(0.2, wires=0) return qml.expval(qml.PauliZ(0)) a = tf.Variable(0.1) with tf.GradientTape() as tape: res = circuit(a) grad = tape.gradient(res, a) assert isinstance(grad, tf.Tensor) assert grad.shape == () def test_grad_single_measurement_multiple_param( self, dev_name, diff_method, grad_on_execution, interface ): """For one measurement and multiple param, the gradient is a tuple of arrays.""" num_wires = 1 if diff_method == "hadamard": num_wires = 2 dev = qml.device(dev_name, wires=num_wires) @qnode( dev, interface=interface, diff_method=diff_method, grad_on_execution=grad_on_execution ) def circuit(a, b): qml.RY(a, wires=0) qml.RX(b, wires=0) return qml.expval(qml.PauliZ(0)) a = tf.Variable(0.1) b = tf.Variable(0.2) with tf.GradientTape() as tape: res = circuit(a, b) grad = tape.gradient(res, (a, b)) assert isinstance(grad, tuple) assert len(grad) == 2 assert grad[0].shape == () assert grad[1].shape == () def test_grad_single_measurement_multiple_param_array( self, dev_name, diff_method, grad_on_execution, interface ): """For one measurement and multiple param as a single array params, the gradient is an array.""" num_wires = 1 if diff_method == "hadamard": num_wires = 2 dev = qml.device(dev_name, wires=num_wires) @qnode( dev, interface=interface, diff_method=diff_method, grad_on_execution=grad_on_execution ) def circuit(a): qml.RY(a[0], wires=0) qml.RX(a[1], wires=0) return qml.expval(qml.PauliZ(0)) a = tf.Variable([0.1, 0.2]) with tf.GradientTape() as tape: res = circuit(a) grad = tape.gradient(res, a) assert isinstance(grad, tf.Tensor) assert len(grad) == 2 assert grad.shape == (2,) def test_jacobian_single_measurement_param_probs( self, dev_name, diff_method, grad_on_execution, interface ): """For a multi dimensional measurement (probs), check that a single array is returned with the correct dimension""" if diff_method == "adjoint": pytest.skip("Test does not supports adjoint because of probabilities.") num_wires = 2 if diff_method == "hadamard": num_wires = 3 dev = qml.device(dev_name, wires=num_wires) @qnode( dev, interface=interface, diff_method=diff_method, grad_on_execution=grad_on_execution ) def circuit(a): qml.RY(a, wires=0) qml.RX(0.2, wires=0) return qml.probs(wires=[0, 1]) a = tf.Variable(0.1) with tf.GradientTape() as tape: res = circuit(a) jac = tape.jacobian(res, a) assert isinstance(jac, tf.Tensor) assert jac.shape == (4,) def test_jacobian_single_measurement_probs_multiple_param( self, dev_name, diff_method, grad_on_execution, interface ): """For a multi dimensional measurement (probs), check that a single tuple is returned containing arrays with the correct dimension""" if diff_method == "adjoint": pytest.skip("Test does not supports adjoint because of probabilities.") num_wires = 2 if diff_method == "hadamard": num_wires = 3 dev = qml.device(dev_name, wires=num_wires) @qnode( dev, interface=interface, diff_method=diff_method, grad_on_execution=grad_on_execution ) def circuit(a, b): qml.RY(a, wires=0) qml.RX(b, wires=0) return qml.probs(wires=[0, 1]) a = tf.Variable(0.1) b = tf.Variable(0.2) with tf.GradientTape() as tape: res = circuit(a, b) jac = tape.jacobian(res, (a, b)) assert isinstance(jac, tuple) assert isinstance(jac[0], tf.Tensor) assert jac[0].shape == (4,) assert isinstance(jac[1], tf.Tensor) assert jac[1].shape == (4,) def test_jacobian_single_measurement_probs_multiple_param_single_array( self, dev_name, diff_method, grad_on_execution, interface ): """For a multi dimensional measurement (probs), check that a single array is returned.""" if diff_method == "adjoint": pytest.skip("Test does not supports adjoint because of probabilities.") num_wires = 2 if diff_method == "hadamard": num_wires = 3 dev = qml.device(dev_name, wires=num_wires) @qnode( dev, interface=interface, diff_method=diff_method, grad_on_execution=grad_on_execution ) def circuit(a): qml.RY(a[0], wires=0) qml.RX(a[1], wires=0) return qml.probs(wires=[0, 1]) a = tf.Variable([0.1, 0.2]) with tf.GradientTape() as tape: res = circuit(a) jac = tape.jacobian(res, a) assert isinstance(jac, tf.Tensor) assert jac.shape == (4, 2) def test_jacobian_multiple_measurement_single_param( self, dev_name, diff_method, grad_on_execution, interface ): """The jacobian of multiple measurements with a single params return an array.""" num_wires = 2 if diff_method == "hadamard": num_wires = 3 dev = qml.device(dev_name, wires=num_wires) if diff_method == "adjoint": pytest.skip("Test does not supports adjoint because of probabilities.") @qnode( dev, interface=interface, diff_method=diff_method, grad_on_execution=grad_on_execution ) def circuit(a): qml.RY(a, wires=0) qml.RX(0.2, wires=0) return qml.expval(qml.PauliZ(0)), qml.probs(wires=[0, 1]) a = tf.Variable(0.1) with tf.GradientTape() as tape: res = circuit(a) res = tf.experimental.numpy.hstack(res) jac = tape.jacobian(res, a) assert isinstance(jac, tf.Tensor) assert jac.shape == (5,) def test_jacobian_multiple_measurement_multiple_param( self, dev_name, diff_method, grad_on_execution, interface ): """The jacobian of multiple measurements with a multiple params return a tuple of arrays.""" if diff_method == "adjoint": pytest.skip("Test does not supports adjoint because of probabilities.") num_wires = 2 if diff_method == "hadamard": num_wires = 3 dev = qml.device(dev_name, wires=num_wires) @qnode( dev, interface=interface, diff_method=diff_method, grad_on_execution=grad_on_execution ) def circuit(a, b): qml.RY(a, wires=0) qml.RX(b, wires=0) return qml.expval(qml.PauliZ(0)), qml.probs(wires=[0, 1]) a = tf.Variable(0.1) b = tf.Variable(0.2) with tf.GradientTape() as tape: res = circuit(a, b) res = tf.experimental.numpy.hstack(res) jac = tape.jacobian(res, (a, b)) assert isinstance(jac, tuple) assert len(jac) == 2 assert isinstance(jac[0], tf.Tensor) assert jac[0].shape == (5,) assert isinstance(jac[1], tf.Tensor) assert jac[1].shape == (5,) def test_jacobian_multiple_measurement_multiple_param_array( self, dev_name, diff_method, grad_on_execution, interface ): """The jacobian of multiple measurements with a multiple params array return a single array.""" if diff_method == "adjoint": pytest.skip("Test does not supports adjoint because of probabilities.") num_wires = 2 if diff_method == "hadamard": num_wires = 4 dev = qml.device(dev_name, wires=num_wires) @qnode( dev, interface=interface, diff_method=diff_method, grad_on_execution=grad_on_execution ) def circuit(a): qml.RY(a[0], wires=0) qml.RX(a[1], wires=0) return qml.expval(qml.PauliZ(0)), qml.probs(wires=[0, 1]) a = tf.Variable([0.1, 0.2]) with tf.GradientTape() as tape: res = circuit(a) res = tf.experimental.numpy.hstack(res) jac = tape.jacobian(res, a) assert isinstance(jac, tf.Tensor) assert jac.shape == (5, 2) def test_hessian_expval_multiple_params( self, dev_name, diff_method, grad_on_execution, interface ): """The hessian of single a measurement with multiple params return a tuple of arrays.""" num_wires = 2 if diff_method == "hadamard": num_wires = 4 dev = qml.device(dev_name, wires=num_wires) if diff_method == "adjoint": pytest.skip("Test does not supports adjoint because second order diff.") par_0 = tf.Variable(0.1, dtype=tf.float64) par_1 = tf.Variable(0.2, dtype=tf.float64) @qnode( dev, interface=interface, diff_method=diff_method, max_diff=2, grad_on_execution=grad_on_execution, ) def circuit(x, y): qml.RX(x, wires=[0]) qml.RY(y, wires=[1]) qml.CNOT(wires=[0, 1]) return qml.expval(qml.PauliZ(0) @ qml.PauliX(1)) with tf.GradientTape() as tape1: with tf.GradientTape() as tape2: res = circuit(par_0, par_1) grad = tape2.gradient(res, (par_0, par_1)) grad = tf.stack(grad) hess = tape1.jacobian(grad, (par_0, par_1)) assert isinstance(hess, tuple) assert len(hess) == 2 assert isinstance(hess[0], tf.Tensor) assert hess[0].shape == (2,) assert isinstance(hess[1], tf.Tensor) assert hess[1].shape == (2,) def test_hessian_expval_multiple_param_array( self, dev_name, diff_method, grad_on_execution, interface ): """The hessian of single measurement with a multiple params array return a single array.""" if diff_method == "adjoint": pytest.skip("Test does not supports adjoint because second order diff.") num_wires = 2 if diff_method == "hadamard": num_wires = 4 dev = qml.device(dev_name, wires=num_wires) params = tf.Variable([0.1, 0.2], dtype=tf.float64) @qnode( dev, interface=interface, diff_method=diff_method, max_diff=2, grad_on_execution=grad_on_execution, ) def circuit(x): qml.RX(x[0], wires=[0]) qml.RY(x[1], wires=[1]) qml.CNOT(wires=[0, 1]) return qml.expval(qml.PauliZ(0) @ qml.PauliX(1)) with tf.GradientTape() as tape1: with tf.GradientTape() as tape2: res = circuit(params) grad = tape2.gradient(res, params) hess = tape1.jacobian(grad, params) assert isinstance(hess, tf.Tensor) assert hess.shape == (2, 2) def test_hessian_var_multiple_params(self, dev_name, diff_method, grad_on_execution, interface): """The hessian of single a measurement with multiple params return a tuple of arrays.""" dev = qml.device(dev_name, wires=2) if diff_method == "adjoint": pytest.skip("Test does not supports adjoint because second order diff.") if diff_method == "hadamard": pytest.skip("Test does not support hadamard because of variance.") par_0 = tf.Variable(0.1, dtype=tf.float64) par_1 = tf.Variable(0.2, dtype=tf.float64) @qnode( dev, interface=interface, diff_method=diff_method, max_diff=2, grad_on_execution=grad_on_execution, ) def circuit(x, y): qml.RX(x, wires=[0]) qml.RY(y, wires=[1]) qml.CNOT(wires=[0, 1]) return qml.var(qml.PauliZ(0) @ qml.PauliX(1)) with tf.GradientTape() as tape1: with tf.GradientTape() as tape2: res = circuit(par_0, par_1) grad = tape2.gradient(res, (par_0, par_1)) grad = tf.stack(grad) hess = tape1.jacobian(grad, (par_0, par_1)) assert isinstance(hess, tuple) assert len(hess) == 2 assert isinstance(hess[0], tf.Tensor) assert hess[0].shape == (2,) assert isinstance(hess[1], tf.Tensor) assert hess[1].shape == (2,) def test_hessian_var_multiple_param_array( self, dev_name, diff_method, grad_on_execution, interface ): """The hessian of single measurement with a multiple params array return a single array.""" if diff_method == "adjoint": pytest.skip("Test does not supports adjoint because second order diff.") if diff_method == "hadamard": pytest.skip("Test does not support hadamard because of variance.") dev = qml.device(dev_name, wires=2) params = tf.Variable([0.1, 0.2], dtype=tf.float64) @qnode( dev, interface=interface, diff_method=diff_method, max_diff=2, grad_on_execution=grad_on_execution, ) def circuit(x): qml.RX(x[0], wires=[0]) qml.RY(x[1], wires=[1]) qml.CNOT(wires=[0, 1]) return qml.var(qml.PauliZ(0) @ qml.PauliX(1)) with tf.GradientTape() as tape1: with tf.GradientTape() as tape2: res = circuit(params) grad = tape2.gradient(res, params) hess = tape1.jacobian(grad, params) assert isinstance(hess, tf.Tensor) assert hess.shape == (2, 2) def test_hessian_probs_expval_multiple_params( self, dev_name, diff_method, grad_on_execution, interface ): """The hessian of multiple measurements with multiple params return a tuple of arrays.""" num_wires = 2 if diff_method == "hadamard": pytest.skip("Test does not support hadamard because multiple measurements.") dev = qml.device(dev_name, wires=num_wires) if diff_method == "adjoint": pytest.skip("Test does not supports adjoint because second order diff.") par_0 = tf.Variable(0.1, dtype=tf.float64) par_1 = tf.Variable(0.2, dtype=tf.float64) @qnode( dev, interface=interface, diff_method=diff_method, max_diff=2, grad_on_execution=grad_on_execution, ) def circuit(x, y): qml.RX(x, wires=[0]) qml.RY(y, wires=[1]) qml.CNOT(wires=[0, 1]) return qml.expval(qml.PauliZ(0) @ qml.PauliX(1)), qml.probs(wires=[0]) with tf.GradientTape() as tape1: with tf.GradientTape(persistent=True) as tape2: res = circuit(par_0, par_1) res = tf.experimental.numpy.hstack(res) grad = tape2.jacobian(res, (par_0, par_1), experimental_use_pfor=False) grad = tf.concat(grad, 0) hess = tape1.jacobian(grad, (par_0, par_1)) assert isinstance(hess, tuple) assert len(hess) == 2 assert isinstance(hess[0], tf.Tensor) assert hess[0].shape == (6,) assert isinstance(hess[1], tf.Tensor) assert hess[1].shape == (6,) def test_hessian_probs_expval_multiple_param_array( self, dev_name, diff_method, grad_on_execution, interface ): """The hessian of multiple measurements with a multiple param array return a single array.""" if diff_method == "adjoint": pytest.skip("Test does not supports adjoint because second order diff.") if diff_method == "hadamard": pytest.skip("Test does not support hadamard because multiple measurements.") num_wires = 2 dev = qml.device(dev_name, wires=num_wires) params = tf.Variable([0.1, 0.2], dtype=tf.float64) @qnode( dev, interface=interface, diff_method=diff_method, max_diff=2, grad_on_execution=grad_on_execution, ) def circuit(x): qml.RX(x[0], wires=[0]) qml.RY(x[1], wires=[1]) qml.CNOT(wires=[0, 1]) return qml.expval(qml.PauliZ(0) @ qml.PauliX(1)), qml.probs(wires=[0]) with tf.GradientTape() as tape1: with tf.GradientTape(persistent=True) as tape2: res = circuit(params) res = tf.experimental.numpy.hstack(res) grad = tape2.jacobian(res, params, experimental_use_pfor=False) hess = tape1.jacobian(grad, params) assert isinstance(hess, tf.Tensor) assert hess.shape == (3, 2, 2) def test_hessian_probs_var_multiple_params( self, dev_name, diff_method, grad_on_execution, interface ): """The hessian of multiple measurements with multiple params return a tuple of arrays.""" dev = qml.device(dev_name, wires=2) if diff_method == "adjoint": pytest.skip("Test does not supports adjoint because second order diff.") if diff_method == "hadamard": pytest.skip("Test does not support hadamard because of variance.") par_0 = tf.Variable(0.1, dtype=tf.float64) par_1 = tf.Variable(0.2, dtype=tf.float64) @qnode( dev, interface=interface, diff_method=diff_method, max_diff=2, grad_on_execution=grad_on_execution, ) def circuit(x, y): qml.RX(x, wires=[0]) qml.RY(y, wires=[1]) qml.CNOT(wires=[0, 1]) return qml.var(qml.PauliZ(0) @ qml.PauliX(1)), qml.probs(wires=[0]) with tf.GradientTape() as tape1: with tf.GradientTape(persistent=True) as tape2: res = circuit(par_0, par_1) res = tf.experimental.numpy.hstack(res) grad = tape2.jacobian(res, (par_0, par_1), experimental_use_pfor=False) grad = tf.concat(grad, 0) hess = tape1.jacobian(grad, (par_0, par_1)) assert isinstance(hess, tuple) assert len(hess) == 2 assert isinstance(hess[0], tf.Tensor) assert hess[0].shape == (6,) assert isinstance(hess[1], tf.Tensor) assert hess[1].shape == (6,) def test_hessian_probs_var_multiple_param_array( self, dev_name, diff_method, grad_on_execution, interface ): """The hessian of multiple measurements with a multiple param array return a single array.""" if diff_method == "adjoint": pytest.skip("Test does not supports adjoint because second order diff.") if diff_method == "hadamard": pytest.skip("Test does not support hadamard because of variance.") dev = qml.device(dev_name, wires=2) params = tf.Variable([0.1, 0.2], dtype=tf.float64) @qnode( dev, interface=interface, diff_method=diff_method, max_diff=2, grad_on_execution=grad_on_execution, ) def circuit(x): qml.RX(x[0], wires=[0]) qml.RY(x[1], wires=[1]) qml.CNOT(wires=[0, 1]) return qml.var(qml.PauliZ(0) @ qml.PauliX(1)), qml.probs(wires=[0]) with tf.GradientTape() as tape1: with tf.GradientTape(persistent=True) as tape2: res = circuit(params) res = tf.experimental.numpy.hstack(res) grad = tape2.jacobian(res, params, experimental_use_pfor=False) hess = tape1.jacobian(grad, params) assert isinstance(hess, tf.Tensor) assert hess.shape == (3, 2, 2) @pytest.mark.parametrize("dev_name", ["default.qubit.legacy", "default.mixed"]) def test_no_ops(dev_name): """Test that the return value of the QNode matches in the interface even if there are no ops""" dev = qml.device(dev_name, wires=1) @qml.qnode(dev, interface="tf") def circuit(): qml.Hadamard(wires=0) return qml.state() res = circuit() assert isinstance(res, tf.Tensor)
pennylane/tests/interfaces/legacy_devices_integration/test_tensorflow_qnode_legacy.py/0
{ "file_path": "pennylane/tests/interfaces/legacy_devices_integration/test_tensorflow_qnode_legacy.py", "repo_id": "pennylane", "token_count": 44120 }
82
# Copyright 2018-2020 Xanadu Quantum Technologies Inc. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Unit tests for the :func:`pennylane.math.is_independent` function. """ import numpy as np # pylint: disable=too-few-public-methods import pytest import pennylane as qml from pennylane import numpy as pnp from pennylane.math import is_independent from pennylane.math.is_independent import _get_random_args pytestmark = pytest.mark.all_interfaces tf = pytest.importorskip("tensorflow", minversion="2.1") torch = pytest.importorskip("torch") jax = pytest.importorskip("jax") jnp = pytest.importorskip("jax.numpy") dependent_lambdas = [ lambda x: x, lambda x: (x, x), lambda x: [x] * 10, lambda x: (2.0 * x, x), lambda x: 0.0 * x, lambda x, y: (0.0 * x, 0.0 * y), lambda x: x if x > 0 else 0.0, # RELU for x>0 is okay numerically lambda x: x if x > 0 else 0.0, # RELU for x<0 is okay numerically lambda x: 1.0 if abs(x) < 1e-5 else 0.0, # delta for x=0 is okay numerically lambda x: x if abs(x) < 1e-4 else 0.0, # x*delta for x=0 is okay lambda x: 1.0 if x > 0 else 0.0, # Heaviside is okay numerically lambda x: 1.0 if x > 0 else 0.0, # Heaviside is okay numerically lambda x: qml.math.log(1 + qml.math.exp(100.0 * x)) / 100.0, # Softplus is okay lambda x: qml.math.log(1 + qml.math.exp(100.0 * x)) / 100.0, # Softplus is okay ] args_dependent_lambdas = [ (np.array(1.2),), (2.19,), (2.19,), (1.0,), (np.ones((2, 3)),), (np.array([2.0, 5.0]), 1.2), (1.6,), (-2.0,), (0.0,), (0.0,), (-2.0,), (2.0,), (-0.2,), (0.9,), ] lambdas_expect_torch_fail = [ False, False, False, False, True, True, False, False, False, True, False, False, False, False, ] overlooked_lambdas = [ lambda x: 1.0 if abs(x) < 1e-5 else 0.0, # delta for x!=0 is not okay lambda x: 1.0 if abs(x) < 1e-5 else 0.0, # delta for x!=0 is not okay ] args_overlooked_lambdas = [ (2.0,), (-2.0,), ] def const_circuit(x, y): # pylint: disable=unused-argument qml.RX(0.1, wires=0) return qml.expval(qml.PauliZ(0)) def dependent_circuit(x, y, z): # pylint: disable=unused-argument qml.RX(0.1, wires=0) qml.RY(y / 2, wires=0) qml.RZ(qml.math.sin(z), wires=0) return qml.expval(qml.PauliX(0)) class TestIsIndependentAutograd: """Tests for is_independent, which tests a function to be independent of its inputs, using Autograd.""" interface = "autograd" @pytest.mark.parametrize("num", [0, 1, 2]) @pytest.mark.parametrize( "args", [ (0.2,), (1.1, 3.2, 0.2), (np.array([[0, 9.2], [-1.2, 3.2]]),), (0.3, [1, 4, 2], np.array([0.3, 9.1])), ], ) @pytest.mark.parametrize("bounds", [(-1, 1), (0.1, 1.0211)]) def test_get_random_args(self, args, num, bounds): """Tests the utility ``_get_random_args`` using a fixed seed.""" seed = 921 rnd_args = _get_random_args(args, self.interface, num, seed, bounds) assert len(rnd_args) == num rng = np.random.default_rng(seed) for _rnd_args in rnd_args: expected = tuple( rng.random(np.shape(arg)) * (bounds[1] - bounds[0]) + bounds[0] for arg in args ) assert all(np.allclose(_exp, _rnd) for _exp, _rnd in zip(expected, _rnd_args)) dev = qml.device("default.qubit", wires=1) constant_functions = [ qml.QNode(const_circuit, dev, interface=interface), lambda x: np.arange(20).reshape((2, 5, 2)), lambda x: (np.ones(3), -0.1), qml.jacobian(lambda x, y: 4 * x - 2.1 * y, argnum=[0, 1]), ] args_constant = [ (0.1, np.array([-2.1, 0.1])), (1.2,), (np.ones((2, 3)),), (np.ones((3, 8)) * 0.1, -0.2 * np.ones((3, 8))), ] dependent_functions = [ qml.QNode(dependent_circuit, dev, interface=interface), np.array, lambda x: np.array(x * 0.0), lambda x: (1 + qml.math.tanh(100 * x)) / 2, *dependent_lambdas, ] args_dependent = [ (0.1, np.array(-2.1), -0.9), (-4.1,), (-4.1,), (np.ones((3, 8)) * 1.1,), *args_dependent_lambdas, ] @pytest.mark.parametrize("func, args", zip(constant_functions, args_constant)) def test_independent(self, func, args): """Tests that an independent function is correctly detected as such.""" assert is_independent(func, self.interface, args) @pytest.mark.parametrize("func, args", zip(dependent_functions, args_dependent)) def test_dependent(self, func, args): """Tests that a dependent function is correctly detected as such.""" assert not is_independent(func, self.interface, args) @pytest.mark.xfail @pytest.mark.parametrize("func, args", zip(overlooked_lambdas, args_overlooked_lambdas)) def test_overlooked_dependence(self, func, args): """Test that particular functions that are dependent on the input are overlooked.""" assert not is_independent(func, self.interface, args) def test_kwargs_are_considered(self): """Tests that kwargs are taken into account when checking independence of outputs.""" f = lambda x, kw=False: 0.1 * x if kw else 0.2 jac = qml.jacobian(f, argnum=0) args = (0.2,) assert is_independent(f, self.interface, args) assert not is_independent(f, self.interface, args, {"kw": True}) assert is_independent(jac, self.interface, args, {"kw": True}) def test_no_trainable_params_deprecation_grad(self, recwarn): """Tests that no deprecation warning arises when using qml.grad with qml.math.is_independent. """ def lin(x): return pnp.sum(x) x = pnp.array([0.2, 9.1, -3.2], requires_grad=True) jac = qml.grad(lin) assert qml.math.is_independent(jac, "autograd", (x,), {}) assert len(recwarn) == 0 def test_no_trainable_params_deprecation_jac(self, recwarn): """Tests that no deprecation arises when using qml.jacobian with qml.math.is_independent.""" def lin(x, weights=None): return np.dot(x, weights) x = pnp.array([0.2, 9.1, -3.2], requires_grad=True) weights = pnp.array([1.1, -0.7, 1.8], requires_grad=True) jac = qml.jacobian(lin) assert qml.math.is_independent(jac, "autograd", (x,), {"weights": weights}) assert len(recwarn) == 0 class TestIsIndependentJax: """Tests for is_independent, which tests a function to be independent of its inputs, using JAX.""" interface = "jax" @pytest.mark.parametrize("num", [0, 1, 2]) @pytest.mark.parametrize( "args", [ (0.2,), (1.1, 3.2, 0.2), (np.array([[0, 9.2], [-1.2, 3.2]]),), (0.3, [1, 4, 2], np.array([0.3, 9.1])), ], ) @pytest.mark.parametrize("bounds", [(-1, 1), (0.1, 1.0211)]) def test_get_random_args(self, args, num, bounds): """Tests the utility ``_get_random_args`` using a fixed seed.""" seed = 921 rnd_args = _get_random_args(args, self.interface, num, seed, bounds) assert len(rnd_args) == num rng = np.random.default_rng(seed) for _rnd_args in rnd_args: expected = tuple( rng.random(np.shape(arg)) * (bounds[1] - bounds[0]) + bounds[0] for arg in args ) assert all(np.allclose(_exp, _rnd) for _exp, _rnd in zip(expected, _rnd_args)) dev = qml.device("default.qubit", wires=1) constant_functions = [ qml.QNode(const_circuit, dev, interface=interface), lambda x: np.arange(20).reshape((2, 5, 2)), lambda x: (np.ones(3), -0.1), jax.jacobian(lambda x, y: 4.0 * x - 2.1 * y, argnums=[0, 1]), ] args_constant = [ (0.1, np.array([-2.1, 0.1])), (1.2,), (np.ones((2, 3)),), (jax.numpy.ones((3, 8)) * 0.1, -0.2 * jax.numpy.ones((3, 8))), ] dependent_functions = [ qml.QNode(dependent_circuit, dev, interface=interface), jax.numpy.array, lambda x: (1 + qml.math.tanh(1000 * x)) / 2, *dependent_lambdas, ] args_dependent = [ (0.1, np.array(-2.1), -0.9), (-4.1,), (jax.numpy.ones((3, 8)) * 1.1,), *args_dependent_lambdas, ] @pytest.mark.parametrize("func, args", zip(constant_functions, args_constant)) def test_independent(self, func, args): """Tests that an independent function is correctly detected as such.""" assert is_independent(func, self.interface, args) @pytest.mark.parametrize("func, args", zip(dependent_functions, args_dependent)) def test_dependent(self, func, args): """Tests that a dependent function is correctly detected as such.""" assert not is_independent(func, self.interface, args) @pytest.mark.xfail @pytest.mark.parametrize("func, args", zip(overlooked_lambdas, args_overlooked_lambdas)) def test_overlooked_dependence(self, func, args): """Test that particular functions that are dependent on the input are overlooked.""" assert not is_independent(func, self.interface, args) def test_kwargs_are_considered(self): """Tests that kwargs are taken into account when checking independence of outputs.""" f = lambda x, kw=False: 0.1 * x if kw else 0.2 jac = jax.jacobian(f, argnums=0) args = (0.2,) assert is_independent(f, self.interface, args) assert not is_independent(f, self.interface, args, {"kw": True}) assert is_independent(jac, self.interface, args, {"kw": True}) class TestIsIndependentTensorflow: """Tests for is_independent, which tests a function to be independent of its inputs, using Tensorflow.""" interface = "tf" @pytest.mark.parametrize("num", [0, 1, 2]) @pytest.mark.parametrize( "args", [ (tf.Variable(0.2),), (tf.Variable(1.1), tf.constant(3.2), tf.Variable(0.2)), (tf.Variable(np.array([[0, 9.2], [-1.2, 3.2]])),), (tf.Variable(0.3), [1, 4, 2], tf.Variable(np.array([0.3, 9.1]))), ], ) @pytest.mark.parametrize("bounds", [(-1, 1), (0.1, 1.0211)]) def test_get_random_args(self, args, num, bounds): """Tests the utility ``_get_random_args`` using a fixed seed.""" seed = 921 rnd_args = _get_random_args(args, self.interface, num, seed, bounds) assert len(rnd_args) == num tf.random.set_seed(seed) for _rnd_args in rnd_args: expected = tuple( tf.random.uniform(tf.shape(arg)) * (bounds[1] - bounds[0]) + bounds[0] for arg in args ) expected = tuple( tf.Variable(_exp) if isinstance(_arg, tf.Variable) else _exp for _arg, _exp in zip(args, expected) ) assert all(np.allclose(_exp, _rnd) for _exp, _rnd in zip(expected, _rnd_args)) dev = qml.device("default.qubit", wires=1) constant_functions = [ qml.QNode(const_circuit, dev, interface=interface), lambda x: np.arange(20).reshape((2, 5, 2)), lambda x: (np.ones(3), np.array(-0.1)), ] args_constant = [ (0.1, np.array([-2.1, 0.1])), (1.2,), (np.ones((2, 3)),), ] dependent_functions = [ qml.QNode(dependent_circuit, dev, interface=interface), lambda x: (1 + qml.math.tanh(1000 * x)) / 2, *dependent_lambdas, ] args_dependent = [ (tf.Variable(0.1), np.array(-2.1), tf.Variable(-0.9)), ( tf.Variable( np.ones((3, 8)) * 1.1, ), ), *args_dependent_lambdas, ] @pytest.mark.parametrize("func, args", zip(constant_functions, args_constant)) def test_independent(self, func, args): """Tests that an independent function is correctly detected as such.""" args = tuple(tf.Variable(_arg) for _arg in args) assert is_independent(func, self.interface, args) @pytest.mark.parametrize("func, args", zip(dependent_functions, args_dependent)) def test_dependent(self, func, args): """Tests that a dependent function is correctly detected as such.""" from tensorflow.python.framework.errors_impl import InvalidArgumentError args = tuple(tf.Variable(_arg) for _arg in args) # Filter out functions with TF-incompatible output format out = func(*args) if not isinstance(out, tf.Tensor): try: assert not is_independent(func, self.interface, args) except AttributeError: _func = lambda *args: tf.Variable(func(*args)) assert not is_independent(_func, self.interface, args) except InvalidArgumentError: pytest.skip() else: assert not is_independent(func, self.interface, args) @pytest.mark.xfail @pytest.mark.parametrize("func, args", zip(overlooked_lambdas, args_overlooked_lambdas)) def test_overlooked_dependence(self, func, args): """Test that particular functions that are dependent on the input are overlooked.""" assert not is_independent(func, self.interface, args) def test_kwargs_are_considered(self): """Tests that kwargs are taken into account when checking independence of outputs.""" f = lambda x, kw=False: 0.1 * x if kw else tf.constant(0.2) def _jac(x, kw): with tf.GradientTape() as tape: out = f(x, kw) return tape.jacobian(out, x) args = (tf.Variable(0.2),) assert is_independent(f, self.interface, args) assert not is_independent(f, self.interface, args, {"kw": True}) assert is_independent(_jac, self.interface, args, {"kw": True}) class TestIsIndependentTorch: """Tests for is_independent, which tests a function to be independent of its inputs, using PyTorch.""" interface = "torch" @pytest.mark.parametrize("num", [0, 1, 2]) @pytest.mark.parametrize( "args", [ (torch.tensor(0.2),), (1.1, 3.2, torch.tensor(0.2)), (torch.tensor([[0, 9.2], [-1.2, 3.2]]),), (0.3, torch.tensor([1, 4, 2]), torch.tensor([0.3, 9.1])), ], ) @pytest.mark.parametrize("bounds", [(-1, 1), (0.1, 1.0211)]) def test_get_random_args(self, args, num, bounds): """Tests the utility ``_get_random_args`` using a fixed seed.""" seed = 921 rnd_args = _get_random_args(args, self.interface, num, seed, bounds) assert len(rnd_args) == num torch.random.manual_seed(seed) for _rnd_args in rnd_args: expected = tuple( torch.rand(np.shape(arg)) * (bounds[1] - bounds[0]) + bounds[0] for arg in args ) assert all(np.allclose(_exp, _rnd) for _exp, _rnd in zip(expected, _rnd_args)) dev = qml.device("default.qubit", wires=1) constant_functions = [ qml.QNode(const_circuit, dev, interface=interface), lambda x: np.arange(20).reshape((2, 5, 2)), lambda x: (np.ones(3), -0.1), ] args_constant = [ (0.1, torch.tensor([-2.1, 0.1])), (1.2,), (torch.ones((2, 3)),), ] dependent_functions = [ qml.QNode(dependent_circuit, dev, interface=interface), torch.as_tensor, lambda x: (1 + qml.math.tanh(1000 * x)) / 2, *dependent_lambdas, ] args_dependent = [ (0.1, torch.tensor(-2.1), -0.9), (-4.1,), (torch.ones((3, 8)) * 1.1,), *args_dependent_lambdas, ] dependent_expect_torch_fail = [False, False, False, *lambdas_expect_torch_fail] @pytest.mark.parametrize("func, args", zip(constant_functions, args_constant)) def test_independent(self, func, args): """Tests that an independent function is correctly detected as such.""" with pytest.warns(UserWarning, match=r"The function is_independent is only available"): assert is_independent(func, self.interface, args) @pytest.mark.parametrize( "func, args, exp_fail", zip(dependent_functions, args_dependent, dependent_expect_torch_fail), ) def test_dependent(self, func, args, exp_fail): """Tests that a dependent function is correctly detected as such.""" with pytest.warns(UserWarning, match=r"The function is_independent is only available"): if exp_fail: assert is_independent(func, self.interface, args) else: assert not is_independent(func, self.interface, args) @pytest.mark.xfail @pytest.mark.parametrize("func, args", zip(overlooked_lambdas, args_overlooked_lambdas)) def test_overlooked_dependence(self, func, args): """Test that particular functions that are dependent on the input are overlooked.""" assert not is_independent(func, self.interface, args) def test_kwargs_are_considered(self): """Tests that kwargs are taken into account when checking independence of outputs.""" f = lambda x, kw=False: 0.1 * x if kw else 0.2 jac = lambda x, kw: torch.autograd.functional.jacobian(lambda x: f(x, kw), x) args = (torch.tensor(0.2),) with pytest.warns(UserWarning, match=r"The function is_independent is only available"): assert is_independent(f, self.interface, args) with pytest.warns(UserWarning, match=r"The function is_independent is only available"): assert not is_independent(f, self.interface, args, {"kw": True}) with pytest.warns(UserWarning, match=r"The function is_independent is only available"): assert is_independent(jac, self.interface, args, {"kw": True}) class TestOther: """Other tests for is_independent.""" def test_unknown_interface(self): """Test that an error is raised if an unknown interface is requested.""" with pytest.raises(ValueError, match="Unknown interface: hello"): is_independent(lambda x: x, "hello", (0.1,))
pennylane/tests/math/test_is_independent.py/0
{ "file_path": "pennylane/tests/math/test_is_independent.py", "repo_id": "pennylane", "token_count": 8623 }
83
# Copyright 2018-2023 Xanadu Quantum Technologies Inc. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for the qml.counts measurement process.""" import copy import numpy as np import pytest import pennylane as qml from pennylane.measurements import AllCounts, Counts, CountsMP from pennylane.wires import Wires class TestCounts: """Tests for the counts function""" def test_counts_properties(self): """Test that the properties are correct.""" meas1 = qml.counts(wires=0) meas2 = qml.counts(op=qml.PauliX(0), all_outcomes=True) assert meas1.samples_computational_basis is True assert meas1.return_type == Counts assert meas2.samples_computational_basis is False assert meas2.return_type == AllCounts def test_queue(self): """Test that the right measurement class is queued.""" with qml.queuing.AnnotatedQueue() as q: op = qml.PauliX(0) m = qml.counts(op) assert q.queue[0] is m assert isinstance(m, CountsMP) def test_copy(self): """Test that the ``__copy__`` method also copies the ``all_outcomes`` information.""" meas = qml.counts(wires=0, all_outcomes=True) meas_copy = copy.copy(meas) assert meas_copy.wires == Wires(0) assert meas_copy.all_outcomes is True def test_providing_observable_and_wires(self): """Test that a ValueError is raised if both an observable is provided and wires are specified""" with pytest.raises( ValueError, match="Cannot specify the wires to sample if an observable is provided." " The wires to sample will be determined directly from the observable.", ): qml.counts(qml.PauliZ(0), wires=[0, 1]) def test_hash(self): """Test that the hash property includes the all_outcomes property.""" m1 = qml.counts(all_outcomes=True) m2 = qml.counts(all_outcomes=False) assert m1.hash != m2.hash m3 = CountsMP(eigvals=[0.5, -0.5], wires=qml.wires.Wires(0), all_outcomes=True) assert m3.hash != m1.hash def test_repr(self): """Test that the repr includes the all_outcomes property.""" m1 = CountsMP(wires=Wires(0), all_outcomes=True) assert repr(m1) == "CountsMP(wires=[0], all_outcomes=True)" m2 = CountsMP(obs=qml.PauliX(0), all_outcomes=True) assert repr(m2) == "CountsMP(X(0), all_outcomes=True)" m3 = CountsMP(eigvals=(-1, 1), wires=[0], all_outcomes=False) assert repr(m3) == "CountsMP(eigvals=[-1 1], wires=[0], all_outcomes=False)" mv = qml.measure(0) m4 = CountsMP(obs=mv, all_outcomes=False) assert repr(m4) == "CountsMP(MeasurementValue(wires=[0]), all_outcomes=False)" class TestProcessSamples: """Unit tests for the counts.process_samples method""" def test_counts_shape_single_wires(self): """Test that the counts output is correct for single wires""" shots = 1000 rng = np.random.default_rng(123) samples = rng.choice([0, 1], size=(shots, 2)).astype(np.int64) result = qml.counts(wires=0).process_samples(samples, wire_order=[0]) assert len(result) == 2 assert set(result.keys()) == {"0", "1"} assert result["0"] == np.count_nonzero(samples[:, 0] == 0) assert result["1"] == np.count_nonzero(samples[:, 0] == 1) def test_counts_shape_multi_wires(self): """Test that the counts function outputs counts of the right size for multiple wires""" shots = 1000 rng = np.random.default_rng(123) samples = rng.choice([0, 1], size=(shots, 2)).astype(np.int64) result = qml.counts(wires=[0, 1]).process_samples(samples, wire_order=[0, 1]) assert len(result) == 4 assert set(result.keys()) == {"00", "01", "10", "11"} assert result["00"] == np.count_nonzero( np.logical_and(samples[:, 0] == 0, samples[:, 1] == 0) ) assert result["01"] == np.count_nonzero( np.logical_and(samples[:, 0] == 0, samples[:, 1] == 1) ) assert result["10"] == np.count_nonzero( np.logical_and(samples[:, 0] == 1, samples[:, 1] == 0) ) assert result["11"] == np.count_nonzero( np.logical_and(samples[:, 0] == 1, samples[:, 1] == 1) ) def test_counts_with_nan_samples(self): """Test that the counts function disregards failed measurements (samples including NaN values) when totalling counts""" shots = 1000 rng = np.random.default_rng(123) samples = rng.choice([0, 1], size=(shots, 2)).astype(np.float64) samples[0][0] = np.NaN samples[17][1] = np.NaN samples[850][0] = np.NaN result = qml.counts(wires=[0, 1]).process_samples(samples, wire_order=[0, 1]) # no keys with NaNs assert len(result) == 4 assert set(result.keys()) == {"00", "01", "10", "11"} # NaNs were not converted into "0", but were excluded from the counts total_counts = sum(count for count in result.values()) assert total_counts == 997 @pytest.mark.parametrize("batch_size", [None, 1, 4]) @pytest.mark.parametrize("n_wires", [4, 10, 65]) @pytest.mark.parametrize("all_outcomes", [False, True]) def test_counts_multi_wires_no_overflow(self, n_wires, all_outcomes, batch_size): """Test that binary strings for wire samples are not negative due to overflow.""" if all_outcomes and n_wires == 65: pytest.skip("Too much memory being used, skipping") shots = 1000 total_wires = 65 shape = (batch_size, shots, total_wires) if batch_size else (shots, total_wires) samples = np.random.choice([0, 1], size=shape).astype(np.float64) result = qml.counts(wires=list(range(n_wires)), all_outcomes=all_outcomes).process_samples( samples, wire_order=list(range(total_wires)) ) if batch_size: assert len(result) == batch_size for r in result: assert sum(r.values()) == shots assert all("-" not in sample for sample in r.keys()) else: assert sum(result.values()) == shots assert all("-" not in sample for sample in result.keys()) def test_counts_obs(self): """Test that the counts function outputs counts of the right size for observables""" shots = 1000 rng = np.random.default_rng(123) samples = rng.choice([0, 1], size=(shots, 2)).astype(np.int64) result = qml.counts(qml.PauliZ(0)).process_samples(samples, wire_order=[0]) assert len(result) == 2 assert set(result.keys()) == {1, -1} assert result[1] == np.count_nonzero(samples[:, 0] == 0) assert result[-1] == np.count_nonzero(samples[:, 0] == 1) def test_count_eigvals(self): """Tests that eigvals are used instead of obs for counts""" shots = 100 rng = np.random.default_rng(123) samples = rng.choice([0, 1], size=(shots, 2)).astype(np.int64) result = CountsMP(eigvals=[1, -1], wires=0).process_samples(samples, wire_order=[0]) assert len(result) == 2 assert set(result.keys()) == {1, -1} assert result[1] == np.count_nonzero(samples[:, 0] == 0) assert result[-1] == np.count_nonzero(samples[:, 0] == 1) def test_counts_shape_single_measurement_value(self): """Test that the counts output is correct for single mid-circuit measurement values.""" shots = 1000 rng = np.random.default_rng(123) samples = rng.choice([0, 1], size=(shots, 2)).astype(np.int64) mv = qml.measure(0) result = qml.counts(mv).process_samples(samples, wire_order=[0]) assert len(result) == 2 assert set(result.keys()) == {0, 1} assert result[0] == np.count_nonzero(samples[:, 0] == 0) assert result[1] == np.count_nonzero(samples[:, 0] == 1) def test_counts_shape_composite_measurement_value(self): """Test that the counts output is correct for composite mid-circuit measurement values.""" shots = 1000 rng = np.random.default_rng(123) samples = rng.choice([0, 1], size=(shots, 2)).astype(np.int64) m0 = qml.measure(0) m1 = qml.measure(1) result = qml.counts(op=m0 | m1).process_samples(samples, wire_order=[0, 1]) assert len(result) == 2 assert set(result.keys()) == {0, 1} samples = np.apply_along_axis((lambda x: x[0] | x[1]), axis=1, arr=samples) assert result[0] == np.count_nonzero(samples == 0) assert result[1] == np.count_nonzero(samples == 1) def test_counts_shape_measurement_value_list(self): """Test that the counts output is correct for list mid-circuit measurement values.""" shots = 1000 rng = np.random.default_rng(123) samples = rng.choice([0, 1], size=(shots, 2)).astype(np.int64) m0 = qml.measure(0) m1 = qml.measure(1) result = qml.counts(op=[m0, m1]).process_samples(samples, wire_order=[0, 1]) assert len(result) == 4 assert set(result.keys()) == {"00", "01", "10", "11"} assert result["00"] == np.count_nonzero([np.allclose(s, [0, 0]) for s in samples]) assert result["01"] == np.count_nonzero([np.allclose(s, [0, 1]) for s in samples]) assert result["10"] == np.count_nonzero([np.allclose(s, [1, 0]) for s in samples]) assert result["11"] == np.count_nonzero([np.allclose(s, [1, 1]) for s in samples]) def test_mixed_lists_as_op_not_allowed(self): """Test that passing a list not containing only measurement values raises an error.""" m0 = qml.measure(0) with pytest.raises( qml.QuantumFunctionError, match="Only sequences of single MeasurementValues can be passed with the op argument", ): _ = qml.counts(op=[m0, qml.PauliZ(0)]) def test_composed_measurement_value_lists_not_allowed(self): """Test that passing a list containing measurement values composed with arithmetic raises an error.""" m0 = qml.measure(0) m1 = qml.measure(1) m2 = qml.measure(2) with pytest.raises( qml.QuantumFunctionError, match="Only sequences of single MeasurementValues can be passed with the op argument", ): _ = qml.counts(op=[m0 + m1, m2]) def test_counts_all_outcomes_wires(self): """Test that the counts output is correct when all_outcomes is passed""" shots = 1000 samples = np.zeros((shots, 2)).astype(np.int64) result1 = qml.counts(wires=0, all_outcomes=False).process_samples(samples, wire_order=[0]) assert len(result1) == 1 assert set(result1.keys()) == {"0"} assert result1["0"] == shots result2 = qml.counts(wires=0, all_outcomes=True).process_samples(samples, wire_order=[0]) assert len(result2) == 2 assert set(result2.keys()) == {"0", "1"} assert result2["0"] == shots assert result2["1"] == 0 def test_counts_all_outcomes_obs(self): """Test that the counts output is correct when all_outcomes is passed""" shots = 1000 samples = np.zeros((shots, 2)).astype(np.int64) result1 = qml.counts(qml.PauliZ(0), all_outcomes=False).process_samples( samples, wire_order=[0] ) assert len(result1) == 1 assert set(result1.keys()) == {1} assert result1[1] == shots result2 = qml.counts(qml.PauliZ(0), all_outcomes=True).process_samples( samples, wire_order=[0] ) assert len(result2) == 2 assert set(result2.keys()) == {1, -1} assert result2[1] == shots assert result2[-1] == 0 def test_counts_all_outcomes_measurement_value(self): """Test that the counts output is correct when all_outcomes is passed for mid-circuit measurement values.""" shots = 1000 samples = np.zeros((shots, 2)).astype(np.int64) mv = qml.measure(0) result1 = qml.counts(mv, all_outcomes=False).process_samples(samples, wire_order=[0]) assert len(result1) == 1 assert set(result1.keys()) == {0} assert result1[0] == shots result2 = qml.counts(mv, all_outcomes=True).process_samples(samples, wire_order=[0]) assert len(result2) == 2 assert set(result2.keys()) == {0, 1} assert result2[0] == shots assert result2[1] == 0 def test_counts_all_outcomes_composite_measurement_value(self): """Test that the counts output is correct when all_outcomes is passed for composite mid-circuit measurement values.""" shots = 1000 samples = np.zeros((shots, 2)).astype(np.int64) m0 = qml.measure(0) m1 = qml.measure(1) mv = (m0 - 1) * 2 * (m1 + 1) - 2 # 00 equates to -4 result1 = qml.counts(mv, all_outcomes=False).process_samples(samples, wire_order=[0, 1]) assert len(result1) == 1 assert set(result1.keys()) == {-4} assert result1[-4] == shots result2 = qml.counts(mv, all_outcomes=True).process_samples(samples, wire_order=[0, 1]) # Possible outcomes are -4, -6, -2 assert len(result2) == 3 assert set(result2.keys()) == {-6, -4, -2} assert result2[-4] == shots assert result2[-6] == result2[-2] == 0 def test_counts_all_outcomes_measurement_value_list(self): """Test that the counts output is correct when all_outcomes is passed for a list of mid-circuit measurement values.""" shots = 1000 samples = np.zeros((shots, 2)).astype(np.int64) m0 = qml.measure(0) m1 = qml.measure(1) result1 = qml.counts([m0, m1], all_outcomes=False).process_samples( samples, wire_order=[0, 1] ) assert len(result1) == 1 assert set(result1.keys()) == {"00"} assert result1["00"] == shots result2 = qml.counts([m0, m1], all_outcomes=True).process_samples( samples, wire_order=[0, 1] ) assert len(result2) == 4 assert set(result2.keys()) == {"00", "01", "10", "11"} assert result2["00"] == shots assert result2["01"] == 0 assert result2["10"] == 0 assert result2["11"] == 0 class TestCountsIntegration: # pylint:disable=too-many-public-methods,not-an-iterable def test_counts_dimension(self): """Test that the counts function outputs counts of the right size""" n_sample = 10 dev = qml.device("default.qubit", wires=2, shots=n_sample) @qml.qnode(dev) def circuit(): qml.RX(0.54, wires=0) return qml.counts(qml.PauliZ(0)), qml.counts(qml.PauliX(1)) sample = circuit() assert len(sample) == 2 assert np.all([sum(s.values()) == n_sample for s in sample]) def test_batched_counts_dimension(self): """Test that the counts function outputs counts of the right size with batching""" n_sample = 10 dev = qml.device("default.qubit", wires=2, shots=n_sample) @qml.qnode(dev) def circuit(): qml.RX([0.54, 0.65], wires=0) return qml.counts(qml.PauliZ(0)), qml.counts(qml.PauliX(1)) sample = circuit() assert isinstance(sample, tuple) assert len(sample) == 2 assert np.all([sum(s.values()) == n_sample for batch in sample for s in batch]) def test_counts_combination(self): """Test the output of combining expval, var and counts""" n_sample = 10 dev = qml.device("default.qubit", wires=3, shots=n_sample) @qml.qnode(dev, diff_method="parameter-shift") def circuit(): qml.RX(0.54, wires=0) return ( qml.counts(qml.PauliZ(0)), qml.expval(qml.PauliX(1)), qml.var(qml.PauliY(2)), ) result = circuit() assert len(result) == 3 assert sum(result[0].values()) == n_sample def test_single_wire_counts(self): """Test the return type and shape of sampling counts from a single wire""" n_sample = 10 dev = qml.device("default.qubit", wires=1, shots=n_sample) @qml.qnode(dev) def circuit(): qml.RX(0.54, wires=0) return qml.counts(qml.PauliZ(0)) result = circuit() assert isinstance(result, dict) assert sum(result.values()) == n_sample def test_multi_wire_counts_regular_shape(self): """Test the return type and shape of sampling multiple wires where a rectangular array is expected""" n_sample = 10 dev = qml.device("default.qubit", wires=3, shots=n_sample) @qml.qnode(dev) def circuit(): return ( qml.counts(qml.PauliZ(0)), qml.counts(qml.PauliZ(1)), qml.counts(qml.PauliZ(2)), ) result = circuit() # If all the dimensions are equal the result will end up to be a proper rectangular array assert isinstance(result, tuple) assert len(result) == 3 assert all(sum(r.values()) == n_sample for r in result) assert all(all(v.dtype == np.dtype("int") for v in r.values()) for r in result) def test_observable_return_type_is_counts(self): """Test that the return type of the observable is :attr:`ObservableReturnTypes.Counts`""" n_shots = 10 dev = qml.device("default.qubit", wires=1, shots=n_shots) @qml.qnode(dev) def circuit(): res = qml.counts(qml.PauliZ(0)) return res circuit() assert circuit._qfunc_output.return_type is Counts # pylint: disable=protected-access def test_providing_no_observable_and_no_wires_counts(self): """Test that we can provide no observable and no wires to sample function""" dev = qml.device("default.qubit", wires=2, shots=1000) @qml.qnode(dev) def circuit(): qml.Hadamard(wires=0) res = qml.counts() assert res.obs is None assert res.wires == qml.wires.Wires([]) return res circuit() def test_providing_no_observable_and_wires_counts(self): """Test that we can provide no observable but specify wires to the sample function""" wires = [0, 2] wires_obj = qml.wires.Wires(wires) dev = qml.device("default.qubit", wires=3, shots=1000) @qml.qnode(dev) def circuit(): qml.Hadamard(wires=0) res = qml.counts(wires=wires) assert res.obs is None assert res.wires == wires_obj return res circuit() def test_batched_counts_work_individually(self): """Test that each counts call operates independently""" n_shots = 10 dev = qml.device("default.qubit", wires=1, shots=n_shots) @qml.qnode(dev) def circuit(): qml.pow(qml.PauliX(0), z=[1, 2]) return qml.counts() assert circuit() == [{"1": 10}, {"0": 10}] @pytest.mark.all_interfaces @pytest.mark.parametrize("wires, basis_state", [(None, "010"), ([2, 1], "01")]) @pytest.mark.parametrize("interface", ["autograd", "jax", "tensorflow", "torch"]) def test_counts_no_op_finite_shots(self, interface, wires, basis_state): """Check all interfaces with computational basis state counts and finite shot""" n_shots = 10 dev = qml.device("default.qubit", wires=3, shots=n_shots) @qml.qnode(dev, interface=interface) def circuit(): qml.PauliX(1) return qml.counts(wires=wires) res = circuit() assert res == {basis_state: n_shots} assert qml.math.get_interface(res[basis_state]) == interface @pytest.mark.all_interfaces @pytest.mark.parametrize("interface", ["autograd", "jax", "tensorflow", "torch"]) def test_counts_operator_finite_shots(self, interface): """Check all interfaces with observable measurement counts and finite shot""" n_shots = 10 dev = qml.device("default.qubit", wires=3, shots=n_shots) @qml.qnode(dev, interface=interface) def circuit(): return qml.counts(qml.PauliZ(0)) res = circuit() assert res == {1: n_shots} @pytest.mark.all_interfaces @pytest.mark.parametrize("shot_vec", [(1, 10, 10), (1, 10, 1000)]) @pytest.mark.parametrize("wires, basis_state", [(None, "010"), ([2, 1], "01")]) @pytest.mark.parametrize("interface", ["autograd", "jax", "tensorflow", "torch"]) def test_counts_binned( self, shot_vec, interface, wires, basis_state ): # pylint:disable=too-many-arguments """Check all interfaces with computational basis state counts and different shot vectors""" dev = qml.device("default.qubit", wires=3, shots=shot_vec) @qml.qnode(dev, interface=interface) def circuit(): qml.PauliX(1) return qml.counts(wires=wires) res = circuit() assert isinstance(res, tuple) assert res[0] == {basis_state: shot_vec[0]} assert res[1] == {basis_state: shot_vec[1]} assert res[2] == {basis_state: shot_vec[2]} assert len(res) == len(shot_vec) assert sum(sum(res_bin.values()) for res_bin in res) == sum(shot_vec) @pytest.mark.all_interfaces @pytest.mark.parametrize("shot_vec", [(1, 10, 10), (1, 10, 1000)]) @pytest.mark.parametrize("interface", ["autograd", "jax", "tensorflow", "torch"]) def test_counts_operator_binned(self, shot_vec, interface): """Check all interfaces with observable measurement counts and different shot vectors""" dev = qml.device("default.qubit", wires=3, shots=shot_vec) @qml.qnode(dev, interface=interface) def circuit(): return qml.counts(qml.PauliZ(0)) res = circuit() assert isinstance(res, tuple) assert res[0] == {1: shot_vec[0]} assert res[1] == {1: shot_vec[1]} assert res[2] == {1: shot_vec[2]} assert len(res) == len(shot_vec) assert sum(sum(res_bin.values()) for res_bin in res) == sum(shot_vec) @pytest.mark.parametrize("shot_vec", [(1, 10, 10), (1, 10, 1000)]) def test_counts_binned_4_wires(self, shot_vec): """Check the autograd interface with computational basis state counts and different shot vectors on a device with 4 wires""" dev = qml.device("default.qubit", wires=4, shots=shot_vec) @qml.qnode(dev, interface="autograd") def circuit(): qml.PauliX(1) qml.PauliX(2) qml.PauliX(3) return qml.counts() res = circuit() basis_state = "0111" assert isinstance(res, tuple) assert res[0][basis_state] == shot_vec[0] assert res[1][basis_state] == shot_vec[1] assert res[2][basis_state] == shot_vec[2] assert len(res) == len(shot_vec) assert sum(sum(res_bin.values()) for res_bin in res) == sum(shot_vec) @pytest.mark.parametrize("shot_vec", [(1, 10, 10), (1, 10, 1000)]) def test_counts_operator_binned_4_wires(self, shot_vec): """Check the autograd interface with observable samples to obtain counts from and different shot vectors on a device with 4 wires""" dev = qml.device("default.qubit", wires=4, shots=shot_vec) @qml.qnode(dev, interface="autograd") def circuit(): qml.PauliX(1) qml.PauliX(2) qml.PauliX(3) return qml.counts(qml.PauliZ(0)) res = circuit() sample = 1 assert isinstance(res, tuple) assert res[0][sample] == shot_vec[0] assert res[1][sample] == shot_vec[1] assert res[2][sample] == shot_vec[2] assert len(res) == len(shot_vec) assert sum(sum(res_bin.values()) for res_bin in res) == sum(shot_vec) meas2 = [ qml.expval(qml.PauliZ(0)), qml.var(qml.PauliZ(0)), qml.probs(wires=[1, 0]), qml.sample(wires=1), ] @pytest.mark.all_interfaces @pytest.mark.parametrize("interface", ["autograd", "jax", "tensorflow", "torch"]) @pytest.mark.parametrize("meas2", meas2) @pytest.mark.parametrize("shots", [1000, (1, 10)]) def test_counts_observable_finite_shots(self, interface, meas2, shots): """Check all interfaces with observable measurement counts and finite shot""" dev = qml.device("default.qubit", wires=3, shots=shots) if isinstance(shots, tuple) and interface == "torch": pytest.skip("Torch needs to be updated for shot vectors.") @qml.qnode(dev, interface=interface) def circuit(): qml.PauliX(0) return qml.counts(wires=0), qml.apply(meas2) res = circuit() assert isinstance(res, tuple) num_shot_bins = 1 if isinstance(shots, int) else len(shots) if num_shot_bins == 1: counts_term_indices = [i * 2 for i in range(num_shot_bins)] for ind in counts_term_indices: assert isinstance(res[ind], dict) else: assert len(res) == 2 assert isinstance(res[0], tuple) assert isinstance(res[0][0], dict) assert isinstance(res[1], tuple) assert isinstance(res[1][0], dict) def test_all_outcomes_kwarg_providing_observable(self): """Test that the dictionary keys *all* eigenvalues of the observable, including 0 count values, if observable is given and all_outcomes=True""" n_shots = 10 dev = qml.device("default.qubit", wires=1, shots=n_shots) @qml.qnode(dev) def circuit(): res = qml.counts(qml.PauliZ(0), all_outcomes=True) return res res = circuit() assert res == {1: n_shots, -1: 0} def test_all_outcomes_kwarg_no_observable_no_wires(self): """Test that the dictionary keys are *all* the possible combinations of basis states for the device, including 0 count values, if no wire count and no observable are given and all_outcomes=True""" n_shots = 10 dev = qml.device("default.qubit", wires=2, shots=n_shots) @qml.qnode(dev) def circuit(): return qml.counts(all_outcomes=True) res = circuit() assert res == {"00": n_shots, "01": 0, "10": 0, "11": 0} def test_all_outcomes_kwarg_providing_wires_and_no_observable(self): """Test that the dictionary keys are *all* possible combinations of basis states for the specified wires, including 0 count values, if wire count is given and all_outcomes=True""" n_shots = 10 dev = qml.device("default.qubit", wires=4, shots=n_shots) @qml.qnode(dev) def circuit(): return qml.counts(wires=[0, 2], all_outcomes=True) res = circuit() assert res == {"00": n_shots, "01": 0, "10": 0, "11": 0} def test_all_outcomes_hermitian(self): """Tests that the all_outcomes=True option for counts works with the qml.Hermitian observable""" n_shots = 10 dev = qml.device("default.qubit", wires=2, shots=n_shots) A = np.array([[1, 0], [0, -1]]) @qml.qnode(dev) def circuit(x): return qml.counts(qml.Hermitian(x, wires=0), all_outcomes=True) res = circuit(A) assert res == {-1.0: 0, 1.0: n_shots} def test_all_outcomes_multiple_measurements(self): """Tests that the all_outcomes=True option for counts works when multiple measurements are performed""" dev = qml.device("default.qubit", wires=2, shots=10) @qml.qnode(dev) def circuit(): return qml.sample(qml.PauliZ(0)), qml.counts(), qml.counts(all_outcomes=True) res = circuit() assert len(res[0]) == 10 assert res[1] == {"00": 10} assert res[2] == {"00": 10, "01": 0, "10": 0, "11": 0} def test_batched_all_outcomes(self): """Tests that all_outcomes=True works with broadcasting.""" n_shots = 10 dev = qml.device("default.qubit", wires=1, shots=n_shots) @qml.qnode(dev) def circuit(): qml.pow(qml.PauliX(0), z=[1, 2]) return qml.counts(qml.PauliZ(0), all_outcomes=True) assert circuit() == [{1: 0, -1: n_shots}, {1: n_shots, -1: 0}] def test_counts_empty_wires(self): """Test that using ``qml.counts`` with an empty wire list raises an error.""" with pytest.raises(ValueError, match="Cannot set an empty list of wires."): qml.counts(wires=[]) @pytest.mark.parametrize("shots", [1, 100]) def test_counts_no_arguments(self, shots): """Test that using ``qml.counts`` with no arguments returns the counts of all wires.""" dev = qml.device("default.qubit", wires=3, shots=shots) @qml.qnode(dev) def circuit(): return qml.counts() res = circuit() assert qml.math.allequal(res, {"000": shots}) @pytest.mark.all_interfaces @pytest.mark.parametrize("wires, basis_state", [(None, "010"), ([2, 1], "01")]) @pytest.mark.parametrize("interface", ["autograd", "jax", "tensorflow", "torch"]) def test_counts_no_op_finite_shots(interface, wires, basis_state): """Check all interfaces with computational basis state counts and finite shot""" n_shots = 10 dev = qml.device("default.qubit", wires=3, shots=n_shots) @qml.qnode(dev, interface=interface) def circuit(): qml.PauliX(1) return qml.counts(wires=wires) res = circuit() assert res == {basis_state: n_shots} assert qml.math.get_interface(res[basis_state]) == interface @pytest.mark.all_interfaces @pytest.mark.parametrize("wires, basis_states", [(None, ("010", "000")), ([2, 1], ("01", "00"))]) @pytest.mark.parametrize("interface", ["autograd", "jax", "tensorflow", "torch"]) def test_batched_counts_no_op_finite_shots(interface, wires, basis_states): """Check all interfaces with computational basis state counts and finite shot""" n_shots = 10 dev = qml.device("default.qubit", wires=3, shots=n_shots) @qml.qnode(dev, interface=interface) def circuit(): qml.pow(qml.PauliX(1), z=[1, 2]) return qml.counts(wires=wires) res = circuit() assert res == type(res)([{basis_state: n_shots} for basis_state in basis_states]) @pytest.mark.all_interfaces @pytest.mark.parametrize("wires, basis_states", [(None, ("010", "000")), ([2, 1], ("01", "00"))]) @pytest.mark.parametrize("interface", ["autograd", "jax", "tensorflow", "torch"]) def test_batched_counts_and_expval_no_op_finite_shots(interface, wires, basis_states): """Check all interfaces with computational basis state counts and finite shot""" n_shots = 10 dev = qml.device("default.qubit", wires=3, shots=n_shots) @qml.qnode(dev, interface=interface) def circuit(): qml.pow(qml.PauliX(1), z=[1, 2]) return qml.counts(wires=wires), qml.expval(qml.PauliZ(0)) res = circuit() assert isinstance(res, tuple) and len(res) == 2 for i, basis_state in enumerate(basis_states): assert list(res[0][i].keys()) == [basis_state] assert qml.math.allequal(list(res[0][i].values()), n_shots) # assert res[0] == [{basis_state: expected_n_shots} for basis_state in basis_states] assert len(res[1]) == 2 and qml.math.allequal(res[1], 1) @pytest.mark.all_interfaces @pytest.mark.parametrize("interface", ["autograd", "jax", "tensorflow", "torch"]) def test_batched_counts_operator_finite_shots(interface): """Check all interfaces with observable measurement counts, batching and finite shots""" n_shots = 10 dev = qml.device("default.qubit", wires=3, shots=n_shots) @qml.qnode(dev, interface=interface) def circuit(): qml.pow(qml.PauliX(0), z=[1, 2]) return qml.counts(qml.PauliZ(0)) res = circuit() assert res == type(res)([{-1: n_shots}, {1: n_shots}]) @pytest.mark.all_interfaces @pytest.mark.parametrize("interface", ["autograd", "jax", "tensorflow", "torch"]) def test_batched_counts_and_expval_operator_finite_shots(interface): """Check all interfaces with observable measurement counts, batching and finite shots""" n_shots = 10 dev = qml.device("default.qubit", wires=3, shots=n_shots) @qml.qnode(dev, interface=interface) def circuit(): qml.pow(qml.PauliX(0), z=[1, 2]) return qml.counts(qml.PauliZ(0)), qml.expval(qml.PauliZ(0)) res = circuit() assert isinstance(res, tuple) and len(res) == 2 assert res[0] == type(res[0])([{-1: n_shots}, {1: n_shots}]) assert len(res[1]) == 2 and qml.math.allequal(res[1], [-1, 1]) class TestProcessCounts: """Unit tests for the counts.process_counts method""" @pytest.mark.parametrize("all_outcomes", [True, False]) def test_should_not_modify_counts_dictionary(self, all_outcomes): """Tests that count dictionary is not modified""" counts = {"000": 100, "100": 100} expected = counts.copy() wire_order = qml.wires.Wires((0, 1, 2)) qml.counts(wires=(0, 1), all_outcomes=all_outcomes).process_counts(counts, wire_order) assert counts == expected def test_all_outcomes_is_true(self): """When all_outcomes is True, 0 count should be added to missing outcomes in the counts dictionary""" counts_to_process = {"00": 100, "10": 100} wire_order = qml.wires.Wires((0, 1)) actual = qml.counts(wires=wire_order, all_outcomes=True).process_counts( counts_to_process, wire_order=wire_order ) expected_counts = {"00": 100, "01": 0, "10": 100, "11": 0} assert actual == expected_counts def test_all_outcomes_is_false(self): """When all_outcomes is True, 0 count should be removed from the counts dictionary""" counts_to_process = {"00": 0, "01": 0, "10": 0, "11": 100} wire_order = qml.wires.Wires((0, 1)) actual = qml.counts(wires=wire_order, all_outcomes=False).process_counts( counts_to_process, wire_order=wire_order ) expected_counts = {"11": 100} assert actual == expected_counts @pytest.mark.parametrize( "wires, expected", [ ((0, 1), {"00": 100, "10": 100}), ((1, 0), {"00": 100, "01": 100}), ], ) def test_wire_order(self, wires, expected): """Test impact of wires in qml.counts""" counts = {"000": 100, "100": 100} wire_order = qml.wires.Wires((0, 1, 2)) actual = qml.counts(wires=wires, all_outcomes=False).process_counts(counts, wire_order) assert actual == expected @pytest.mark.parametrize("all_outcomes", [True, False]) def test_process_count_returns_same_count_dictionary(self, all_outcomes): """ Test that process_count returns same dictionary when all outcomes are in count dictionary and wire_order is same """ expected = {"0": 100, "1": 100} wires = qml.wires.Wires(0) actual = qml.counts(wires=wires, all_outcomes=all_outcomes).process_counts(expected, wires) assert actual == expected
pennylane/tests/measurements/test_counts.py/0
{ "file_path": "pennylane/tests/measurements/test_counts.py", "repo_id": "pennylane", "token_count": 16094 }
84
# Copyright 2018-2020 Xanadu Quantum Technologies Inc. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Unit tests for ensuring that objects that are pickled/unpickled are identical to the original. """ import pickle import pennylane as qml def test_unpickling_tensor(): """Tests whether qml.numpy.tensor objects are pickleable.""" x = qml.numpy.random.random(15) x_str = pickle.dumps(x) x_reloaded = pickle.loads(x_str) assert qml.numpy.allclose(x, x_reloaded) assert x.__dict__ == x_reloaded.__dict__ assert hasattr(x_reloaded, "requires_grad")
pennylane/tests/numpy/test_pickling.py/0
{ "file_path": "pennylane/tests/numpy/test_pickling.py", "repo_id": "pennylane", "token_count": 336 }
85
# Copyright 2018-2021 Xanadu Quantum Technologies Inc. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Unit tests for the qml.simplify function """ # pylint: disable=too-few-public-methods import pytest import pennylane as qml from pennylane import numpy as np from pennylane.tape import QuantumScript def build_op(): """Return function to build nested operator.""" return qml.adjoint( qml.prod( qml.RX(1, 0) ** 1, qml.RY(1, 0), qml.prod(qml.adjoint(qml.PauliX(0)), qml.RZ(1, 0)), qml.RX(1, 0), ) ) simplified_op = qml.prod( qml.RX(4 * np.pi - 1, 0), qml.RZ(4 * np.pi - 1, 0), qml.PauliX(0), qml.RY(4 * np.pi - 1, 0), qml.RX(4 * np.pi - 1, 0), ) class TestSimplifyOperators: """Tests for the qml.simplify method used with operators.""" def test_simplify_method_with_default_depth(self): """Test simplify method with default depth.""" op = build_op() s_op = qml.simplify(op) assert isinstance(s_op, qml.ops.Prod) # pylint: disable=no-member assert s_op.data == simplified_op.data assert s_op.wires == simplified_op.wires assert s_op.arithmetic_depth == simplified_op.arithmetic_depth def test_simplify_method_with_queuing(self): """Test the simplify method while queuing.""" with qml.queuing.AnnotatedQueue() as q: op = build_op() s_op = qml.simplify(op) assert len(q) == 1 assert q.queue[0] is s_op def test_simplify_unsupported_object_raises_error(self): """Test that an error is raised when trying to simplify an unsupported object.""" with pytest.raises(ValueError, match="Cannot simplify the object"): qml.simplify("unsupported type") @pytest.mark.jax def test_jit_simplification(self): """Test that simplification can be jitted.""" import jax sum_op = qml.sum(qml.PauliX(0), qml.PauliX(0)) simp_op = jax.jit(qml.simplify)(sum_op) qml.assert_equal( simp_op, qml.s_prod(2.0, qml.PauliX(0)), check_interface=False, check_trainability=False ) class TestSimplifyTapes: """Tests for the qml.simplify method used with tapes.""" @pytest.mark.parametrize("shots", [None, 100]) def test_simplify_tape(self, shots): """Test the simplify method with a tape.""" with qml.queuing.AnnotatedQueue() as q_tape: build_op() tape = QuantumScript.from_queue(q_tape, shots=shots) [s_tape], _ = qml.simplify(tape) assert len(s_tape) == 1 s_op = s_tape[0] assert isinstance(s_op, qml.ops.Prod) # pylint: disable=no-member assert s_op.data == simplified_op.data assert s_op.wires == simplified_op.wires assert s_op.arithmetic_depth == simplified_op.arithmetic_depth assert tape.shots == s_tape.shots def test_execute_simplified_tape(self): """Test the execution of a simplified tape.""" dev = qml.device("default.qubit", wires=2) with qml.queuing.AnnotatedQueue() as q_tape: qml.prod(qml.prod(qml.PauliX(0) ** 1, qml.PauliX(0)), qml.PauliZ(1)) qml.expval(op=qml.PauliZ(1)) tape = QuantumScript.from_queue(q_tape) simplified_tape_op = qml.PauliZ(1) [s_tape], _ = qml.simplify(tape) s_op = s_tape.operations[0] assert isinstance(s_op, qml.PauliZ) assert s_op.data == simplified_tape_op.data assert s_op.wires == simplified_tape_op.wires assert s_op.arithmetic_depth == simplified_tape_op.arithmetic_depth assert dev.execute(tape) == dev.execute(s_tape) class TestSimplifyQNodes: """Tests for the qml.simplify method used with qnodes.""" def test_simplify_qnode(self): """Test the simplify method with a qnode.""" dev = qml.device("default.qubit", wires=2) @qml.qnode(dev) def qnode(): qml.prod(qml.prod(qml.PauliX(0) ** 1, qml.PauliX(0)), qml.PauliZ(1)) return qml.expval( op=qml.prod(qml.prod(qml.PauliX(0) ** 1, qml.PauliX(0)), qml.PauliZ(1)) ) simplified_tape_op = qml.PauliZ(1) s_qnode = qml.simplify(qnode) assert s_qnode() == qnode() [s_tape], _ = s_qnode.transform_program([s_qnode.tape]) assert len(s_tape) == 2 s_op = s_tape.operations[0] s_obs = s_tape.observables[0] assert isinstance(s_op, qml.PauliZ) assert s_op.data == simplified_tape_op.data assert s_op.wires == simplified_tape_op.wires assert s_op.arithmetic_depth == simplified_tape_op.arithmetic_depth assert isinstance(s_obs, qml.PauliZ) assert s_obs.data == simplified_tape_op.data assert s_obs.wires == simplified_tape_op.wires assert s_obs.arithmetic_depth == simplified_tape_op.arithmetic_depth class TestSimplifyCallables: """Tests for the qml.simplify method used with callables.""" def test_simplify_qfunc(self): """Test the simplify method with a qfunc.""" dev = qml.device("default.qubit", wires=2) def qfunc(): qml.prod(qml.prod(qml.PauliX(0) ** 1, qml.PauliX(0)), qml.PauliZ(1)) return qml.probs(wires=0) simplified_tape_op = qml.PauliZ(1) s_qfunc = qml.simplify(qfunc) qnode = qml.QNode(qfunc, dev) s_qnode = qml.QNode(s_qfunc, dev) assert (s_qnode() == qnode()).all() assert len(s_qnode.tape) == 2 s_op = s_qnode.tape.operations[0] assert isinstance(s_op, qml.PauliZ) assert s_op.data == simplified_tape_op.data assert s_op.wires == simplified_tape_op.wires assert s_op.arithmetic_depth == simplified_tape_op.arithmetic_depth @pytest.mark.jax def test_jitting_simplified_qfunc(self): """Test that we can jit qnodes that have a simplified quantum function.""" import jax @jax.jit @qml.qnode(qml.device("default.qubit", wires=1)) @qml.simplify def circuit(x): qml.adjoint(qml.RX(x, wires=0)) _ = qml.PauliX(0) ** 2 return qml.expval(qml.PauliY(0)) x = jax.numpy.array(4 * jax.numpy.pi + 0.1) res = circuit(x) assert qml.math.allclose(res, jax.numpy.sin(x)) grad = jax.grad(circuit)(x) assert qml.math.allclose(grad, jax.numpy.cos(x))
pennylane/tests/ops/functions/test_simplify.py/0
{ "file_path": "pennylane/tests/ops/functions/test_simplify.py", "repo_id": "pennylane", "token_count": 3283 }
86
# Copyright 2018-2022 Xanadu Quantum Technologies Inc. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Unit tests for the SymbolicOp class of qubit operations""" from copy import copy import pytest import pennylane as qml from pennylane import numpy as np from pennylane.operation import Operator from pennylane.ops.op_math import ScalarSymbolicOp, SymbolicOp from pennylane.wires import Wires class TempScalar(ScalarSymbolicOp): # pylint:disable=too-few-public-methods """Temporary scalar symbolic op class.""" _name = "TempScalar" @staticmethod def _matrix(scalar, mat): pass class TempScalarCopy(ScalarSymbolicOp): # pylint:disable=too-few-public-methods """Copy of temporary scalar symbolic op class.""" _name = "TempScalarCopy" @staticmethod def _matrix(scalar, mat): pass def test_intialization(): """Test initialization for a SymbolicOp""" base = Operator("a") op = SymbolicOp(base, id="something") assert op.base is base assert op.hyperparameters["base"] is base assert op.id == "something" assert op.name == "Symbolic" def test_copy(): """Test that a copy of the operator can have its parameters updated independently of the original operator.""" param1 = 1.234 base = Operator(param1, "a") op = SymbolicOp(base) copied_op = copy(op) assert copied_op.__class__ is op.__class__ assert copied_op.data == (param1,) copied_op.data = (6.54,) assert op.data == (param1,) def test_map_wires(): """Test the map_wires method.""" base = Operator("a") op = SymbolicOp(base, id="something") # pylint:disable=attribute-defined-outside-init,protected-access op._pauli_rep = qml.pauli.PauliSentence({qml.pauli.PauliWord({"a": "X"}): 1}) wire_map = {"a": 5} mapped_op = op.map_wires(wire_map=wire_map) assert op.wires == Wires("a") assert op.base.wires == Wires("a") assert mapped_op.wires == Wires(5) assert mapped_op.base.wires == Wires(5) assert mapped_op.pauli_rep is not op.pauli_rep assert mapped_op.pauli_rep == qml.pauli.PauliSentence({qml.pauli.PauliWord({5: "X"}): 1}) class TestProperties: """Test the properties of the symbolic op.""" # pylint:disable=too-few-public-methods def test_data(self): """Test that the data property for symbolic ops allows for the getting and setting of the base operator's data.""" x = np.array(1.234) base = Operator(x, "a") op = SymbolicOp(base) assert op.data == (x,) # update parameters through op x_new = np.array(2.345) op.data = (x_new,) assert base.data == (x_new,) assert op.data == (x_new,) # update base data updates symbolic data x_new2 = np.array(3.45) base.data = (x_new2,) assert op.data == (x_new2,) def test_parameters(self): """Test parameter property is a list of the base's trainable parameters.""" x = np.array(9.876) base = Operator(x, "b") op = SymbolicOp(base) assert op.parameters == [x] def test_num_params(self): """Test symbolic ops defer num-params to those of the base operator.""" base = Operator(1.234, 3.432, 0.5490, 8.789453, wires="b") op = SymbolicOp(base) assert op.num_params == base.num_params == 4 @pytest.mark.parametrize("has_mat", (True, False)) def test_has_matrix(self, has_mat): """Test that a symbolic op has a matrix if its base has a matrix.""" class DummyOp(Operator): has_matrix = has_mat base = DummyOp("b") op = SymbolicOp(base) assert op.has_matrix == has_mat def test_has_matrix_hamiltonian(self): """Test that it has a matrix if the base is a hamiltonian.""" H = qml.Hamiltonian([1.0], [qml.PauliX(0)]) op = TempScalar(H, 2) assert op.has_matrix @pytest.mark.parametrize("is_herm", (True, False)) def test_is_hermitian(self, is_herm): """Test that symbolic op is hermitian if the base is hermitian.""" class DummyOp(Operator): is_hermitian = is_herm base = DummyOp("b") op = SymbolicOp(base) assert op.is_hermitian == is_herm @pytest.mark.parametrize("queue_cat", ("_ops", None)) def test_queuecateory(self, queue_cat): """Test that a symbolic operator inherits the queue_category from its base.""" class DummyOp(Operator): _queue_category = queue_cat op = SymbolicOp(DummyOp("b")) assert op._queue_category == queue_cat # pylint:disable=protected-access def test_map_wires(self): """Test that base wires can be set through the operator's private `_wires` property.""" w = qml.wires.Wires("a") base = Operator(w) op = SymbolicOp(base) new_op = op.map_wires(wire_map={"a": "c"}) assert new_op.wires == Wires("c") def test_num_wires(self): """Test that the number of wires is the length of the `wires` property, rather than the `num_wires` set by the base.""" t = Operator(wires=(0, 1, 2)) op = SymbolicOp(t) assert op.num_wires == 3 def test_pauli_rep(self): """Test that pauli_rep is None by default""" base = Operator("a") op = SymbolicOp(base) assert op.pauli_rep is None class TestQueuing: """Test that Symbolic Operators queue and update base metadata.""" def test_queuing(self): """Test symbolic op queues and updates base metadata.""" with qml.queuing.AnnotatedQueue() as q: base = Operator("a") op = SymbolicOp(base) assert base not in q assert q.queue[0] is op assert len(q) == 1 def test_queuing_base_defined_outside(self): """Test symbolic op queues without adding base to the queue if it isn't already in the queue.""" base = Operator("b") with qml.queuing.AnnotatedQueue() as q: op = SymbolicOp(base) assert len(q) == 1 assert q.queue[0] is op class TestScalarSymbolicOp: """Tests for the ScalarSymbolicOp class.""" def test_init(self): base = Operator(1.1, wires=[0]) scalar = 2.2 op = TempScalar(base, scalar) assert isinstance(op.scalar, float) assert op.scalar == 2.2 assert op.data == (2.2, 1.1) base = Operator(1.1, wires=[0]) scalar = [2.2, 3.3] op = TempScalar(base, scalar) assert isinstance(op.scalar, np.ndarray) assert np.all(op.scalar == [2.2, 3.3]) assert np.all(op.data[0] == op.scalar) assert op.data[1] == 1.1 def test_data(self): """Tests the data property.""" op = TempScalar(Operator(1.1, wires=[0]), 2.2) assert op.scalar == 2.2 assert op.data == (2.2, 1.1) # check setting through ScalarSymbolicOp op.data = (3.3, 4.4) # pylint:disable=attribute-defined-outside-init assert op.data == (3.3, 4.4) assert op.scalar == 3.3 assert op.base.data == (4.4,) # check setting through base op.base.data = (5.5,) assert op.data == (3.3, 5.5) assert op.scalar == 3.3 assert op.base.data == (5.5,) def test_hash(self): """Test that a hash correctly identifies ScalarSymbolicOps.""" op0 = TempScalar(Operator(1.1, wires=[0]), 0.3) op1 = TempScalar(Operator(1.1, wires=[0]), 0.3) op2 = TempScalar(Operator(1.1, wires=[0]), 0.6) op3 = TempScalar(Operator(1.2, wires=[0]), 0.3) op4 = TempScalarCopy(Operator(1.1, wires=[0]), 0.3) assert op0.hash == op1.hash for second_op in [op2, op3, op4]: assert op0.hash != second_op.hash
pennylane/tests/ops/op_math/test_symbolic_op.py/0
{ "file_path": "pennylane/tests/ops/op_math/test_symbolic_op.py", "repo_id": "pennylane", "token_count": 3573 }
87
# Copyright 2018-2022 Xanadu Quantum Technologies Inc. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Unit tests for qutrit observables.""" import functools from unittest.mock import PropertyMock, patch import numpy as np import pytest from gate_data import GELL_MANN import pennylane as qml # pylint: disable=protected-access, unused-argument # Hermitian matrices, their corresponding eigenvalues and eigenvectors. EIGVALS_TEST_DATA = [ ( np.eye(3), np.array([1.0, 1.0, 1.0]), np.array([[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]), ), ( np.array([[0, 0, 1], [0, 1, 0], [1, 0, 0]]), np.array([-1.0, 1.0, 1.0]), np.array( [[-0.70710678, -0.70710678, 0.0], [0.0, 0.0, -1.0], [0.70710678, -0.70710678, 0.0]] ), ), ( np.array([[0, 0, -1j], [0, 0, 0], [1j, 0, 0]]), np.array([-1.0, 0.0, 1.0]), np.array( [ [-0.70710678 + 0.0j, 0.0 + 0.0j, -0.70710678 + 0.0j], [0.0 + 0.0j, 0.0 + 1.0j, 0.0 + 0.0j], [0.0 + 0.70710678j, 0.0 + 0.0j, 0.0 - 0.70710678j], ] ), ), ( np.array([[2, 0, 0], [0, 3, 0], [0, 0, 4]]), np.array([2.0, 3.0, 4.0]), np.array([[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]), ), ( np.array([[1, 0, 0], [0, 1, 0], [0, 0, -2]]) / 2, np.array([-1.0, 0.5, 0.5]), np.array([[0.0, 0.0, 1.0], [0.0, 1.0, 0.0], [1.0, 0.0, 0.0]]), ), ] X_12 = np.array([[1, 0, 0], [0, 0, 1], [0, 1, 0]]) Z_0 = np.array([[-1, 0, 0], [0, 1, 0], [0, 0, -1]]) EIGVALS_TEST_DATA_MULTI_WIRES = [functools.reduce(np.kron, [X_12, np.eye(3), Z_0])] # run all tests in this class in the same thread. # Prevents multiple threads from updating THermitian._eigs at the same time @pytest.mark.xdist_group(name="thermitian_cache_group") @pytest.mark.usefixtures("tear_down_thermitian") class TestTHermitian: """Test the THermitian observable""" def setup_method(self): """Patch the _eigs class attribute of the Hermitian class before every test.""" self.patched_eigs = patch( # pylint: disable=attribute-defined-outside-init "pennylane.ops.qutrit.observables.THermitian._eigs", PropertyMock(return_value={}) ) self.patched_eigs.start() def tear_down_method(self): """Stop patch after every test.""" self.patched_eigs.stop() @pytest.mark.parametrize("observable, eigvals, eigvecs", EIGVALS_TEST_DATA) def test_thermitian_eigegendecomposition_single_wire(self, observable, eigvals, eigvecs, tol): """Tests that the eigendecomposition property of the THermitian class returns the correct results for a single wire.""" eigendecomp = qml.THermitian(observable, wires=0).eigendecomposition assert np.allclose(eigendecomp["eigval"], eigvals, atol=tol, rtol=0) assert np.allclose(eigendecomp["eigvec"], eigvecs, atol=tol, rtol=0) key = tuple(observable.flatten().tolist()) assert np.allclose(qml.THermitian._eigs[key]["eigval"], eigvals, atol=tol, rtol=0) assert np.allclose(qml.THermitian._eigs[key]["eigvec"], eigvecs, atol=tol, rtol=0) @pytest.mark.parametrize("observable", EIGVALS_TEST_DATA_MULTI_WIRES) def test_thermitian_eigendecomposition_multiple_wires(self, observable, tol): """Tests that the eigendecomposition property of the THermitian class returns the correct results for multiple wires.""" num_wires = int(np.log(len(observable)) / np.log(3)) eigendecomp = qml.THermitian(observable, wires=list(range(num_wires))).eigendecomposition eigvals, eigvecs = np.linalg.eigh(observable) assert np.allclose(eigendecomp["eigval"], eigvals, atol=tol, rtol=0) assert np.allclose(eigendecomp["eigvec"], eigvecs, atol=tol, rtol=0) key = tuple(observable.flatten().tolist()) assert np.allclose(qml.THermitian._eigs[key]["eigval"], eigvals, atol=tol, rtol=0) assert np.allclose(qml.THermitian._eigs[key]["eigvec"], eigvecs, atol=tol, rtol=0) assert len(qml.THermitian._eigs) == 1 @pytest.mark.parametrize("obs1", EIGVALS_TEST_DATA) @pytest.mark.parametrize("obs2", EIGVALS_TEST_DATA) def test_thermitian_eigvals_eigvecs_two_different_observables(self, obs1, obs2, tol): """Tests that the eigvals method of the THermitian class returns the correct results for two observables.""" if np.all(obs1[0] == obs2[0]): pytest.skip("Test only runs for pairs of differing observable") observable_1 = obs1[0] observable_1_eigvals = obs1[1] observable_1_eigvecs = obs1[2] key = tuple(observable_1.flatten().tolist()) qml.THermitian(observable_1, 0).eigvals() assert np.allclose( qml.THermitian._eigs[key]["eigval"], observable_1_eigvals, atol=tol, rtol=0 ) assert np.allclose( qml.THermitian._eigs[key]["eigvec"], observable_1_eigvecs, atol=tol, rtol=0 ) assert len(qml.THermitian._eigs) == 1 observable_2 = obs2[0] observable_2_eigvals = obs2[1] observable_2_eigvecs = obs2[2] key_2 = tuple(observable_2.flatten().tolist()) qml.THermitian(observable_2, 0).eigvals() assert np.allclose( qml.THermitian._eigs[key_2]["eigval"], observable_2_eigvals, atol=tol, rtol=0 ) assert np.allclose( qml.THermitian._eigs[key_2]["eigvec"], observable_2_eigvecs, atol=tol, rtol=0 ) assert len(qml.THermitian._eigs) == 2 @pytest.mark.parametrize("observable, eigvals, eigvecs", EIGVALS_TEST_DATA) def test_thermitian_eigvals_eigvecs_same_observable_twice( self, observable, eigvals, eigvecs, tol ): """Tests that the eigvals method of the THermitian class keeps the same dictionary entries upon multiple calls.""" key = tuple(observable.flatten().tolist()) qml.THermitian(observable, 0).eigvals() assert np.allclose(qml.THermitian._eigs[key]["eigval"], eigvals, atol=tol, rtol=0) assert np.allclose(qml.THermitian._eigs[key]["eigvec"], eigvecs, atol=tol, rtol=0) assert len(qml.THermitian._eigs) == 1 qml.THermitian(observable, 0).eigvals() assert np.allclose(qml.THermitian._eigs[key]["eigval"], eigvals, atol=tol, rtol=0) assert np.allclose(qml.THermitian._eigs[key]["eigvec"], eigvecs, atol=tol, rtol=0) assert len(qml.THermitian._eigs) == 1 @pytest.mark.parametrize("observable, eigvals, eigvecs", EIGVALS_TEST_DATA) def test_hermitian_diagonalizing_gates(self, observable, eigvals, eigvecs, tol): """Tests that the diagonalizing_gates method of the THermitian class returns the correct results.""" qutrit_unitary = qml.THermitian(observable, wires=[0]).diagonalizing_gates() key = tuple(observable.flatten().tolist()) assert np.allclose(qml.THermitian._eigs[key]["eigval"], eigvals, atol=tol, rtol=0) assert np.allclose(qml.THermitian._eigs[key]["eigvec"], eigvecs, atol=tol, rtol=0) assert np.allclose(qutrit_unitary[0].data, eigvecs.conj().T, atol=tol, rtol=0) assert len(qml.THermitian._eigs) == 1 def test_thermitian_compute_diagonalizing_gates(self, tol): """Tests that the compute_diagonalizing_gates method of the THermitian class returns the correct results.""" eigvecs = np.array( [ [0.38268343, -0.92387953, 0.70710678], [-0.92387953, -0.38268343, -0.70710678], [0.70710678, -0.38268343, 1.41421356], ] ) res = qml.THermitian.compute_diagonalizing_gates(eigvecs, wires=[0])[0].data expected = eigvecs.conj().T assert np.allclose(res, expected, atol=tol, rtol=0) @pytest.mark.parametrize("obs1", EIGVALS_TEST_DATA) @pytest.mark.parametrize("obs2", EIGVALS_TEST_DATA) def test_thermitian_diagonalizing_gates_two_different_observables(self, obs1, obs2, tol): """Tests that the diagonalizing_gates method of the THermitian class returns the correct results for two observables.""" if np.all(obs1[0] == obs2[0]): pytest.skip("Test only runs for pairs of differing observable") observable_1 = obs1[0] observable_1_eigvals = obs1[1] observable_1_eigvecs = obs1[2] qutrit_unitary = qml.THermitian(observable_1, wires=[0]).diagonalizing_gates() key = tuple(observable_1.flatten().tolist()) assert np.allclose( qml.THermitian._eigs[key]["eigval"], observable_1_eigvals, atol=tol, rtol=0 ) assert np.allclose( qml.THermitian._eigs[key]["eigvec"], observable_1_eigvecs, atol=tol, rtol=0 ) assert np.allclose(qutrit_unitary[0].data, observable_1_eigvecs.conj().T, atol=tol, rtol=0) assert len(qml.THermitian._eigs) == 1 observable_2 = obs2[0] observable_2_eigvals = obs2[1] observable_2_eigvecs = obs2[2] qutrit_unitary_2 = qml.THermitian(observable_2, wires=[0]).diagonalizing_gates() key = tuple(observable_2.flatten().tolist()) assert np.allclose( qml.THermitian._eigs[key]["eigval"], observable_2_eigvals, atol=tol, rtol=0 ) assert np.allclose( qml.THermitian._eigs[key]["eigvec"], observable_2_eigvecs, atol=tol, rtol=0 ) assert np.allclose( qutrit_unitary_2[0].data, observable_2_eigvecs.conj().T, atol=tol, rtol=0 ) assert len(qml.THermitian._eigs) == 2 @pytest.mark.parametrize("observable, eigvals, eigvecs", EIGVALS_TEST_DATA) def test_thermitian_diagonalizing_gates_same_observable_twice( self, observable, eigvals, eigvecs, tol ): """Tests that the diagonalizing_gates method of the THermitian class keeps the same dictionary entries upon multiple calls.""" qutrit_unitary = qml.THermitian(observable, wires=[0]).diagonalizing_gates() key = tuple(observable.flatten().tolist()) assert np.allclose(qml.THermitian._eigs[key]["eigval"], eigvals, atol=tol, rtol=0) assert np.allclose(qml.THermitian._eigs[key]["eigvec"], eigvecs, atol=tol, rtol=0) assert np.allclose(qutrit_unitary[0].data, eigvecs.conj().T, atol=tol, rtol=0) assert len(qml.THermitian._eigs) == 1 qutrit_unitary = qml.THermitian(observable, wires=[0]).diagonalizing_gates() key = tuple(observable.flatten().tolist()) assert np.allclose(qml.THermitian._eigs[key]["eigval"], eigvals, atol=tol, rtol=0) assert np.allclose(qml.THermitian._eigs[key]["eigvec"], eigvecs, atol=tol, rtol=0) assert np.allclose(qutrit_unitary[0].data, eigvecs.conj().T, atol=tol, rtol=0) assert len(qml.THermitian._eigs) == 1 @pytest.mark.parametrize("observable, eigvals, eigvecs", EIGVALS_TEST_DATA) def test_thermitian_diagonalizing_gates_integration(self, observable, eigvals, eigvecs, tol): """Tests that the diagonalizing_gates method of the THermitian class diagonalizes the given observable.""" tensor_obs = np.kron(observable, observable) eigvals = np.kron(eigvals, eigvals) diag_gates = qml.THermitian(tensor_obs, wires=[0, 1]).diagonalizing_gates() assert len(diag_gates) == 1 U = diag_gates[0].parameters[0] x = U @ tensor_obs @ U.conj().T assert np.allclose(np.diag(np.sort(eigvals)), x, atol=tol, rtol=0) def test_thermitian_matrix(self, tol): """Test that the Hermitian matrix method produces the correct output.""" H_01 = np.array([[1, 1, 0], [1, -1, 0], [0, 0, np.sqrt(2)]]) / np.sqrt(2) out = qml.THermitian(H_01, wires=0).matrix() # verify output type assert isinstance(out, np.ndarray) # verify equivalent to input state assert np.allclose(out, H_01, atol=tol, rtol=0) def test_thermitian_exceptions(self): """Tests that the Hermitian matrix method raises the proper errors.""" H_01 = np.array([[1, 1, 0], [1, -1, 0], [0, 0, np.sqrt(2)]]) / np.sqrt(2) # test non-square matrix with pytest.raises(ValueError, match="must be a square matrix"): qml.THermitian(H_01[1:], wires=0).matrix() # test non-Hermitian matrix H2 = H_01.copy() H2[0, 1] = 2 with pytest.raises(ValueError, match="must be Hermitian"): qml.THermitian(H2, wires=0).matrix() def test_matrix_representation(self, tol): """Test that the matrix representation is defined correctly""" A = np.array([[6 + 0j, 1 - 2j, 0], [1 + 2j, -1, 0], [0, 0, 1]]) res_static = qml.THermitian.compute_matrix(A) res_dynamic = qml.THermitian(A, wires=0).matrix() expected = np.array( [ [6.0 + 0.0j, 1.0 - 2.0j, 0.0 + 0.0j], [1.0 + 2.0j, -1.0 + 0.0j, 0.0 + 0.0j], [0.0 + 0.0j, 0.0 + 0.0j, 1.0 + 0.0j], ] ) assert np.allclose(res_static, expected, atol=tol) assert np.allclose(res_dynamic, expected, atol=tol) GM_OBSERVABLES = [ (1, GELL_MANN[0], [1, -1, 0]), (2, GELL_MANN[1], [1, -1, 0]), (3, GELL_MANN[2], [1, -1, 0]), (4, GELL_MANN[3], [1, -1, 0]), (5, GELL_MANN[4], [1, -1, 0]), (6, GELL_MANN[5], [1, -1, 0]), (7, GELL_MANN[6], [1, -1, 0]), (8, GELL_MANN[7], np.array([1, 1, -2]) / np.sqrt(3)), ] class TestGellMann: """Tests for simple single-qutrit observables""" @pytest.mark.parametrize("index, mat, eigs", GM_OBSERVABLES) def test_diagonalization(self, index, mat, eigs, tol): """Test the method transforms Gell-Mann observables appropriately.""" ob = qml.GellMann(wires=0, index=index) A = ob.matrix() diag_gates = ob.diagonalizing_gates() U = np.eye(3) if index in {3, 8}: assert len(diag_gates) == 0 else: assert len(diag_gates) == 1 assert diag_gates[0].__class__ == qml.QutritUnitary mat = diag_gates[0].matrix() U = np.dot(np.eye(3), mat) res = U @ A @ U.conj().T expected = np.diag(eigs) assert np.allclose(res, expected, atol=tol, rtol=0) @pytest.mark.parametrize("index", [0, 9, 1.0, 2.5, "c"]) def test_index_error(self, index): """Test that using bad index values throws the appropriate error""" with pytest.raises( ValueError, match="The index of a Gell-Mann observable must be an integer between 1 and 8 inclusive.", ): qml.GellMann(wires=0, index=index) @pytest.mark.parametrize("index, mat, eigs", GM_OBSERVABLES) def test_matrix(self, index, mat, eigs, tol): """Test that the Gell-Mann matrices are correct""" res_static = qml.GellMann.compute_matrix(index) res_dynamic = qml.GellMann(wires=0, index=index).matrix() assert np.allclose(res_static, mat) assert np.allclose(res_dynamic, mat) @pytest.mark.usefixtures("use_legacy_opmath") def test_obs_data(self): """Test that the _obs_data() method of qml.GellMann returns the correct observable data.""" ob1 = qml.GellMann(wires=0, index=2) ob2 = qml.GellMann(wires=0, index=2) @ qml.GellMann(wires=1, index=1) assert ob1._obs_data() == {("GellMann", qml.wires.Wires(0), (2,))} assert ob2._obs_data() == { ("GellMann", qml.wires.Wires(0), (2,)), ("GellMann", qml.wires.Wires(1), (1,)), } @pytest.mark.parametrize("index, mat, eigs", GM_OBSERVABLES) def test_eigvals(self, index, mat, eigs, tol): """Test that the Gell-Mann eigenvalues are correct""" res_static = qml.GellMann.compute_eigvals(index) res_dynamic = qml.GellMann(wires=0, index=index).eigvals() assert np.allclose(res_static, eigs) assert np.allclose(res_dynamic, eigs) @pytest.mark.parametrize("index", list(range(1, 9))) def test_label(self, index): """Test that the label is correct""" label = f"GellMann({index})" obs = qml.GellMann(wires=0, index=index) assert obs.label() == label assert obs.label(decimals=2) == label @pytest.mark.parametrize("index", list(range(1, 9))) def test_repr(self, index): """Test that the __repr__ method is correct""" rep = f"GellMann{index}(wires=[0])" obs = qml.GellMann(wires=0, index=index) assert repr(obs) == rep
pennylane/tests/ops/qutrit/test_qutrit_observables.py/0
{ "file_path": "pennylane/tests/ops/qutrit/test_qutrit_observables.py", "repo_id": "pennylane", "token_count": 8418 }
88
# Copyright 2018-2021 Xanadu Quantum Technologies Inc. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Unit tests for the ``QNSPSAOptimizer`` """ # pylint: disable=protected-access from copy import deepcopy import pytest from scipy.linalg import sqrtm import pennylane as qml from pennylane import numpy as np def get_single_input_qnode(): """Prepare qnode with a single tensor as input.""" dev = qml.device("default.qubit", wires=2) # the analytical expression of the qnode goes as: # np.cos(params[0][0] / 2) ** 2 - np.sin(params[0][0] / 2) ** 2 * np.cos(params[0][1]) @qml.qnode(dev) def loss_fn(params): qml.RY(params[0][0], wires=0) qml.CRX(params[0][1], wires=[0, 1]) return qml.expval(qml.PauliZ(0) @ qml.PauliZ(1)) return loss_fn, (1, 2) # returns the qnode and the input param shape def get_multi_input_qnode(): """Prepare qnode with two separate tensors as input.""" dev = qml.device("default.qubit", wires=2) # the analytical expression of the qnode goes as: # np.cos(x1 / 2) ** 2 - np.sin(x1 / 2) ** 2 * np.cos(x2) @qml.qnode(dev) def loss_fn(x1, x2): qml.RY(x1, wires=0) qml.CRX(x2, wires=[0, 1]) return qml.expval(qml.PauliZ(0) @ qml.PauliZ(1)) return loss_fn def get_grad_finite_diff(params, finite_diff_step, grad_dirs): """Helper function computing the qnode finite difference for computing the gradient analytically. One can expand the following expression to get the qnode_finite_diff expression: qnode(params + finite_diff_step * grad_dirs) - qnode(params - finite_diff_step * grad_dirs) """ qnode_finite_diff = ( -np.sin(params[0]) * np.sin(finite_diff_step * grad_dirs[0]) + np.sin(params[1]) * np.sin(finite_diff_step * grad_dirs[1]) + ( np.cos( params[0] + params[1] + finite_diff_step * grad_dirs[0] + finite_diff_step * grad_dirs[1] ) + np.cos( params[0] + finite_diff_step * grad_dirs[0] - params[1] - finite_diff_step * grad_dirs[1] ) - np.cos( params[0] + params[1] - finite_diff_step * grad_dirs[0] - finite_diff_step * grad_dirs[1] ) - np.cos( params[0] - finite_diff_step * grad_dirs[0] - params[1] + finite_diff_step * grad_dirs[1] ) ) / 4 ) return qnode_finite_diff def get_metric_from_single_input_qnode(params, finite_diff_step, tensor_dirs): """Compute the expected raw metric tensor from analytical state overlap expression.""" dir_vec1 = tensor_dirs[0] dir_vec2 = tensor_dirs[1] dir1 = dir_vec1.reshape(params.shape) dir2 = dir_vec2.reshape(params.shape) perturb1 = dir1 * finite_diff_step perturb2 = dir2 * finite_diff_step def get_state_overlap(params1, params2): # analytically computed state overlap between two parameterized ansatzes # with input params1 and params2 return ( np.cos(params1[0][0] / 2) * np.cos(params2[0][0] / 2) + np.sin(params1[0][0] / 2) * np.sin(params2[0][0] / 2) * ( np.sin(params1[0][1] / 2) * np.sin(params2[0][1] / 2) + np.cos(params1[0][1] / 2) * np.cos(params2[0][1] / 2) ) ) ** 2 tensor_finite_diff = ( get_state_overlap(params, params + perturb1 + perturb2) - get_state_overlap(params, params + perturb1) - get_state_overlap(params, params - perturb1 + perturb2) + get_state_overlap(params, params - perturb1) ) metric_tensor_expected = ( -(np.tensordot(dir_vec1, dir_vec2, axes=0) + np.tensordot(dir_vec2, dir_vec1, axes=0)) * tensor_finite_diff / (8 * finite_diff_step * finite_diff_step) ) return metric_tensor_expected @pytest.mark.parametrize("seed", [1, 151, 1231]) @pytest.mark.parametrize("finite_diff_step", [1e-3, 1e-2, 1e-1]) class TestQNSPSAOptimizer: def test_gradient_from_single_input(self, finite_diff_step, seed): """Test that the QNSPSA gradient estimation is correct by comparing the optimizer result to the analytical result.""" opt = qml.QNSPSAOptimizer( stepsize=1e-3, regularization=1e-3, finite_diff_step=finite_diff_step, resamplings=1, blocking=True, history_length=5, seed=seed, ) qnode, params_shape = get_single_input_qnode() params = np.random.rand(*params_shape) # gradient result from QNSPSAOptimizer grad_tapes, grad_dirs = opt._get_spsa_grad_tapes(qnode, [params], {}) raw_results = qml.execute(grad_tapes, qnode.device, None) grad_res = opt._post_process_grad(raw_results, grad_dirs)[0] # gradient computed analytically qnode_finite_diff = get_grad_finite_diff(params[0], finite_diff_step, grad_dirs[0][0]) grad_expected = qnode_finite_diff / (2 * finite_diff_step) * grad_dirs[0] assert np.allclose(grad_res, grad_expected) def test_raw_metric_tensor(self, finite_diff_step, seed): """Test that the QNSPSA metric tensor estimation(before regularization) is correct by comparing the optimizer result to the analytical result.""" opt = qml.QNSPSAOptimizer( stepsize=1e-3, regularization=1e-3, finite_diff_step=finite_diff_step, resamplings=1, blocking=True, history_length=5, seed=seed, ) qnode, params_shape = get_single_input_qnode() params = np.random.rand(*params_shape) # raw metric tensor result from QNSPSAOptimizer metric_tapes, tensor_dirs = opt._get_tensor_tapes(qnode, [params], {}) raw_results = qml.execute(metric_tapes, qnode.device, None) metric_tensor_res = opt._post_process_tensor(raw_results, tensor_dirs) # expected raw metric tensor from analytical state overlap metric_tensor_expected = get_metric_from_single_input_qnode( params, finite_diff_step, tensor_dirs ) assert np.allclose(metric_tensor_res, metric_tensor_expected) def test_gradient_from_multi_input(self, finite_diff_step, seed): """Test that the QNSPSA gradient estimation is correct by comparing the optimizer result to the analytical result.""" opt = qml.QNSPSAOptimizer( stepsize=1e-3, regularization=1e-3, finite_diff_step=finite_diff_step, resamplings=1, blocking=True, history_length=5, seed=seed, ) qnode = get_multi_input_qnode() params = [np.random.rand(1) for _ in range(2)] # gradient result from QNSPSAOptimizer grad_tapes, grad_dirs = opt._get_spsa_grad_tapes(qnode, params, {}) raw_results = qml.execute(grad_tapes, qnode.device, None) grad_res = opt._post_process_grad(raw_results, grad_dirs) # gradient computed analytically qnode_finite_diff = get_grad_finite_diff(params, finite_diff_step, grad_dirs) grad_expected = [ qnode_finite_diff / (2 * finite_diff_step) * grad_dir for grad_dir in grad_dirs ] assert np.allclose(grad_res, grad_expected) def test_step_from_single_input(self, finite_diff_step, seed): """Test step() function with the single-input qnode.""" regularization = 1e-3 stepsize = 1e-2 opt = qml.QNSPSAOptimizer( stepsize=stepsize, regularization=regularization, finite_diff_step=finite_diff_step, resamplings=1, blocking=False, history_length=5, seed=seed, ) # target opt is used to reproduce the random sampling result target_opt = deepcopy(opt) qnode, params_shape = get_single_input_qnode() params = np.random.rand(*params_shape) new_params_res = opt.step(qnode, params) _, grad_dirs = target_opt._get_spsa_grad_tapes(qnode, [params], {}) _, tensor_dirs = target_opt._get_tensor_tapes(qnode, [params], {}) qnode_finite_diff = get_grad_finite_diff(params[0], finite_diff_step, grad_dirs[0][0]) grad_expected = (qnode_finite_diff / (2 * finite_diff_step) * grad_dirs[0])[0] metric_tensor_expected = get_metric_from_single_input_qnode( params, finite_diff_step, tensor_dirs ) # regularize raw metric tensor identity = np.identity(metric_tensor_expected.shape[0]) avg_metric_tensor = 0.5 * (identity + metric_tensor_expected) tensor_reg = np.real(sqrtm(np.matmul(avg_metric_tensor, avg_metric_tensor))) tensor_reg = (tensor_reg + regularization * identity) / (1 + regularization) inv_metric_tensor = np.linalg.inv(tensor_reg) new_params_expected = params - stepsize * np.matmul(inv_metric_tensor, grad_expected) assert np.allclose(new_params_res, new_params_expected) def test_step_and_cost_from_single_input(self, finite_diff_step, seed): """Test step_and_cost() function with the single-input qnode. Both blocking settings (on/off) are tested. """ regularization = 1e-3 stepsize = 1e-2 opt_blocking = qml.QNSPSAOptimizer( stepsize=stepsize, regularization=regularization, finite_diff_step=finite_diff_step, resamplings=1, blocking=True, history_length=5, seed=seed, ) opt_no_blocking = deepcopy(opt_blocking) opt_no_blocking.blocking = False # target opt is used to reproduce the result with step() target_opt = deepcopy(opt_blocking) qnode, params_shape = get_single_input_qnode() params = np.random.rand(*params_shape) new_params_blocking_res, qnode_blocking_res = opt_blocking.step_and_cost(qnode, params) with pytest.warns(UserWarning): new_params_expected = target_opt.step(qnode, params) # analytical expression of the qnode qnode_expected = np.cos(params[0][0] / 2) ** 2 - np.sin(params[0][0] / 2) ** 2 * np.cos( params[0][1] ) assert np.allclose(new_params_blocking_res, new_params_expected) assert np.allclose(qnode_blocking_res, qnode_expected) new_params_no_blocking_res, qnode_no_blocking_res = opt_no_blocking.step_and_cost( qnode, params ) assert np.allclose(new_params_no_blocking_res, new_params_expected) assert np.allclose(qnode_no_blocking_res, qnode_expected) def test_step_and_cost_from_multi_input(self, finite_diff_step, seed): """Test step_and_cost() function with the multi-input qnode.""" regularization = 1e-3 stepsize = 1e-2 opt = qml.QNSPSAOptimizer( stepsize=stepsize, regularization=regularization, finite_diff_step=finite_diff_step, resamplings=1, blocking=True, history_length=5, seed=seed, ) # target opt is used to reproduce the random sampling result target_opt = deepcopy(opt) qnode = get_multi_input_qnode() params = [np.array(1.0) for _ in range(2)] # this single-step result will be different from the one from the single-input qnode, due to the # different order in sampling perturbation directions. new_params_res, qnode_res = opt.step_and_cost(qnode, *params) # test the expectation value qnode_expected = np.cos(params[0] / 2) ** 2 - np.sin(params[0] / 2) ** 2 * np.cos(params[1]) assert np.allclose(qnode_res, qnode_expected) # test the next-step parameter _, grad_dirs = target_opt._get_spsa_grad_tapes(qnode, params, {}) _, tensor_dirs = target_opt._get_tensor_tapes(qnode, params, {}) qnode_finite_diff = get_grad_finite_diff(params, finite_diff_step, grad_dirs) grad_expected = [ qnode_finite_diff / (2 * finite_diff_step) * grad_dir for grad_dir in grad_dirs ] # reshape the params list into a tensor to reuse the # get_metric_from_single_input_qnode helper function params_tensor = np.array(params).reshape(1, len(params)) metric_tensor_expected = get_metric_from_single_input_qnode( params_tensor, finite_diff_step, tensor_dirs ) # regularize raw metric tensor identity = np.identity(metric_tensor_expected.shape[0]) avg_metric_tensor = 0.5 * (identity + metric_tensor_expected) tensor_reg = np.real(sqrtm(np.matmul(avg_metric_tensor, avg_metric_tensor))) tensor_reg = (tensor_reg + regularization * identity) / (1 + regularization) inv_metric_tensor = np.linalg.inv(tensor_reg) grad_tensor = np.array(grad_expected).reshape( inv_metric_tensor.shape[0], ) new_params_tensor_expected = params_tensor - stepsize * np.matmul( inv_metric_tensor, grad_tensor ) assert np.allclose( np.array(new_params_res).reshape(new_params_tensor_expected.shape), new_params_tensor_expected, ) @pytest.mark.parametrize("device_name", ["default.qubit", "default.qubit.legacy"]) def test_step_and_cost_with_non_trainable_input(self, device_name, finite_diff_step, seed): """ Test step_and_cost() function with the qnode with non-trainable input, both using the `default.qubit` and `default.qubit.legacy` device. """ regularization = 1e-3 stepsize = 1e-2 opt = qml.QNSPSAOptimizer( stepsize=stepsize, regularization=regularization, finite_diff_step=finite_diff_step, resamplings=1, blocking=True, history_length=5, seed=seed, ) # a deep copy of the same opt, to be applied to qnode_reduced target_opt = deepcopy(opt) dev = qml.device(device_name, wires=2) non_trainable_param = np.random.rand(1) non_trainable_param.requires_grad = False trainable_param = np.random.rand(1) @qml.qnode(dev) def qnode_with_non_trainable(trainable, non_trainable): qml.RY(trainable, wires=0) qml.CRX(non_trainable, wires=[0, 1]) return qml.expval(qml.PauliZ(0) @ qml.PauliZ(1)) # reduced qnode where non-trainable param value is hard coded @qml.qnode(dev) def qnode_reduced(trainable): qml.RY(trainable, wires=0) qml.CRX(non_trainable_param, wires=[0, 1]) return qml.expval(qml.PauliZ(0) @ qml.PauliZ(1)) new_params_res, qnode_res = opt.step_and_cost( qnode_with_non_trainable, trainable_param, non_trainable_param ) new_trainable_res, new_non_trianable_res = new_params_res new_trainable_expected, qnode_expected = target_opt.step_and_cost( qnode_reduced, trainable_param ) assert np.allclose(qnode_res, qnode_expected) assert np.allclose(new_non_trianable_res, non_trainable_param) assert np.allclose(new_trainable_res, new_trainable_expected) def test_blocking(self, finite_diff_step, seed): """Test blocking setting of the optimizer.""" regularization = 1e-3 stepsize = 1.0 history_length = 5 opt = qml.QNSPSAOptimizer( stepsize=stepsize, regularization=regularization, finite_diff_step=finite_diff_step, resamplings=1, blocking=True, history_length=history_length, seed=seed, ) qnode, params_shape = get_single_input_qnode() # params minimizes the qnode params = np.tensor([3.1415, 0]).reshape(params_shape) # fill opt.last_n_steps array with a minimum expectation value for _ in range(history_length): opt.step_and_cost(qnode, params) # blocking should stop params from updating from this minimum new_params, _ = opt.step_and_cost(qnode, params) assert np.allclose(new_params, params) def test_template_no_adjoint(): """Test that qnspsa iterates when the operations do not have a custom adjoint.""" num_qubits = 2 dev = qml.device("default.qubit", wires=num_qubits) @qml.qnode(dev) def cost(params): qml.RandomLayers(weights=params, wires=range(num_qubits), seed=42) return qml.expval(qml.PauliZ(0) @ qml.PauliZ(1)) params = np.random.normal(0, np.pi, (2, 4)) opt = qml.QNSPSAOptimizer(stepsize=5e-2) assert opt.step_and_cost(cost, params) # just checking it runs without error assert not qml.RandomLayers.has_adjoint def test_workflow_integration(): """Test that the optimizer can optimize a workflow.""" num_qubits = 2 dev = qml.device("default.qubit", wires=num_qubits) @qml.qnode(dev) def cost(params): qml.RX(params[0], wires=0) qml.CRY(params[1], wires=[0, 1]) return qml.expval(qml.Z(0) @ qml.Z(1)) params = qml.numpy.array([0.5, 0.5], requires_grad=True) opt = qml.optimize.QNSPSAOptimizer(stepsize=5e-2) for _ in range(101): params, loss = opt.step_and_cost(cost, params) assert qml.math.allclose(loss, -1, atol=1e-3) # compare sine of params and target params as could converge to params + 2* np.pi target_params = np.array([np.pi, 0]) assert qml.math.allclose(np.sin(params), np.sin(target_params), atol=1e-2)
pennylane/tests/optimize/test_qnspsa.py/0
{ "file_path": "pennylane/tests/optimize/test_qnspsa.py", "repo_id": "pennylane", "token_count": 8526 }
89
# Copyright 2018-2023 Xanadu Quantum Technologies Inc. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Unit tests for the :mod:`pauli` interface functions in ``pauli/pauli_interface.py``. """ import numpy as np import pytest import pennylane as qml from pennylane.pauli import pauli_word_prefactor ops_factors = ( (qml.PauliX(0), 1), (qml.PauliY(1), 1), (qml.PauliZ("a"), 1), (qml.Identity(0), 1), (qml.PauliX(0) @ qml.PauliY(1), 1), (qml.PauliX(0) @ qml.PauliY(0), 1j), (qml.operation.Tensor(qml.X(0), qml.Y(1)), 1), (qml.operation.Tensor(qml.X(0), qml.Y(0)), 1j), (qml.Hamiltonian([-1.23], [qml.PauliZ(0)]), -1.23), (qml.prod(qml.PauliX(0), qml.PauliY(1)), 1), (qml.s_prod(1.23, qml.s_prod(-1j, qml.PauliZ(0))), -1.23j), ) @pytest.mark.parametrize("op, true_prefactor", ops_factors) def test_pauli_word_prefactor(op, true_prefactor): """Test that we can accurately determine the prefactor""" assert pauli_word_prefactor(op) == true_prefactor def test_pauli_word_prefactor_tensor_error(): """Test that an error is raised is the tensor is not a pauli sentence.""" op = qml.operation.Tensor(qml.Hermitian(np.eye(2), wires=0), qml.Hadamard(wires=1)) with pytest.raises(ValueError, match="Expected a valid Pauli word"): pauli_word_prefactor(op) ops = ( qml.Hadamard(0), qml.Hadamard(0) @ qml.PauliZ(1), qml.Hamiltonian([], []), qml.Hamiltonian([1.23, 0.45], [qml.PauliX(0) @ qml.PauliY(1), qml.PauliZ(1)]), qml.prod(qml.PauliX(0), qml.Hadamard(1)), qml.prod(qml.sum(qml.PauliX(0), qml.PauliY(0)), qml.PauliZ(1)), qml.s_prod(1.23, qml.sum(qml.PauliX(0), qml.PauliY(0))), ) @pytest.mark.usefixtures("use_legacy_and_new_opmath") @pytest.mark.parametrize("op", ops) def test_pauli_word_prefactor_raises_error(op): """Test that an error is raised when the operator provided is not a valid PauliWord.""" with pytest.raises(ValueError, match="Expected a valid Pauli word, got"): pauli_word_prefactor(op)
pennylane/tests/pauli/test_pauli_interface.py/0
{ "file_path": "pennylane/tests/pauli/test_pauli_interface.py", "repo_id": "pennylane", "token_count": 1071 }
90
# Copyright 2018-2023 Xanadu Quantum Technologies Inc. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Unit tests for the ``decompose`` function. """ # pylint: disable=too-many-arguments import os import numpy as np import pytest from pennylane import qchem ref_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), "test_ref_files") @pytest.mark.parametrize( ( "name", "core", "active", "mapping", "coeffs_ref", "pauli_strings_ref", ), [ ( "lih", [0], [1, 2], "jordan_WIGNER", np.array( [ -7.50915719e00 + 0.0j, 1.55924093e-01 + 0.0j, 1.40159380e-02 + 0.0j, 1.40159380e-02 + 0.0j, 1.55924093e-01 + 0.0j, 1.40159380e-02 + 0.0j, 1.40159380e-02 + 0.0j, -1.50398257e-02 + 0.0j, -1.50398257e-02 + 0.0j, 1.21827742e-01 + 0.0j, 1.21448939e-02 + 0.0j, 1.21448939e-02 + 0.0j, 1.21448939e-02 + 0.0j, 1.21448939e-02 + 0.0j, 3.26599399e-03 + 0.0j, -3.26599399e-03 + 0.0j, -3.26599399e-03 + 0.0j, 3.26599399e-03 + 0.0j, 5.26365152e-02 + 0.0j, 5.59025092e-02 + 0.0j, -1.87104184e-03 + 0.0j, -1.87104184e-03 + 0.0j, 5.59025092e-02 + 0.0j, -1.87104184e-03 + 0.0j, -1.87104184e-03 + 0.0j, 5.26365152e-02 + 0.0j, 8.44705692e-02 + 0.0j, ] ), [ (), ((0, "Z"),), ((0, "Y"), (1, "Z"), (2, "Y")), ((0, "X"), (1, "Z"), (2, "X")), ((1, "Z"),), ((1, "Y"), (2, "Z"), (3, "Y")), ((1, "X"), (2, "Z"), (3, "X")), ((2, "Z"),), ((3, "Z"),), ((0, "Z"), (1, "Z")), ((0, "Y"), (2, "Y")), ((0, "X"), (2, "X")), ((0, "Z"), (1, "Y"), (2, "Z"), (3, "Y")), ((0, "Z"), (1, "X"), (2, "Z"), (3, "X")), ((0, "Y"), (1, "X"), (2, "X"), (3, "Y")), ((0, "Y"), (1, "Y"), (2, "X"), (3, "X")), ((0, "X"), (1, "X"), (2, "Y"), (3, "Y")), ((0, "X"), (1, "Y"), (2, "Y"), (3, "X")), ((0, "Z"), (2, "Z")), ((0, "Z"), (3, "Z")), ((0, "Y"), (1, "Z"), (2, "Y"), (3, "Z")), ((0, "X"), (1, "Z"), (2, "X"), (3, "Z")), ((1, "Z"), (2, "Z")), ((1, "Y"), (3, "Y")), ((1, "X"), (3, "X")), ((1, "Z"), (3, "Z")), ((2, "Z"), (3, "Z")), ], ), ( "lih", [0], [1, 2], "BRAVYI_kitaev", np.array( [ -7.50915719e00 + 0.0j, 1.55924093e-01 + 0.0j, 1.40159380e-02 + 0.0j, -1.40159380e-02 + 0.0j, 1.55924093e-01 + 0.0j, -1.40159380e-02 + 0.0j, 1.40159380e-02 + 0.0j, -1.50398257e-02 + 0.0j, -1.50398257e-02 + 0.0j, 1.21827742e-01 + 0.0j, 1.21448939e-02 + 0.0j, 1.21448939e-02 + 0.0j, -1.21448939e-02 + 0.0j, 1.21448939e-02 + 0.0j, 3.26599399e-03 + 0.0j, 3.26599399e-03 + 0.0j, 3.26599399e-03 + 0.0j, 3.26599399e-03 + 0.0j, 5.26365152e-02 + 0.0j, 5.59025092e-02 + 0.0j, 1.87104184e-03 + 0.0j, 1.87104184e-03 + 0.0j, 5.59025092e-02 + 0.0j, 1.87104184e-03 + 0.0j, -1.87104184e-03 + 0.0j, 5.26365152e-02 + 0.0j, 8.44705692e-02 + 0.0j, ] ), [ (), ((0, "Z"),), ((0, "X"), (1, "Y"), (2, "Y")), ((0, "Y"), (1, "Y"), (2, "X")), ((0, "Z"), (1, "Z")), ((0, "Z"), (1, "X"), (3, "Z")), ((1, "X"), (2, "Z")), ((2, "Z"),), ((1, "Z"), (2, "Z"), (3, "Z")), ((1, "Z"),), ((0, "Y"), (1, "X"), (2, "Y")), ((0, "X"), (1, "X"), (2, "X")), ((1, "X"), (3, "Z")), ((0, "Z"), (1, "X"), (2, "Z")), ((0, "Y"), (1, "Z"), (2, "Y"), (3, "Z")), ((0, "X"), (1, "Z"), (2, "X")), ((0, "X"), (1, "Z"), (2, "X"), (3, "Z")), ((0, "Y"), (1, "Z"), (2, "Y")), ((0, "Z"), (2, "Z")), ((0, "Z"), (1, "Z"), (2, "Z"), (3, "Z")), ((0, "X"), (1, "X"), (2, "X"), (3, "Z")), ((0, "Y"), (1, "X"), (2, "Y"), (3, "Z")), ((0, "Z"), (1, "Z"), (2, "Z")), ((0, "Z"), (1, "X"), (2, "Z"), (3, "Z")), ((1, "X"),), ((0, "Z"), (2, "Z"), (3, "Z")), ((1, "Z"), (3, "Z")), ], ), ( "h2_pyscf", list(range(0)), list(range(2)), "jordan_WIGNER", np.array( [ -0.04207898 + 0.0j, 0.17771287 + 0.0j, 0.17771287 + 0.0j, -0.24274281 + 0.0j, -0.24274281 + 0.0j, 0.17059738 + 0.0j, 0.04475014 + 0.0j, -0.04475014 + 0.0j, -0.04475014 + 0.0j, 0.04475014 + 0.0j, 0.12293305 + 0.0j, 0.16768319 + 0.0j, 0.16768319 + 0.0j, 0.12293305 + 0.0j, 0.17627641 + 0.0j, ] ), [ (), ((0, "Z"),), ((1, "Z"),), ((2, "Z"),), ((3, "Z"),), ((0, "Z"), (1, "Z")), ((0, "Y"), (1, "X"), (2, "X"), (3, "Y")), ((0, "Y"), (1, "Y"), (2, "X"), (3, "X")), ((0, "X"), (1, "X"), (2, "Y"), (3, "Y")), ((0, "X"), (1, "Y"), (2, "Y"), (3, "X")), ((0, "Z"), (2, "Z")), ((0, "Z"), (3, "Z")), ((1, "Z"), (2, "Z")), ((1, "Z"), (3, "Z")), ((2, "Z"), (3, "Z")), ], ), ( "h2_pyscf", list(range(0)), list(range(2)), "BRAVYI_kitaev", np.array( [ -0.04207898 + 0.0j, 0.17771287 + 0.0j, 0.17771287 + 0.0j, -0.24274281 + 0.0j, -0.24274281 + 0.0j, 0.17059738 + 0.0j, 0.04475014 + 0.0j, 0.04475014 + 0.0j, 0.04475014 + 0.0j, 0.04475014 + 0.0j, 0.12293305 + 0.0j, 0.16768319 + 0.0j, 0.16768319 + 0.0j, 0.12293305 + 0.0j, 0.17627641 + 0.0j, ] ), [ (), ((0, "Z"),), ((0, "Z"), (1, "Z")), ((2, "Z"),), ((1, "Z"), (2, "Z"), (3, "Z")), ((1, "Z"),), ((0, "Y"), (1, "Z"), (2, "Y"), (3, "Z")), ((0, "X"), (1, "Z"), (2, "X")), ((0, "X"), (1, "Z"), (2, "X"), (3, "Z")), ((0, "Y"), (1, "Z"), (2, "Y")), ((0, "Z"), (2, "Z")), ((0, "Z"), (1, "Z"), (2, "Z"), (3, "Z")), ((0, "Z"), (1, "Z"), (2, "Z")), ((0, "Z"), (2, "Z"), (3, "Z")), ((1, "Z"), (3, "Z")), ], ), ( "h2o_psi4", list(range(3)), list(range(3, 6)), "jordan_WIGNER", np.array( [ -7.33320454e01 + 0.0j, 5.15279475e-01 + 0.0j, 7.77875498e-02 + 0.0j, 7.77875498e-02 + 0.0j, 5.15279475e-01 + 0.0j, 7.77875498e-02 + 0.0j, 7.77875498e-02 + 0.0j, 4.81292588e-01 + 0.0j, 4.81292588e-01 + 0.0j, 9.03094918e-02 + 0.0j, 9.03094918e-02 + 0.0j, 1.95659072e-01 + 0.0j, 3.03466140e-02 + 0.0j, 3.03466140e-02 + 0.0j, 1.39775966e-02 + 0.0j, -1.39775966e-02 + 0.0j, -1.39775966e-02 + 0.0j, 1.39775966e-02 + 0.0j, 3.03466140e-02 + 0.0j, 3.03466140e-02 + 0.0j, 1.71852512e-02 + 0.0j, -1.71852512e-02 + 0.0j, -1.71852512e-02 + 0.0j, 1.71852512e-02 + 0.0j, 1.68241745e-01 + 0.0j, 2.95127118e-02 + 0.0j, 2.95127118e-02 + 0.0j, 1.82219342e-01 + 0.0j, 2.90775939e-02 + 0.0j, 2.90775939e-02 + 0.0j, 4.35117913e-04 + 0.0j, 4.35117913e-04 + 0.0j, 4.35117913e-04 + 0.0j, 4.35117913e-04 + 0.0j, 1.20083139e-01 + 0.0j, 1.37268390e-01 + 0.0j, 1.11493731e-02 + 0.0j, 1.11493731e-02 + 0.0j, 1.82219342e-01 + 0.0j, 2.90775939e-02 + 0.0j, 2.90775939e-02 + 0.0j, 4.35117913e-04 + 0.0j, -4.35117913e-04 + 0.0j, -4.35117913e-04 + 0.0j, 4.35117913e-04 + 0.0j, 1.68241745e-01 + 0.0j, 2.95127118e-02 + 0.0j, 2.95127118e-02 + 0.0j, 1.37268390e-01 + 0.0j, 1.11493731e-02 + 0.0j, 1.11493731e-02 + 0.0j, 1.20083139e-01 + 0.0j, 2.20039773e-01 + 0.0j, 9.64747528e-03 + 0.0j, -9.64747528e-03 + 0.0j, -9.64747528e-03 + 0.0j, 9.64747528e-03 + 0.0j, 1.37589592e-01 + 0.0j, 1.47237067e-01 + 0.0j, 1.47237067e-01 + 0.0j, 1.37589592e-01 + 0.0j, 1.49282756e-01 + 0.0j, ] ), [ (), ((0, "Z"),), ((0, "Y"), (1, "Z"), (2, "Z"), (3, "Z"), (4, "Y")), ((0, "X"), (1, "Z"), (2, "Z"), (3, "Z"), (4, "X")), ((1, "Z"),), ((1, "Y"), (2, "Z"), (3, "Z"), (4, "Z"), (5, "Y")), ((1, "X"), (2, "Z"), (3, "Z"), (4, "Z"), (5, "X")), ((2, "Z"),), ((3, "Z"),), ((4, "Z"),), ((5, "Z"),), ((0, "Z"), (1, "Z")), ((0, "Y"), (2, "Z"), (3, "Z"), (4, "Y")), ((0, "X"), (2, "Z"), (3, "Z"), (4, "X")), ((0, "Y"), (1, "X"), (2, "X"), (3, "Y")), ((0, "Y"), (1, "Y"), (2, "X"), (3, "X")), ((0, "X"), (1, "X"), (2, "Y"), (3, "Y")), ((0, "X"), (1, "Y"), (2, "Y"), (3, "X")), ((0, "Z"), (1, "Y"), (2, "Z"), (3, "Z"), (4, "Z"), (5, "Y")), ((0, "Z"), (1, "X"), (2, "Z"), (3, "Z"), (4, "Z"), (5, "X")), ((0, "Y"), (1, "X"), (4, "X"), (5, "Y")), ((0, "Y"), (1, "Y"), (4, "X"), (5, "X")), ((0, "X"), (1, "X"), (4, "Y"), (5, "Y")), ((0, "X"), (1, "Y"), (4, "Y"), (5, "X")), ((0, "Z"), (2, "Z")), ((0, "Y"), (1, "Z"), (3, "Z"), (4, "Y")), ((0, "X"), (1, "Z"), (3, "Z"), (4, "X")), ((0, "Z"), (3, "Z")), ((0, "Y"), (1, "Z"), (2, "Z"), (4, "Y")), ((0, "X"), (1, "Z"), (2, "Z"), (4, "X")), ((0, "Y"), (1, "Z"), (2, "Y"), (3, "Y"), (4, "Z"), (5, "Y")), ((0, "Y"), (1, "Z"), (2, "Y"), (3, "X"), (4, "Z"), (5, "X")), ((0, "X"), (1, "Z"), (2, "X"), (3, "Y"), (4, "Z"), (5, "Y")), ((0, "X"), (1, "Z"), (2, "X"), (3, "X"), (4, "Z"), (5, "X")), ((0, "Z"), (4, "Z")), ((0, "Z"), (5, "Z")), ((0, "Y"), (1, "Z"), (2, "Z"), (3, "Z"), (4, "Y"), (5, "Z")), ((0, "X"), (1, "Z"), (2, "Z"), (3, "Z"), (4, "X"), (5, "Z")), ((1, "Z"), (2, "Z")), ((1, "Y"), (3, "Z"), (4, "Z"), (5, "Y")), ((1, "X"), (3, "Z"), (4, "Z"), (5, "X")), ((1, "Y"), (2, "X"), (3, "X"), (4, "Y")), ((1, "Y"), (2, "Y"), (3, "X"), (4, "X")), ((1, "X"), (2, "X"), (3, "Y"), (4, "Y")), ((1, "X"), (2, "Y"), (3, "Y"), (4, "X")), ((1, "Z"), (3, "Z")), ((1, "Y"), (2, "Z"), (4, "Z"), (5, "Y")), ((1, "X"), (2, "Z"), (4, "Z"), (5, "X")), ((1, "Z"), (4, "Z")), ((1, "Y"), (2, "Z"), (3, "Z"), (5, "Y")), ((1, "X"), (2, "Z"), (3, "Z"), (5, "X")), ((1, "Z"), (5, "Z")), ((2, "Z"), (3, "Z")), ((2, "Y"), (3, "X"), (4, "X"), (5, "Y")), ((2, "Y"), (3, "Y"), (4, "X"), (5, "X")), ((2, "X"), (3, "X"), (4, "Y"), (5, "Y")), ((2, "X"), (3, "Y"), (4, "Y"), (5, "X")), ((2, "Z"), (4, "Z")), ((2, "Z"), (5, "Z")), ((3, "Z"), (4, "Z")), ((3, "Z"), (5, "Z")), ((4, "Z"), (5, "Z")), ], ), ( "h2o_psi4", list(range(3)), list(range(3, 6)), "BRAVYI_kitaev", np.array( [ -7.33320454e01 + 0.0j, 5.15279475e-01 + 0.0j, 7.77875498e-02 + 0.0j, -7.77875498e-02 + 0.0j, 5.15279475e-01 + 0.0j, 7.77875498e-02 + 0.0j, -7.77875498e-02 + 0.0j, 4.81292588e-01 + 0.0j, 4.81292588e-01 + 0.0j, 9.03094918e-02 + 0.0j, 9.03094918e-02 + 0.0j, 1.95659072e-01 + 0.0j, -3.03466140e-02 + 0.0j, -3.03466140e-02 + 0.0j, 1.39775966e-02 + 0.0j, 1.39775966e-02 + 0.0j, 1.39775966e-02 + 0.0j, 1.39775966e-02 + 0.0j, 3.03466140e-02 + 0.0j, -3.03466140e-02 + 0.0j, 1.71852512e-02 + 0.0j, 1.71852512e-02 + 0.0j, 1.71852512e-02 + 0.0j, 1.71852512e-02 + 0.0j, 1.68241745e-01 + 0.0j, 2.95127118e-02 + 0.0j, -2.95127118e-02 + 0.0j, 1.82219342e-01 + 0.0j, 2.90775939e-02 + 0.0j, -2.90775939e-02 + 0.0j, -4.35117913e-04 + 0.0j, 4.35117913e-04 + 0.0j, -4.35117913e-04 + 0.0j, -4.35117913e-04 + 0.0j, 1.20083139e-01 + 0.0j, 1.37268390e-01 + 0.0j, 1.11493731e-02 + 0.0j, 1.11493731e-02 + 0.0j, 1.82219342e-01 + 0.0j, 2.90775939e-02 + 0.0j, -2.90775939e-02 + 0.0j, 4.35117913e-04 + 0.0j, -4.35117913e-04 + 0.0j, 4.35117913e-04 + 0.0j, 4.35117913e-04 + 0.0j, 1.68241745e-01 + 0.0j, 2.95127118e-02 + 0.0j, 2.95127118e-02 + 0.0j, 1.37268390e-01 + 0.0j, 1.11493731e-02 + 0.0j, -1.11493731e-02 + 0.0j, 1.20083139e-01 + 0.0j, 2.20039773e-01 + 0.0j, 9.64747528e-03 + 0.0j, 9.64747528e-03 + 0.0j, 9.64747528e-03 + 0.0j, 9.64747528e-03 + 0.0j, 1.37589592e-01 + 0.0j, 1.47237067e-01 + 0.0j, 1.47237067e-01 + 0.0j, 1.37589592e-01 + 0.0j, 1.49282756e-01 + 0.0j, ] ), [ (), ((0, "Z"),), ((0, "X"), (1, "X"), (3, "Y"), (4, "Y"), (5, "X")), ((0, "Y"), (1, "X"), (3, "Y"), (4, "X"), (5, "X")), ((0, "Z"), (1, "Z")), ((0, "Z"), (1, "X"), (3, "Y"), (5, "Y")), ((1, "Y"), (3, "Y"), (4, "Z"), (5, "X")), ((2, "Z"),), ((1, "Z"), (2, "Z"), (3, "Z")), ((4, "Z"),), ((4, "Z"), (5, "Z")), ((1, "Z"),), ((0, "Y"), (1, "Y"), (3, "Y"), (4, "Y"), (5, "X")), ((0, "X"), (1, "Y"), (3, "Y"), (4, "X"), (5, "X")), ((0, "Y"), (1, "Z"), (2, "Y"), (3, "Z")), ((0, "X"), (1, "Z"), (2, "X")), ((0, "X"), (1, "Z"), (2, "X"), (3, "Z")), ((0, "Y"), (1, "Z"), (2, "Y")), ((1, "X"), (3, "Y"), (5, "Y")), ((0, "Z"), (1, "Y"), (3, "Y"), (4, "Z"), (5, "X")), ((0, "Y"), (4, "Y"), (5, "Z")), ((0, "X"), (1, "Z"), (4, "X")), ((0, "X"), (4, "X"), (5, "Z")), ((0, "Y"), (1, "Z"), (4, "Y")), ((0, "Z"), (2, "Z")), ((0, "X"), (1, "X"), (2, "Z"), (3, "Y"), (4, "Y"), (5, "X")), ((0, "Y"), (1, "X"), (2, "Z"), (3, "Y"), (4, "X"), (5, "X")), ((0, "Z"), (1, "Z"), (2, "Z"), (3, "Z")), ((0, "X"), (1, "Y"), (2, "Z"), (3, "X"), (4, "Y"), (5, "X")), ((0, "Y"), (1, "Y"), (2, "Z"), (3, "X"), (4, "X"), (5, "X")), ((0, "X"), (1, "X"), (2, "X"), (3, "Y"), (5, "Y")), ((0, "X"), (1, "Y"), (2, "Y"), (3, "X"), (4, "Z"), (5, "X")), ((0, "Y"), (1, "X"), (2, "Y"), (3, "Y"), (5, "Y")), ((0, "Y"), (1, "Y"), (2, "X"), (3, "X"), (4, "Z"), (5, "X")), ((0, "Z"), (4, "Z")), ((0, "Z"), (4, "Z"), (5, "Z")), ((0, "X"), (1, "X"), (3, "Y"), (4, "X"), (5, "Y")), ((0, "Y"), (1, "X"), (3, "Y"), (4, "Y"), (5, "Y")), ((0, "Z"), (1, "Z"), (2, "Z")), ((0, "Z"), (1, "X"), (2, "Z"), (3, "Y"), (5, "Y")), ((1, "Y"), (2, "Z"), (3, "Y"), (4, "Z"), (5, "X")), ((0, "Z"), (1, "Y"), (2, "X"), (3, "X"), (4, "Y"), (5, "X")), ((0, "Z"), (1, "Y"), (2, "Y"), (3, "X"), (4, "X"), (5, "X")), ((1, "Y"), (2, "Y"), (3, "Y"), (4, "Y"), (5, "X")), ((1, "Y"), (2, "X"), (3, "Y"), (4, "X"), (5, "X")), ((0, "Z"), (2, "Z"), (3, "Z")), ((0, "Z"), (1, "Y"), (2, "Z"), (3, "X"), (5, "Y")), ((1, "X"), (2, "Z"), (3, "X"), (4, "Z"), (5, "X")), ((0, "Z"), (1, "Z"), (4, "Z")), ((0, "Z"), (1, "X"), (3, "Y"), (4, "Z"), (5, "Y")), ((1, "Y"), (3, "Y"), (5, "X")), ((0, "Z"), (1, "Z"), (4, "Z"), (5, "Z")), ((1, "Z"), (3, "Z")), ((2, "Y"), (4, "Y"), (5, "Z")), ((1, "Z"), (2, "X"), (3, "Z"), (4, "X")), ((2, "X"), (4, "X"), (5, "Z")), ((1, "Z"), (2, "Y"), (3, "Z"), (4, "Y")), ((2, "Z"), (4, "Z")), ((2, "Z"), (4, "Z"), (5, "Z")), ((1, "Z"), (2, "Z"), (3, "Z"), (4, "Z")), ((1, "Z"), (2, "Z"), (3, "Z"), (4, "Z"), (5, "Z")), ((5, "Z"),), ], ), ], ) @pytest.mark.usefixtures("skip_if_no_openfermion_support") def test_transformation(name, core, active, mapping, coeffs_ref, pauli_strings_ref, tol): r"""Test the correctness of the decomposed Hamiltonian for the (:math: `H_2, H_2O, LiH`) molecules using Jordan-Wigner and Bravyi-Kitaev transformations.""" hf_file = os.path.join(ref_dir, name) qubit_hamiltonian = qchem.decompose(hf_file, mapping=mapping, core=core, active=active) coeffs = np.array(list(qubit_hamiltonian.terms.values())) pauli_strings = list(qubit_hamiltonian.terms.keys()) assert np.allclose(coeffs, coeffs_ref, **tol) assert pauli_strings == pauli_strings_ref
pennylane/tests/qchem/openfermion_pyscf_tests/test_decompose.py/0
{ "file_path": "pennylane/tests/qchem/openfermion_pyscf_tests/test_decompose.py", "repo_id": "pennylane", "token_count": 16307 }
91
# Copyright 2018-2023 Xanadu Quantum Technologies Inc. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Unit tests for the ``two_particle`` function of FermionOperator in openfermion. """ import os import numpy as np import pytest from pennylane import qchem ref_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), "test_ref_files") v_op_1 = { (): 0.0, ((0, 1), (0, 1), (0, 0), (0, 0)): 0.3411947665760211, ((0, 1), (1, 1), (1, 0), (0, 0)): 0.3411947665760211, ((1, 1), (0, 1), (0, 0), (1, 0)): 0.3411947665760211, ((1, 1), (1, 1), (1, 0), (1, 0)): 0.3411947665760211, ((0, 1), (0, 1), (2, 0), (2, 0)): 0.08950028803070323, ((0, 1), (1, 1), (3, 0), (2, 0)): 0.08950028803070323, ((1, 1), (0, 1), (2, 0), (3, 0)): 0.08950028803070323, ((1, 1), (1, 1), (3, 0), (3, 0)): 0.08950028803070323, ((0, 1), (2, 1), (0, 0), (2, 0)): 0.08950028803070323, ((0, 1), (3, 1), (1, 0), (2, 0)): 0.08950028803070323, ((1, 1), (2, 1), (0, 0), (3, 0)): 0.08950028803070323, ((1, 1), (3, 1), (1, 0), (3, 0)): 0.08950028803070323, ((0, 1), (2, 1), (2, 0), (0, 0)): 0.3353663891543792, ((0, 1), (3, 1), (3, 0), (0, 0)): 0.3353663891543792, ((1, 1), (2, 1), (2, 0), (1, 0)): 0.3353663891543792, ((1, 1), (3, 1), (3, 0), (1, 0)): 0.3353663891543792, ((2, 1), (0, 1), (0, 0), (2, 0)): 0.3353663891543792, ((2, 1), (1, 1), (1, 0), (2, 0)): 0.3353663891543792, ((3, 1), (0, 1), (0, 0), (3, 0)): 0.3353663891543792, ((3, 1), (1, 1), (1, 0), (3, 0)): 0.3353663891543792, ((2, 1), (0, 1), (2, 0), (0, 0)): 0.08950028803070323, ((2, 1), (1, 1), (3, 0), (0, 0)): 0.08950028803070323, ((3, 1), (0, 1), (2, 0), (1, 0)): 0.08950028803070323, ((3, 1), (1, 1), (3, 0), (1, 0)): 0.08950028803070323, ((2, 1), (2, 1), (0, 0), (0, 0)): 0.08950028803070323, ((2, 1), (3, 1), (1, 0), (0, 0)): 0.08950028803070323, ((3, 1), (2, 1), (0, 0), (1, 0)): 0.08950028803070323, ((3, 1), (3, 1), (1, 0), (1, 0)): 0.08950028803070323, ((2, 1), (2, 1), (2, 0), (2, 0)): 0.352552816086392, ((2, 1), (3, 1), (3, 0), (2, 0)): 0.352552816086392, ((3, 1), (2, 1), (2, 0), (3, 0)): 0.352552816086392, ((3, 1), (3, 1), (3, 0), (3, 0)): 0.352552816086392, } v_op_2 = { (): 0.6823895331520422, ((0, 1), (0, 0)): 1.1624649805561105, ((1, 1), (1, 0)): 1.1624649805561105, ((0, 1), (0, 1), (0, 0), (0, 0)): 0.352552816086392, ((0, 1), (1, 1), (1, 0), (0, 0)): 0.352552816086392, ((1, 1), (0, 1), (0, 0), (1, 0)): 0.352552816086392, ((1, 1), (1, 1), (1, 0), (1, 0)): 0.352552816086392, } v_op_3 = { (): 1.6585666870874103, ((0, 1), (0, 0)): 0.7200645027092623, ((1, 1), (1, 0)): 0.7200645027092623, ((0, 1), (2, 0)): 0.01568677271778423, ((1, 1), (3, 0)): 0.01568677271778423, ((2, 1), (0, 0)): 0.01568677271778432, ((3, 1), (1, 0)): 0.01568677271778432, ((2, 1), (2, 0)): 0.7696051973390092, ((3, 1), (3, 0)): 0.7696051973390092, ((0, 1), (0, 1), (0, 0), (0, 0)): 0.24365548437056841, ((0, 1), (1, 1), (1, 0), (0, 0)): 0.24365548437056841, ((1, 1), (0, 1), (0, 0), (1, 0)): 0.24365548437056841, ((1, 1), (1, 1), (1, 0), (1, 0)): 0.24365548437056841, ((0, 1), (0, 1), (0, 0), (2, 0)): -0.02428978770367371, ((0, 1), (1, 1), (1, 0), (2, 0)): -0.02428978770367371, ((1, 1), (0, 1), (0, 0), (3, 0)): -0.02428978770367371, ((1, 1), (1, 1), (1, 0), (3, 0)): -0.02428978770367371, ((0, 1), (0, 1), (2, 0), (0, 0)): -0.024289787703673717, ((0, 1), (1, 1), (3, 0), (0, 0)): -0.024289787703673717, ((1, 1), (0, 1), (2, 0), (1, 0)): -0.024289787703673717, ((1, 1), (1, 1), (3, 0), (1, 0)): -0.024289787703673717, ((0, 1), (0, 1), (2, 0), (2, 0)): 0.006531987971873417, ((0, 1), (1, 1), (3, 0), (2, 0)): 0.006531987971873417, ((1, 1), (0, 1), (2, 0), (3, 0)): 0.006531987971873417, ((1, 1), (1, 1), (3, 0), (3, 0)): 0.006531987971873417, ((0, 1), (2, 1), (0, 0), (0, 0)): -0.02428978770367371, ((0, 1), (3, 1), (1, 0), (0, 0)): -0.02428978770367371, ((1, 1), (2, 1), (0, 0), (1, 0)): -0.02428978770367371, ((1, 1), (3, 1), (1, 0), (1, 0)): -0.02428978770367371, ((0, 1), (2, 1), (0, 0), (2, 0)): 0.006531987971873418, ((0, 1), (3, 1), (1, 0), (2, 0)): 0.006531987971873418, ((1, 1), (2, 1), (0, 0), (3, 0)): 0.006531987971873418, ((1, 1), (3, 1), (1, 0), (3, 0)): 0.006531987971873418, ((0, 1), (2, 1), (2, 0), (0, 0)): 0.11180501845367194, ((0, 1), (3, 1), (3, 0), (0, 0)): 0.11180501845367194, ((1, 1), (2, 1), (2, 0), (1, 0)): 0.11180501845367194, ((1, 1), (3, 1), (3, 0), (1, 0)): 0.11180501845367194, ((0, 1), (2, 1), (2, 0), (2, 0)): 0.0037420836721733935, ((0, 1), (3, 1), (3, 0), (2, 0)): 0.0037420836721733935, ((1, 1), (2, 1), (2, 0), (3, 0)): 0.0037420836721733935, ((1, 1), (3, 1), (3, 0), (3, 0)): 0.0037420836721733935, ((2, 1), (0, 1), (0, 0), (0, 0)): -0.02428978770367371, ((2, 1), (1, 1), (1, 0), (0, 0)): -0.02428978770367371, ((3, 1), (0, 1), (0, 0), (1, 0)): -0.02428978770367371, ((3, 1), (1, 1), (1, 0), (1, 0)): -0.02428978770367371, ((2, 1), (0, 1), (0, 0), (2, 0)): 0.11180501845367194, ((2, 1), (1, 1), (1, 0), (2, 0)): 0.11180501845367194, ((3, 1), (0, 1), (0, 0), (3, 0)): 0.11180501845367194, ((3, 1), (1, 1), (1, 0), (3, 0)): 0.11180501845367194, ((2, 1), (0, 1), (2, 0), (0, 0)): 0.006531987971873418, ((2, 1), (1, 1), (3, 0), (0, 0)): 0.006531987971873418, ((3, 1), (0, 1), (2, 0), (1, 0)): 0.006531987971873418, ((3, 1), (1, 1), (3, 0), (1, 0)): 0.006531987971873418, ((2, 1), (0, 1), (2, 0), (2, 0)): 0.003742083672173376, ((2, 1), (1, 1), (3, 0), (2, 0)): 0.003742083672173376, ((3, 1), (0, 1), (2, 0), (3, 0)): 0.003742083672173376, ((3, 1), (1, 1), (3, 0), (3, 0)): 0.003742083672173376, ((2, 1), (2, 1), (0, 0), (0, 0)): 0.006531987971873423, ((2, 1), (3, 1), (1, 0), (0, 0)): 0.006531987971873423, ((3, 1), (2, 1), (0, 0), (1, 0)): 0.006531987971873423, ((3, 1), (3, 1), (1, 0), (1, 0)): 0.006531987971873423, ((2, 1), (2, 1), (0, 0), (2, 0)): 0.0037420836721733645, ((2, 1), (3, 1), (1, 0), (2, 0)): 0.0037420836721733645, ((3, 1), (2, 1), (0, 0), (3, 0)): 0.0037420836721733645, ((3, 1), (3, 1), (1, 0), (3, 0)): 0.0037420836721733645, ((2, 1), (2, 1), (2, 0), (0, 0)): 0.0037420836721733727, ((2, 1), (3, 1), (3, 0), (0, 0)): 0.0037420836721733727, ((3, 1), (2, 1), (2, 0), (1, 0)): 0.0037420836721733727, ((3, 1), (3, 1), (3, 0), (1, 0)): 0.0037420836721733727, ((2, 1), (2, 1), (2, 0), (2, 0)): 0.16894113834436625, ((2, 1), (3, 1), (3, 0), (2, 0)): 0.16894113834436625, ((3, 1), (2, 1), (2, 0), (3, 0)): 0.16894113834436625, ((3, 1), (3, 1), (3, 0), (3, 0)): 0.16894113834436625, } v_op_4 = { (): 15.477079668766912, ((0, 1), (0, 0)): 4.348718720149925, ((1, 1), (1, 0)): 4.348718720149925, ((2, 1), (2, 0)): 4.7839298822632825, ((3, 1), (3, 0)): 4.7839298822632825, ((4, 1), (4, 0)): 3.9720173194427786, ((5, 1), (5, 0)): 3.9720173194427786, ((0, 1), (0, 1), (0, 0), (0, 0)): 0.3913181430816212, ((0, 1), (1, 1), (1, 0), (0, 0)): 0.3913181430816212, ((1, 1), (0, 1), (0, 0), (1, 0)): 0.3913181430816212, ((1, 1), (1, 1), (1, 0), (1, 0)): 0.3913181430816212, ((0, 1), (0, 1), (2, 0), (2, 0)): 0.02795519311163234, ((0, 1), (1, 1), (3, 0), (2, 0)): 0.02795519311163234, ((1, 1), (0, 1), (2, 0), (3, 0)): 0.02795519311163234, ((1, 1), (1, 1), (3, 0), (3, 0)): 0.02795519311163234, ((0, 1), (0, 1), (4, 0), (4, 0)): 0.03448849005311543, ((0, 1), (1, 1), (5, 0), (4, 0)): 0.03448849005311543, ((1, 1), (0, 1), (4, 0), (5, 0)): 0.03448849005311543, ((1, 1), (1, 1), (5, 0), (5, 0)): 0.03448849005311543, ((0, 1), (2, 1), (0, 0), (2, 0)): 0.02795519311163234, ((0, 1), (3, 1), (1, 0), (2, 0)): 0.02795519311163234, ((1, 1), (2, 1), (0, 0), (3, 0)): 0.02795519311163234, ((1, 1), (3, 1), (1, 0), (3, 0)): 0.02795519311163234, ((0, 1), (2, 1), (2, 0), (0, 0)): 0.36443868319762635, ((0, 1), (3, 1), (3, 0), (0, 0)): 0.36443868319762635, ((1, 1), (2, 1), (2, 0), (1, 0)): 0.36443868319762635, ((1, 1), (3, 1), (3, 0), (1, 0)): 0.36443868319762635, ((0, 1), (4, 1), (0, 0), (4, 0)): 0.03448849005311544, ((0, 1), (5, 1), (1, 0), (4, 0)): 0.03448849005311544, ((1, 1), (4, 1), (0, 0), (5, 0)): 0.03448849005311544, ((1, 1), (5, 1), (1, 0), (5, 0)): 0.03448849005311544, ((0, 1), (4, 1), (4, 0), (0, 0)): 0.3041058444913643, ((0, 1), (5, 1), (5, 0), (0, 0)): 0.3041058444913643, ((1, 1), (4, 1), (4, 0), (1, 0)): 0.3041058444913643, ((1, 1), (5, 1), (5, 0), (1, 0)): 0.3041058444913643, ((2, 1), (0, 1), (0, 0), (2, 0)): 0.36443868319762635, ((2, 1), (1, 1), (1, 0), (2, 0)): 0.36443868319762635, ((3, 1), (0, 1), (0, 0), (3, 0)): 0.36443868319762635, ((3, 1), (1, 1), (1, 0), (3, 0)): 0.36443868319762635, ((2, 1), (0, 1), (2, 0), (0, 0)): 0.02795519311163234, ((2, 1), (1, 1), (3, 0), (0, 0)): 0.02795519311163234, ((3, 1), (0, 1), (2, 0), (1, 0)): 0.02795519311163234, ((3, 1), (1, 1), (3, 0), (1, 0)): 0.02795519311163234, ((2, 1), (2, 1), (0, 0), (0, 0)): 0.02795519311163234, ((2, 1), (3, 1), (1, 0), (0, 0)): 0.02795519311163234, ((3, 1), (2, 1), (0, 0), (1, 0)): 0.02795519311163234, ((3, 1), (3, 1), (1, 0), (1, 0)): 0.02795519311163234, ((2, 1), (2, 1), (2, 0), (2, 0)): 0.44007954668752236, ((2, 1), (3, 1), (3, 0), (2, 0)): 0.44007954668752236, ((3, 1), (2, 1), (2, 0), (3, 0)): 0.44007954668752236, ((3, 1), (3, 1), (3, 0), (3, 0)): 0.44007954668752236, ((2, 1), (2, 1), (4, 0), (4, 0)): 0.012175350836228654, ((2, 1), (3, 1), (5, 0), (4, 0)): 0.012175350836228654, ((3, 1), (2, 1), (4, 0), (5, 0)): 0.012175350836228654, ((3, 1), (3, 1), (5, 0), (5, 0)): 0.012175350836228654, ((2, 1), (4, 1), (2, 0), (4, 0)): 0.012175350836228654, ((2, 1), (5, 1), (3, 0), (4, 0)): 0.012175350836228654, ((3, 1), (4, 1), (2, 0), (5, 0)): 0.012175350836228654, ((3, 1), (5, 1), (3, 0), (5, 0)): 0.012175350836228654, ((2, 1), (4, 1), (4, 0), (2, 0)): 0.3124924051344332, ((2, 1), (5, 1), (5, 0), (2, 0)): 0.3124924051344332, ((3, 1), (4, 1), (4, 0), (3, 0)): 0.3124924051344332, ((3, 1), (5, 1), (5, 0), (3, 0)): 0.3124924051344332, ((4, 1), (0, 1), (0, 0), (4, 0)): 0.3041058444913643, ((4, 1), (1, 1), (1, 0), (4, 0)): 0.3041058444913643, ((5, 1), (0, 1), (0, 0), (5, 0)): 0.3041058444913643, ((5, 1), (1, 1), (1, 0), (5, 0)): 0.3041058444913643, ((4, 1), (0, 1), (4, 0), (0, 0)): 0.034488490053115425, ((4, 1), (1, 1), (5, 0), (0, 0)): 0.034488490053115425, ((5, 1), (0, 1), (4, 0), (1, 0)): 0.034488490053115425, ((5, 1), (1, 1), (5, 0), (1, 0)): 0.034488490053115425, ((4, 1), (2, 1), (2, 0), (4, 0)): 0.3124924051344332, ((4, 1), (3, 1), (3, 0), (4, 0)): 0.3124924051344332, ((5, 1), (2, 1), (2, 0), (5, 0)): 0.3124924051344332, ((5, 1), (3, 1), (3, 0), (5, 0)): 0.3124924051344332, ((4, 1), (2, 1), (4, 0), (2, 0)): 0.012175350836228654, ((4, 1), (3, 1), (5, 0), (2, 0)): 0.012175350836228654, ((5, 1), (2, 1), (4, 0), (3, 0)): 0.012175350836228654, ((5, 1), (3, 1), (5, 0), (3, 0)): 0.012175350836228654, ((4, 1), (4, 1), (0, 0), (0, 0)): 0.03448849005311543, ((4, 1), (5, 1), (1, 0), (0, 0)): 0.03448849005311543, ((5, 1), (4, 1), (0, 0), (1, 0)): 0.03448849005311543, ((5, 1), (5, 1), (1, 0), (1, 0)): 0.03448849005311543, ((4, 1), (4, 1), (2, 0), (2, 0)): 0.012175350836228654, ((4, 1), (5, 1), (3, 0), (2, 0)): 0.012175350836228654, ((5, 1), (4, 1), (2, 0), (3, 0)): 0.012175350836228654, ((5, 1), (5, 1), (3, 0), (3, 0)): 0.012175350836228654, ((4, 1), (4, 1), (4, 0), (4, 0)): 0.3097576511847101, ((4, 1), (5, 1), (5, 0), (4, 0)): 0.3097576511847101, ((5, 1), (4, 1), (4, 0), (5, 0)): 0.3097576511847101, ((5, 1), (5, 1), (5, 0), (5, 0)): 0.3097576511847101, } @pytest.mark.parametrize( ("name", "core", "active", "v_op_exp"), [ ("h2_pyscf", None, None, v_op_1), ("h2_pyscf", [0], None, v_op_2), ("h2_pyscf", None, [0, 1], v_op_1), ("lih", [0], [1, 2], v_op_3), ("h2o_psi4", [0, 1, 2], [3, 4, 6], v_op_4), ], ) @pytest.mark.usefixtures("skip_if_no_openfermion_support") def test_table_two_particle(name, core, active, v_op_exp): r"""Test the FermionOperator built by the function `two_particle` of the `obs` module""" import openfermion hf_data = openfermion.MolecularData(filename=os.path.join(ref_dir, name)) v_op = qchem.two_particle(hf_data.two_body_integrals, core=core, active=active) assert v_op.terms == v_op_exp v_me_1D = np.array([1, 2, 3, 4]) v_me_4D = np.full((2, 2, 2, 2), 0.5) @pytest.mark.parametrize( ("v_me", "core", "active", "msg_match"), [ (v_me_1D, [0], None, "'matrix_elements' must be a 4D array"), (v_me_4D, [-1, 0, 1, 2], None, "Indices of core orbitals must be between 0 and"), (v_me_4D, [0, 1, 2, 3], None, "Indices of core orbitals must be between 0 and"), (v_me_4D, None, [-1, 0], "Indices of active orbitals must be between 0 and"), (v_me_4D, None, [2, 6], "Indices of active orbitals must be between 0 and"), ], ) @pytest.mark.usefixtures("skip_if_no_openfermion_support") def test_exceptions_two_particle(v_me, core, active, msg_match): """Test that the function `'two_particle'` throws an exception if the dimension of the matrix elements array is not a 4D array or if the indices of core and/or active orbitals are out of range.""" with pytest.raises(ValueError, match=msg_match): qchem.two_particle(v_me, core=core, active=active)
pennylane/tests/qchem/openfermion_pyscf_tests/test_two_particle.py/0
{ "file_path": "pennylane/tests/qchem/openfermion_pyscf_tests/test_two_particle.py", "repo_id": "pennylane", "token_count": 8032 }
92
# Copyright 2022 Xanadu Quantum Technologies Inc. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Unit tests for differentiable quantum entropies. """ # pylint: disable=too-many-arguments import pytest import pennylane as qml from pennylane import numpy as np def expected_entropy_ising_xx(param): """ Return the analytical entropy for the IsingXX. """ eigs = [np.cos(param / 2) ** 2, np.sin(param / 2) ** 2] eigs = [eig for eig in eigs if eig > 0] expected_entropy = eigs * np.log(eigs) expected_entropy = -np.sum(expected_entropy) return expected_entropy def expected_entropy_grad_ising_xx(param): """ Return the analytical gradient entropy for the IsingXX. """ eig_1 = (1 + np.sqrt(1 - 4 * np.cos(param / 2) ** 2 * np.sin(param / 2) ** 2)) / 2 eig_2 = (1 - np.sqrt(1 - 4 * np.cos(param / 2) ** 2 * np.sin(param / 2) ** 2)) / 2 eigs = [eig_1, eig_2] eigs = np.maximum(eigs, 1e-08) grad_expected_entropy = -( (np.log(eigs[0]) + 1) * (np.sin(param / 2) ** 3 * np.cos(param / 2) - np.sin(param / 2) * np.cos(param / 2) ** 3) / np.sqrt(1 - 4 * np.cos(param / 2) ** 2 * np.sin(param / 2) ** 2) ) - ( (np.log(eigs[1]) + 1) * ( np.sin(param / 2) * np.cos(param / 2) * (np.cos(param / 2) ** 2 - np.sin(param / 2) ** 2) ) / np.sqrt(1 - 4 * np.cos(param / 2) ** 2 * np.sin(param / 2) ** 2) ) return grad_expected_entropy class TestVonNeumannEntropy: """Tests Von Neumann entropy transform""" single_wires_list = [[0], [1]] base = [2, np.exp(1), 10] check_state = [True, False] parameters = np.linspace(0, 2 * np.pi, 10) devices = ["default.qubit", "default.mixed", "lightning.qubit"] def test_vn_entropy_cannot_specify_device(self): """Test that an error is raised if a device or device wires are given to the vn_entropy transform manually.""" dev = qml.device("default.qubit", wires=2) @qml.qnode(dev) def circuit(params): qml.RY(params, wires=0) qml.CNOT(wires=[0, 1]) return qml.state() with pytest.raises(ValueError, match="Cannot provide a 'device' value"): _ = qml.qinfo.vn_entropy(circuit, wires=[0], device=dev) with pytest.raises(ValueError, match="Cannot provide a 'device_wires' value"): _ = qml.qinfo.vn_entropy(circuit, wires=[0], device_wires=dev.wires) @pytest.mark.parametrize("wires", single_wires_list) @pytest.mark.parametrize("param", parameters) @pytest.mark.parametrize("device", devices) @pytest.mark.parametrize("base", base) def test_IsingXX_qnode_entropy(self, param, wires, device, base): """Test entropy for a QNode numpy.""" dev = qml.device(device, wires=2) @qml.qnode(dev) def circuit_state(x): qml.IsingXX(x, wires=[0, 1]) return qml.state() entropy = qml.qinfo.vn_entropy(circuit_state, wires=wires, base=base)(param) expected_entropy = expected_entropy_ising_xx(param) / np.log(base) assert qml.math.allclose(entropy, expected_entropy) interfaces = ["auto", "autograd"] @pytest.mark.autograd @pytest.mark.parametrize("wires", single_wires_list) @pytest.mark.parametrize("param", parameters) @pytest.mark.parametrize("base", base) @pytest.mark.parametrize("interface", interfaces) def test_IsingXX_qnode_entropy_grad(self, param, wires, base, interface): """Test entropy for a QNode gradient with autograd.""" dev = qml.device("default.qubit", wires=2) @qml.qnode(dev, interface=interface) def circuit_state(x): qml.IsingXX(x, wires=[0, 1]) return qml.state() grad_entropy = qml.grad(qml.qinfo.vn_entropy(circuit_state, wires=wires, base=base))(param) grad_expected_entropy = expected_entropy_grad_ising_xx(param) / np.log(base) assert qml.math.allclose(grad_entropy, grad_expected_entropy) interfaces = ["torch"] @pytest.mark.torch @pytest.mark.parametrize("wires", single_wires_list) @pytest.mark.parametrize("param", parameters) @pytest.mark.parametrize("device", devices) @pytest.mark.parametrize("base", base) @pytest.mark.parametrize("interface", interfaces) def test_IsingXX_qnode_torch_entropy(self, param, wires, device, base, interface): """Test entropy for a QNode with torch interface.""" import torch dev = qml.device(device, wires=2) @qml.qnode(dev, interface=interface) def circuit_state(x): qml.IsingXX(x, wires=[0, 1]) return qml.state() entropy = qml.qinfo.vn_entropy(circuit_state, wires=wires, base=base)(torch.tensor(param)) expected_entropy = expected_entropy_ising_xx(param) / np.log(base) assert qml.math.allclose(entropy, expected_entropy) @pytest.mark.torch @pytest.mark.parametrize("wires", single_wires_list) @pytest.mark.parametrize("param", parameters) @pytest.mark.parametrize("base", base) @pytest.mark.parametrize("interface", interfaces) def test_IsingXX_qnode_entropy_grad_torch(self, param, wires, base, interface): """Test entropy for a QNode gradient with torch.""" import torch dev = qml.device("default.qubit", wires=2) @qml.qnode(dev, interface=interface, diff_method="backprop") def circuit_state(x): qml.IsingXX(x, wires=[0, 1]) return qml.state() eig_1 = (1 + np.sqrt(1 - 4 * np.cos(param / 2) ** 2 * np.sin(param / 2) ** 2)) / 2 eig_2 = (1 - np.sqrt(1 - 4 * np.cos(param / 2) ** 2 * np.sin(param / 2) ** 2)) / 2 eigs = [eig_1, eig_2] eigs = np.maximum(eigs, 1e-08) grad_expected_entropy = expected_entropy_grad_ising_xx(param) / np.log(base) param = torch.tensor(param, dtype=torch.float64, requires_grad=True) entropy = qml.qinfo.vn_entropy(circuit_state, wires=wires, base=base)(param) entropy.backward() grad_entropy = param.grad assert qml.math.allclose(grad_entropy, grad_expected_entropy) interfaces = ["tf"] @pytest.mark.tf @pytest.mark.parametrize("wires", single_wires_list) @pytest.mark.parametrize("param", parameters) @pytest.mark.parametrize("device", devices) @pytest.mark.parametrize("base", base) @pytest.mark.parametrize("interface", interfaces) def test_IsingXX_qnode_tf_entropy(self, param, wires, device, base, interface): """Test entropy for a QNode with tf interface.""" import tensorflow as tf dev = qml.device(device, wires=2) @qml.qnode(dev, interface=interface) def circuit_state(x): qml.IsingXX(x, wires=[0, 1]) return qml.state() entropy = qml.qinfo.vn_entropy(circuit_state, wires=wires, base=base)(tf.Variable(param)) expected_entropy = expected_entropy_ising_xx(param) / np.log(base) assert qml.math.allclose(entropy, expected_entropy) @pytest.mark.tf @pytest.mark.parametrize("wires", single_wires_list) @pytest.mark.parametrize("param", parameters) @pytest.mark.parametrize("base", base) @pytest.mark.parametrize("interface", interfaces) def test_IsingXX_qnode_entropy_grad_tf(self, param, wires, base, interface): """Test entropy for a QNode gradient with tf.""" import tensorflow as tf dev = qml.device("default.qubit", wires=2) @qml.qnode(dev, interface=interface, diff_method="backprop") def circuit_state(x): qml.IsingXX(x, wires=[0, 1]) return qml.state() param = tf.Variable(param) with tf.GradientTape() as tape: entropy = qml.qinfo.vn_entropy(circuit_state, wires=wires, base=base)(param) grad_entropy = tape.gradient(entropy, param) grad_expected_entropy = expected_entropy_grad_ising_xx(param) / np.log(base) assert qml.math.allclose(grad_entropy, grad_expected_entropy) interfaces = ["jax"] @pytest.mark.jax @pytest.mark.parametrize("wires", single_wires_list) @pytest.mark.parametrize("param", parameters) @pytest.mark.parametrize("device", devices) @pytest.mark.parametrize("base", base) @pytest.mark.parametrize("interface", interfaces) def test_IsingXX_qnode_jax_entropy(self, param, wires, device, base, interface): """Test entropy for a QNode with jax interface.""" import jax.numpy as jnp dev = qml.device(device, wires=2) @qml.qnode(dev, interface=interface) def circuit_state(x): qml.IsingXX(x, wires=[0, 1]) return qml.state() entropy = qml.qinfo.vn_entropy(circuit_state, wires=wires, base=base)(jnp.array(param)) expected_entropy = expected_entropy_ising_xx(param) / np.log(base) assert qml.math.allclose(entropy, expected_entropy) @pytest.mark.jax @pytest.mark.parametrize("wires", single_wires_list) @pytest.mark.parametrize("param", parameters) @pytest.mark.parametrize("base", base) @pytest.mark.parametrize("interface", interfaces) def test_IsingXX_qnode_entropy_grad_jax(self, param, wires, base, interface): """Test entropy for a QNode gradient with Jax.""" import jax dev = qml.device("default.qubit", wires=2) @qml.qnode(dev, interface=interface, diff_method="backprop") def circuit_state(x): qml.IsingXX(x, wires=[0, 1]) return qml.state() grad_entropy = jax.grad(qml.qinfo.vn_entropy(circuit_state, wires=wires, base=base))( jax.numpy.array(param) ) grad_expected_entropy = expected_entropy_grad_ising_xx(param) / np.log(base) assert qml.math.allclose(grad_entropy, grad_expected_entropy, rtol=1e-04, atol=1e-05) interfaces = ["jax-jit"] @pytest.mark.jax @pytest.mark.parametrize("wires", single_wires_list) @pytest.mark.parametrize("param", parameters) @pytest.mark.parametrize("base", base) @pytest.mark.parametrize("interface", interfaces) def test_IsingXX_qnode_jax_jit_entropy(self, param, wires, base, interface): """Test entropy for a QNode with jax-jit interface.""" import jax import jax.numpy as jnp dev = qml.device("default.qubit", wires=2) @qml.qnode(dev, interface=interface) def circuit_state(x): qml.IsingXX(x, wires=[0, 1]) return qml.state() entropy = jax.jit(qml.qinfo.vn_entropy(circuit_state, wires=wires, base=base))( jnp.array(param) ) expected_entropy = expected_entropy_ising_xx(param) / np.log(base) assert qml.math.allclose(entropy, expected_entropy) @pytest.mark.jax @pytest.mark.parametrize("wires", single_wires_list) @pytest.mark.parametrize("param", parameters) @pytest.mark.parametrize("base", base) @pytest.mark.parametrize("interface", interfaces) def test_IsingXX_qnode_entropy_grad_jax_jit(self, param, wires, base, interface): """Test entropy for a QNode gradient with Jax-jit.""" import jax dev = qml.device("default.qubit", wires=2) @qml.qnode(dev, interface=interface, diff_method="backprop") def circuit_state(x): qml.IsingXX(x, wires=[0, 1]) return qml.state() grad_entropy = jax.jit( jax.grad(qml.qinfo.vn_entropy(circuit_state, wires=wires, base=base)) )(jax.numpy.array(param)) grad_expected_entropy = expected_entropy_grad_ising_xx(param) / np.log(base) assert qml.math.allclose(grad_entropy, grad_expected_entropy, rtol=1e-04, atol=1e-05) def test_qnode_entropy_wires_full_range_not_state(self): """Test entropy needs a QNode returning state.""" param = 0.1 dev = qml.device("default.qubit", wires=2) @qml.qnode(dev) def circuit_state(x): qml.IsingXX(x, wires=[0, 1]) return qml.expval(qml.PauliX(wires=0)) with pytest.raises( ValueError, match="The qfunc return type needs to be a state.", ): qml.qinfo.vn_entropy(circuit_state, wires=[0, 1])(param) def test_qnode_entropy_wires_full_range_state_vector(self): """Test entropy for a QNode that returns a state vector with all wires, entropy is 0.""" param = 0.1 dev = qml.device("default.qubit", wires=2) @qml.qnode(dev) def circuit_state(x): qml.IsingXX(x, wires=[0, 1]) return qml.state() entropy = qml.qinfo.vn_entropy(circuit_state, wires=[0, 1])(param) expected_entropy = 0.0 assert qml.math.allclose(entropy, expected_entropy) def test_qnode_entropy_wires_full_range_density_mat(self): """Test entropy for a QNode that returns a density mat with all wires, entropy is 0.""" param = 0.1 dev = qml.device("default.mixed", wires=2) @qml.qnode(dev) def circuit_state(x): qml.IsingXX(x, wires=[0, 1]) return qml.state() entropy = qml.qinfo.vn_entropy(circuit_state, wires=[0, 1])(param) expected_entropy = 0.0 assert qml.math.allclose(entropy, expected_entropy) @pytest.mark.parametrize("device", devices) def test_entropy_wire_labels(self, device, tol): """Test that vn_entropy is correct with custom wire labels""" param = np.array(1.234) wires = ["a", 8] dev = qml.device(device, wires=wires) @qml.qnode(dev) def circuit(x): qml.PauliX(wires=wires[0]) qml.IsingXX(x, wires=wires) return qml.state() entropy0 = qml.qinfo.vn_entropy(circuit, wires=[wires[0]])(param) eigs0 = [np.sin(param / 2) ** 2, np.cos(param / 2) ** 2] exp0 = -np.sum(eigs0 * np.log(eigs0)) entropy1 = qml.qinfo.vn_entropy(circuit, wires=[wires[1]])(param) eigs1 = [np.cos(param / 2) ** 2, np.sin(param / 2) ** 2] exp1 = -np.sum(eigs1 * np.log(eigs1)) assert np.allclose(exp0, entropy0, atol=tol) assert np.allclose(exp1, entropy1, atol=tol) class TestRelativeEntropy: """Tests for the mutual information functions""" diff_methods = ["backprop", "finite-diff"] params = [[0.0, 0.0], [np.pi, 0.0], [0.0, np.pi], [0.123, 0.456], [0.789, 1.618]] # to avoid nan values in the gradient for relative entropy grad_params = [[0.123, 0.456], [0.789, 1.618]] @pytest.mark.all_interfaces @pytest.mark.parametrize("device", ["default.qubit", "default.mixed", "lightning.qubit"]) @pytest.mark.parametrize("interface", ["autograd", "jax", "tensorflow", "torch"]) @pytest.mark.parametrize("param", params) def test_qnode_relative_entropy(self, device, interface, param): """Test that the relative entropy transform works for QNodes by comparing against analytic values""" dev = qml.device(device, wires=2) param = qml.math.asarray(np.array(param), like=interface) @qml.qnode(dev, interface=interface) def circuit1(param): qml.RY(param, wires=0) qml.CNOT(wires=[0, 1]) return qml.state() @qml.qnode(dev, interface=interface) def circuit2(param): qml.RY(param, wires=0) qml.CNOT(wires=[0, 1]) return qml.state() rel_ent_circuit = qml.qinfo.relative_entropy(circuit1, circuit2, [0], [1]) actual = rel_ent_circuit((param[0],), (param[1],)) # compare transform results with analytic results first_term = ( 0 if np.cos(param[0] / 2) == 0 else np.cos(param[0] / 2) ** 2 * (np.log(np.cos(param[0] / 2) ** 2) - np.log(np.cos(param[1] / 2) ** 2)) ) second_term = ( 0 if np.sin(param[0] / 2) == 0 else np.sin(param[0] / 2) ** 2 * (np.log(np.sin(param[0] / 2) ** 2) - np.log(np.sin(param[1] / 2) ** 2)) ) expected = first_term + second_term assert np.allclose(actual, expected) interfaces = ["jax-jit"] @pytest.mark.jax @pytest.mark.parametrize("param", params) @pytest.mark.parametrize("interface", interfaces) def test_qnode_relative_entropy_jax_jit(self, param, interface): """Test that the mutual information transform works for QNodes by comparing against analytic values, for the JAX-jit interface""" import jax import jax.numpy as jnp dev = qml.device("default.qubit", wires=2) param = jnp.array(param) @qml.qnode(dev, interface=interface) def circuit1(params): qml.RY(params, wires=0) qml.CNOT(wires=[0, 1]) return qml.state() @qml.qnode(dev, interface=interface) def circuit2(params): qml.RY(params, wires=0) qml.CNOT(wires=[0, 1]) return qml.state() rel_ent_circuit = qml.qinfo.relative_entropy(circuit1, circuit2, [0], [1]) actual = jax.jit(rel_ent_circuit)((param[0],), (param[1],)) # compare transform results with analytic results first_term = ( 0 if jnp.cos(param[0] / 2) == 0 else jnp.cos(param[0] / 2) ** 2 * (jnp.log(jnp.cos(param[0] / 2) ** 2) - jnp.log(jnp.cos(param[1] / 2) ** 2)) ) second_term = ( 0 if jnp.sin(param[0] / 2) == 0 else jnp.sin(param[0] / 2) ** 2 * (jnp.log(jnp.sin(param[0] / 2) ** 2) - jnp.log(jnp.sin(param[1] / 2) ** 2)) ) expected = first_term + second_term assert np.allclose(actual, expected) @pytest.mark.jax @pytest.mark.parametrize("param", grad_params) @pytest.mark.parametrize("interface", interfaces) def test_qnode_grad_jax(self, param, interface): """Test that the gradient of relative entropy works for QNodes with the JAX interface""" import jax import jax.numpy as jnp dev = qml.device("default.qubit", wires=2) @qml.qnode(dev, interface=interface, diff_method="backprop") def circuit1(param): qml.RY(param, wires=0) qml.CNOT(wires=[0, 1]) return qml.state() @qml.qnode(dev, interface=interface, diff_method="backprop") def circuit2(param): qml.RY(param, wires=0) qml.CNOT(wires=[0, 1]) return qml.state() rel_ent_circuit = qml.qinfo.relative_entropy(circuit1, circuit2, [0], [1]) def wrapper(param0, param1): return rel_ent_circuit((param0,), (param1,)) expected = [ np.sin(param[0] / 2) * np.cos(param[0] / 2) * (np.log(np.tan(param[0] / 2) ** 2) - np.log(np.tan(param[1] / 2) ** 2)), np.cos(param[0] / 2) ** 2 * np.tan(param[1] / 2) - np.sin(param[0] / 2) ** 2 / np.tan(param[1] / 2), ] param0, param1 = jnp.array(param[0]), jnp.array(param[1]) actual = jax.grad(wrapper, argnums=[0, 1])(param0, param1) assert np.allclose(actual, expected, atol=1e-8) @pytest.mark.jax @pytest.mark.parametrize("param", grad_params) @pytest.mark.parametrize("interface", interfaces) def test_qnode_grad_jax_jit(self, param, interface): """Test that the gradient of relative entropy works for QNodes with the JAX interface""" import jax import jax.numpy as jnp dev = qml.device("default.qubit", wires=2) @qml.qnode(dev, interface=interface, diff_method="backprop") def circuit1(param): qml.RY(param, wires=0) qml.CNOT(wires=[0, 1]) return qml.state() @qml.qnode(dev, interface=interface, diff_method="backprop") def circuit2(param): qml.RY(param, wires=0) qml.CNOT(wires=[0, 1]) return qml.state() rel_ent_circuit = qml.qinfo.relative_entropy(circuit1, circuit2, [0], [1]) def wrapper(param0, param1): return rel_ent_circuit((param0,), (param1,)) expected = [ np.sin(param[0] / 2) * np.cos(param[0] / 2) * (np.log(np.tan(param[0] / 2) ** 2) - np.log(np.tan(param[1] / 2) ** 2)), np.cos(param[0] / 2) ** 2 * np.tan(param[1] / 2) - np.sin(param[0] / 2) ** 2 / np.tan(param[1] / 2), ] param0, param1 = jnp.array(param[0]), jnp.array(param[1]) actual = jax.jit(jax.grad(wrapper, argnums=[0, 1]))(param0, param1) assert np.allclose(actual, expected, atol=1e-8) interfaces = ["auto", "autograd"] @pytest.mark.autograd @pytest.mark.parametrize("param", grad_params) @pytest.mark.parametrize("interface", interfaces) def test_qnode_grad(self, param, interface): """Test that the gradient of relative entropy works for QNodes with the autograd interface""" dev = qml.device("default.qubit", wires=2) @qml.qnode(dev, interface=interface, diff_method="backprop") def circuit1(param): qml.RY(param, wires=0) qml.CNOT(wires=[0, 1]) return qml.state() @qml.qnode(dev, interface=interface, diff_method="backprop") def circuit2(param): qml.RY(param, wires=0) qml.CNOT(wires=[0, 1]) return qml.state() rel_ent_circuit = qml.qinfo.relative_entropy(circuit1, circuit2, [0], [1]) def wrapper(param0, param1): return rel_ent_circuit((param0,), (param1,)) expected = [ np.sin(param[0] / 2) * np.cos(param[0] / 2) * (np.log(np.tan(param[0] / 2) ** 2) - np.log(np.tan(param[1] / 2) ** 2)), np.cos(param[0] / 2) ** 2 * np.tan(param[1] / 2) - np.sin(param[0] / 2) ** 2 / np.tan(param[1] / 2), ] param0, param1 = np.array(param[0]), np.array(param[1]) actual = qml.grad(wrapper)(param0, param1) assert np.allclose(actual, expected, atol=1e-8) interfaces = ["tf"] @pytest.mark.tf @pytest.mark.parametrize("param", grad_params) @pytest.mark.parametrize("interface", interfaces) def test_qnode_grad_tf(self, param, interface): """Test that the gradient of relative entropy works for QNodes with the TensorFlow interface""" import tensorflow as tf dev = qml.device("default.qubit", wires=2) @qml.qnode(dev, interface=interface, diff_method="backprop") def circuit1(param): qml.RY(param, wires=0) qml.CNOT(wires=[0, 1]) return qml.state() @qml.qnode(dev, interface=interface, diff_method="backprop") def circuit2(param): qml.RY(param, wires=0) qml.CNOT(wires=[0, 1]) return qml.state() expected = [ np.sin(param[0] / 2) * np.cos(param[0] / 2) * (np.log(np.tan(param[0] / 2) ** 2) - np.log(np.tan(param[1] / 2) ** 2)), np.cos(param[0] / 2) ** 2 * np.tan(param[1] / 2) - np.sin(param[0] / 2) ** 2 / np.tan(param[1] / 2), ] param0, param1 = tf.Variable(param[0]), tf.Variable(param[1]) with tf.GradientTape() as tape: out = qml.qinfo.relative_entropy(circuit1, circuit2, [0], [1])((param0,), (param1,)) actual = tape.gradient(out, [param0, param1]) assert np.allclose(actual, expected, atol=1e-5) interfaces = ["torch"] @pytest.mark.torch @pytest.mark.parametrize("param", grad_params) @pytest.mark.parametrize("interface", interfaces) def test_qnode_grad_torch(self, param, interface): """Test that the gradient of relative entropy works for QNodes with the Torch interface""" import torch dev = qml.device("default.qubit", wires=2) @qml.qnode(dev, interface=interface, diff_method="backprop") def circuit1(param): qml.RY(param, wires=0) qml.CNOT(wires=[0, 1]) return qml.state() @qml.qnode(dev, interface=interface, diff_method="backprop") def circuit2(param): qml.RY(param, wires=0) qml.CNOT(wires=[0, 1]) return qml.state() expected = [ np.sin(param[0] / 2) * np.cos(param[0] / 2) * (np.log(np.tan(param[0] / 2) ** 2) - np.log(np.tan(param[1] / 2) ** 2)), np.cos(param[0] / 2) ** 2 * np.tan(param[1] / 2) - np.sin(param[0] / 2) ** 2 / np.tan(param[1] / 2), ] param0 = torch.tensor(param[0], requires_grad=True) param1 = torch.tensor(param[1], requires_grad=True) out = qml.qinfo.relative_entropy(circuit1, circuit2, [0], [1])((param0,), (param1,)) out.backward() actual = [param0.grad, param1.grad] assert np.allclose(actual, expected, atol=1e-8) @pytest.mark.all_interfaces @pytest.mark.parametrize("device", ["default.qubit", "default.mixed", "lightning.qubit"]) @pytest.mark.parametrize("interface", ["autograd", "jax", "tensorflow", "torch"]) def test_num_wires_mismatch(self, device, interface): """Test that an error is raised when the number of wires in the two QNodes are different""" dev = qml.device(device, wires=2) @qml.qnode(dev, interface=interface) def circuit1(param): qml.RY(param, wires=0) qml.CNOT(wires=[0, 1]) return qml.state() @qml.qnode(dev, interface=interface) def circuit2(param): qml.RY(param, wires=0) qml.CNOT(wires=[0, 1]) return qml.state() msg = "The two states must have the same number of wires" with pytest.raises(qml.QuantumFunctionError, match=msg): qml.qinfo.relative_entropy(circuit1, circuit2, [0], [0, 1]) @pytest.mark.parametrize("device", ["default.qubit", "default.mixed", "lightning.qubit"]) def test_full_wires(self, device): """Test that the relative entropy transform for full wires works for QNodes""" dev = qml.device(device, wires=1) @qml.qnode(dev) def circuit1(param): qml.RY(param, wires=0) return qml.state() @qml.qnode(dev) def circuit2(param): qml.RY(param, wires=0) return qml.state() rel_ent_circuit = qml.qinfo.relative_entropy(circuit1, circuit2, [0], [0]) x, y = np.array(0.3), np.array(0.7) # test that the circuit executes rel_ent_circuit(x, y) @pytest.mark.parametrize("device", ["default.qubit", "default.mixed", "lightning.qubit"]) def test_qnode_no_args(self, device): """Test that the relative entropy transform works for QNodes without arguments""" dev = qml.device(device, wires=2) @qml.qnode(dev) def circuit1(): qml.PauliY(wires=0) qml.CNOT(wires=[0, 1]) return qml.state() @qml.qnode(dev) def circuit2(): qml.PauliZ(wires=0) qml.CNOT(wires=[0, 1]) return qml.state() rel_ent_circuit = qml.qinfo.relative_entropy(circuit1, circuit2, [0], [1]) # test that the circuit executes rel_ent_circuit() @pytest.mark.parametrize("device", ["default.qubit", "default.mixed", "lightning.qubit"]) def test_qnode_kwargs(self, device): """Test that the relative entropy transform works for QNodes that take keyword arguments""" dev = qml.device(device, wires=2) @qml.qnode(dev) def circuit1(param=0): qml.RY(param, wires=0) qml.CNOT(wires=[0, 1]) return qml.state() @qml.qnode(dev) def circuit2(param=0): qml.RY(param, wires=0) qml.CNOT(wires=[0, 1]) return qml.state() rel_ent_circuit = qml.qinfo.relative_entropy(circuit1, circuit2, [0], [1]) x, y = np.array(0.4), np.array(0.8) actual = rel_ent_circuit(({"param": x},), ({"param": y},)) # compare transform results with analytic results expected = ( np.cos(x / 2) ** 2 * (np.log(np.cos(x / 2) ** 2) - np.log(np.cos(y / 2) ** 2)) ) + (np.sin(x / 2) ** 2 * (np.log(np.sin(x / 2) ** 2) - np.log(np.sin(y / 2) ** 2))) assert np.allclose(actual, expected) @pytest.mark.parametrize("device", ["default.qubit", "default.mixed", "lightning.qubit"]) def test_entropy_wire_labels(self, device, tol): """Test that relative_entropy is correct with custom wire labels""" param = np.array([0.678, 1.234]) wires = ["a", 8] dev = qml.device(device, wires=wires) @qml.qnode(dev) def circuit(param): qml.RY(param, wires=wires[0]) qml.CNOT(wires=wires) return qml.state() rel_ent_circuit = qml.qinfo.relative_entropy(circuit, circuit, [wires[0]], [wires[1]]) actual = rel_ent_circuit((param[0],), (param[1],)) # compare transform results with analytic results first_term = np.cos(param[0] / 2) ** 2 * ( np.log(np.cos(param[0] / 2) ** 2) - np.log(np.cos(param[1] / 2) ** 2) ) second_term = np.sin(param[0] / 2) ** 2 * ( np.log(np.sin(param[0] / 2) ** 2) - np.log(np.sin(param[1] / 2) ** 2) ) expected = first_term + second_term assert np.allclose(actual, expected, atol=tol) @pytest.mark.parametrize("device", ["default.qubit", "default.mixed"]) class TestBroadcasting: """Test that the entropy transforms support broadcasting""" def test_vn_entropy_broadcast(self, device): """Test that the vn_entropy transform supports broadcasting""" dev = qml.device(device, wires=2) @qml.qnode(dev) def circuit_state(x): qml.IsingXX(x, wires=[0, 1]) return qml.state() x = np.array([0.4, 0.6, 0.8]) entropy = qml.qinfo.vn_entropy(circuit_state, wires=[0])(x) expected = [expected_entropy_ising_xx(_x) for _x in x] assert qml.math.allclose(entropy, expected) def test_mutual_info_broadcast(self, device): """Test that the mutual_info transform supports broadcasting""" dev = qml.device(device, wires=2) @qml.qnode(dev) def circuit_state(x): qml.IsingXX(x, wires=[0, 1]) return qml.state() x = np.array([0.4, 0.6, 0.8]) minfo = qml.qinfo.mutual_info(circuit_state, wires0=[0], wires1=[1])(x) expected = [2 * expected_entropy_ising_xx(_x) for _x in x] assert qml.math.allclose(minfo, expected) def test_relative_entropy_broadcast(self, device): """Test that the relative_entropy transform supports broadcasting""" dev = qml.device(device, wires=2) @qml.qnode(dev) def circuit_state(x): qml.IsingXX(x, wires=[0, 1]) return qml.state() x = np.array([0.4, 0.6, 0.8]) y = np.array([0.6, 0.8, 1.0]) entropy = qml.qinfo.relative_entropy(circuit_state, circuit_state, wires0=[0], wires1=[1])( x, y ) eigs0 = np.stack([np.cos(x / 2) ** 2, np.sin(x / 2) ** 2]) eigs1 = np.stack([np.cos(y / 2) ** 2, np.sin(y / 2) ** 2]) expected = np.sum(eigs0 * np.log(eigs0), axis=0) - np.sum(eigs0 * np.log(eigs1), axis=0) assert qml.math.allclose(entropy, expected)
pennylane/tests/qinfo/test_entropies.py/0
{ "file_path": "pennylane/tests/qinfo/test_entropies.py", "repo_id": "pennylane", "token_count": 15232 }
93