text
stringlengths
4
4.46M
id
stringlengths
13
126
metadata
dict
__index_level_0__
int64
0
415
"""Simple program in Qiskit.""" # Import the Qiskit package import qiskit # Create a quantum register with one qubit qreg = qiskit.QuantumRegister(1, name='qreg') # Create a classical register with one qubit creg = qiskit.ClassicalRegister(1, name='creg') # Create a quantum circuit with the above registers circ = qiskit.QuantumCircuit(qreg, creg) # Add a NOT operation on the qubit circ.x(qreg[0]) # Add a measurement on the qubit circ.measure(qreg, creg) # Print the circuit print(circ.draw()) # Get a backend to run on backend = qiskit.BasicAer.get_backend("qasm_simulator") # Execute the circuit on the backend and get the measurement results job = qiskit.execute(circ, backend, shots=10) result = job.result() # Print the measurement results print(result.get_counts())
quantumcomputingbook/chapter06/qiskit/qiskit-basic.py/0
{ "file_path": "quantumcomputingbook/chapter06/qiskit/qiskit-basic.py", "repo_id": "quantumcomputingbook", "token_count": 257 }
341
"""์จํ ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ ๊ฐ„๋‹จํ•œ ์˜ˆ์ œ ํ”„๋กœ๊ทธ๋žจ.""" # ์จํ ํŒจํ‚ค์ง€ ๊ฐ€์ ธ์˜ค์„ธ์š”. import cirq # ํ๋น„ํŠธ ํ•˜๋‚˜๋ฅผ ๊ณ ๋ฅด์„ธ์š”. qubit = cirq.GridQubit(0, 0) # ํšŒ๋กœ๋ฅผ ๋งŒ๋“œ์„ธ์š”. circuit = cirq.Circuit([ cirq.X(qubit), # ์–‘์ž ๋…ผ๋ฆฌ์—์„œ์˜ NOT. cirq.measure(qubit, key='m') # ํ๋น„ํŠธ ์ธก์ •. ] ) # ํšŒ๋กœ๋ฅผ ํ™”๋ฉด์— ํ…์ŠคํŠธ๋กœ ์ถœ๋ ฅํ•ฉ๋‹ˆ๋‹ค. print("Circuit:") print(circuit) # ํšŒ๋กœ๋ฅผ ์‹คํ–‰ํ•˜๊ธฐ ์œ„ํ•œ ์‹œ๋ฎฌ๋ ˆ์ดํ„ฐ๋ฅผ ๊ฐ€์ ธ์˜ต๋‹ˆ๋‹ค. simulator = cirq.Simulator() # ํšŒ๋กœ๋ฅผ ์—ฌ๋Ÿฌ๋ฒˆ ์‹œ๋ฎฌ๋ ˆ์ด์…˜ ํ•˜์„ธ์š”. result = simulator.run(circuit, repetitions=10) # ๊ฒฐ๊ณผ๋ฅผ ์ถœ๋ ฅํ•ฉ๋‹ˆ๋‹ค. print("Results:") print(result)
quantumcomputingbook/korean/chapter06/cirq/cirq-basic.py/0
{ "file_path": "quantumcomputingbook/korean/chapter06/cirq/cirq-basic.py", "repo_id": "quantumcomputingbook", "token_count": 489 }
342
"""ํ‚ค์Šคํ‚ท์—์„œ ์–‘์ž ์›๊ฒฉ์ด๋™ํ•˜๊ธฐ.""" from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister #from qiskit import available_backends, execute # ์–‘์ž ๋ ˆ์ง€์Šคํ„ฐ์™€ ๊ณ ์ „ ๋ ˆ์ง€์Šคํ„ฐ๋ฅผ ์ƒ์„ฑํ•ฉ๋‹ˆ๋‹ค. q = QuantumRegister(3) c = ClassicalRegister(3) qc = QuantumCircuit(q, c) # ์ดˆ๊ธฐ ์ค‘์ฒฉ ์–‘์ž ์ƒํƒœ |+>๋ฅผ ๊ตฌํ˜„ํ•ฉ๋‹ˆ๋‹ค. qc.h(q[0]) # ํ๋น„ํŠธ๋ฅผ ์ค‘์ฒฉ ํ•ด์ œํ•ฉ๋‹ˆ๋‹ค. qc.h(q[0]) # CNOT ์—ฐ์‚ฐ์ž๋ฅผ ์ ์šฉํ•ฉ๋‹ˆ๋‹ค. qc.cx(q[0], q[1]) # ํ๋น„ํŠธ๋“ค์„ ์ค‘์ฒฉ์ƒํƒœ๋กœ ๋†“์Šต๋‹ˆ๋‹ค. ํ˜„์žฌ ๋‘ ์ƒํƒœ๋Š” ๊ฐ™์Šต๋‹ˆ๋‹ค. qc.h(q[0]) qc.h(q[1]) # ํ๋น„ํŠธ 0์— ๋Œ€ํ•ด ๋‹จ์ผ ์œ ๋‹ˆํƒ€๋ฆฌ ์—ฐ์‚ฐ์œผ๋กœ ์ดˆ๊ธฐ ์ƒํƒœ๋ฅผ ์ค€๋น„ํ•ฉ๋‹ˆ๋‹ค. qc.u1(0.5, q[0]) # CNOT ์—ฐ์‚ฐ์„ ํ๋น„ํŠธ 0๊ณผ ํ๋น„ํŠธ 1์— ์ ์šฉํ•ฉ๋‹ˆ๋‹ค. qc.cx(q[0], q[1]) # ํ๋น„ํŠธ 0์„ |+>์™€ |-> ๊ธฐ์ €๋กœ ์ธก์ •ํ•ฉ๋‹ˆ๋‹ค. qc.h(q[0]) qc.measure(q[0], c[0]) # ํ•„์š”ํ•˜๋‹ค๋ฉด ํ๋น„ํŠธ 1์— ๋Œ€ํ•ด ์œ„์ƒ ๋ณด์ •(phase correction)์„ ์ˆ˜ํ–‰ํ•ฉ๋‹ˆ๋‹ค. if c[0] == 1: qc.z(q[1]) # ํ๋น„ํŠธ 0์— ๋Œ€ํ•ด ๋‹จ์ผ ์œ ๋‹ˆํƒ€๋ฆฌ ์—ฐ์‚ฐ์œผ๋กœ ์ดˆ๊ธฐ ์ƒํƒœ๋ฅผ ์ค€๋น„ํ•ฉ๋‹ˆ๋‹ค. qc.u1(0.5, q[0]) # ํ๋น„ํŠธ 1๊ณผ ํ๋น„ํŠธ 2๋ฅผ ์‚ฌ์šฉํ•ด ์–ฝํžŒ ์ƒํƒœ๋ฅผ ๋งŒ๋“ญ๋‹ˆ๋‹ค. qc.h(q[1]) qc.cx(q[1], q[2]) # ์ตœ์ ํ™”๋ฅผ ์œ„ํ•ด ๊ฒŒ์ดํŠธ๋ฅผ ์žฌ๋ฐฐ์—ดํ•˜๋Š” ๊ฒƒ์„ ๋ง‰๊ณ ์ž ์žฅ๋ง‰(Barrier)์„ ๊ฑธ์–ด๋‘ก๋‹ˆ๋‹ค. qc.barrier(q) # CNOT ์—ฐ์‚ฐ์„ ํ๋น„ํŠธ 0๊ณผ ํ๋น„ํŠธ 1์— ์ ์šฉํ•ฉ๋‹ˆ๋‹ค. qc.cx(q[0], q[1]) # ํ๋น„ํŠธ 1์„ ๊ณ„์‚ฐ๊ธฐ์ €์—์„œ ์ธก์ •ํ•ฉ๋‹ˆ๋‹ค. qc.measure(q[1], c[1]) # ํ•„์š”ํ•˜๋‹ค๋ฉด ํ๋น„ํŠธ 2์— ๋Œ€ํ•ด์„œ ๋น„ํŠธ ๋ฐ˜์ „ ๋ณด์ •(bit flip correction)์„ ์ˆ˜ํ–‰ํ•ฉ๋‹ˆ๋‹ค. if c[1] == 1: qc.x(q[2]) # ํ๋น„ํŠธ 0์„ |+>์™€ |-> ๊ธฐ์ €๋กœ ์ธก์ •ํ•ฉ๋‹ˆ๋‹ค. qc.h(q[0]) qc.measure(q[0], c[0]) # ํ•„์š”ํ•˜๋‹ค๋ฉด ํ๋น„ํŠธ 2์— ๋Œ€ํ•ด ์œ„์ƒ ๋ณด์ •(phase correction)์„ ์ˆ˜ํ–‰ํ•ฉ๋‹ˆ๋‹ค. if c[0] == 1: qc.z(q[2]) print(qc.draw())
quantumcomputingbook/korean/chapter07/qiskit/teleportation.py/0
{ "file_path": "quantumcomputingbook/korean/chapter07/qiskit/teleportation.py", "repo_id": "quantumcomputingbook", "token_count": 1396 }
343
"""ํŒŒ์ดํ€ผ(pyQuil)์—์„œ QAOAํ•˜๊ธฐ ์˜ˆ์ œ""" ########################################################## # Copyright 2016-2018 Rigetti 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. ########################################################## """ ์ด ์˜ˆ์ œ๋Š” QIP 2018ํ•™ํšŒ์—์„œ Rigetti์‚ฌ์˜ ๋ผ์ด๋ธŒ ํ”„๋กœ๊ทธ๋ž˜๋ฐ ์„ธ์…˜์—์„œ ์‹ค์ œ ์„ ๋ณด์˜€๋˜ ํ”„๋กœ๊ทธ๋žจ์ž…๋‹ˆ๋‹ค. QAOA์˜ ๋” ๋ณต์žกํ•œ ๊ตฌํ˜„์„ ์œ„ํ•ด์„œ๋Š” ๊ทธ๋กœ๋ธŒ ์˜ˆ์ œ์™€ ๋ฌธ์„œ๋ฅผ ์ฐพ์•„์ฃผ์‹ญ์‹œ์˜ค. http://grove-docs.readthedocs.io/en/latest/qaoa.html """ from pyquil import get_qc from pyquil.quil import Program from pyquil.gates import H from pyquil.paulis import sI, sX, sZ, exponentiate_commuting_pauli_sum # 4-๋…ธ๋“œ ๋ฐฐ์—ด ๊ทธ๋ž˜ํ”„๋ฅผ ์ƒ์„ฑํ•ฉ๋‹ˆ๋‹ค : 0-1-2-3. graph = [(0, 1), (1, 2), (2, 3)] # ๋…ธ๋“œ๋“ค์€ [0, 1, 2, 3]์ž…๋‹ˆ๋‹ค. nodes = range(4) # ์ดˆ๊ธฐ ์ƒํƒœ ํ”„๋กœ๊ทธ๋žจ์ž…๋‹ˆ๋‹ค. ๋ชจ๋“  ํ๋น„ํŠธ์— ์•„๋‹ค๋งˆ๋ฅด๋ฅผ ๊ฐ€ํ•ด ๋ชจ๋“  ๋น„ํŠธ์—ด์˜ ์ค‘์ฒฉ์„ ๊ตฌํ•ฉ๋‹ˆ๋‹ค. init_state_prog = Program([H(i) for i in nodes]) # ๋น„์šฉ ํ•ด๋ฐ€ํ† ๋‹ˆ์•ˆ์€ ๋ชจ๋“  ํ๋น„ํŠธ ์Œ (i, j)์—์„œ 0.5 * (1 - \sigma_z^i * \sigma_z^j)์˜ ํ•ฉ. h_cost = -0.5 * sum(sI(nodes[0]) - sZ(i) * sZ(j) for i, j in graph) # ๊ตฌ๋™ ํ•ด๋ฐ€ํ† ๋‹ˆ์•ˆ์€ ๋ชจ๋“  ํ๋น„ํŠธ i์— ๋Œ€ํ•ด \sigma_x^i์˜ ํ•ฉ. h_driver = -1. * sum(sX(i) for i in nodes) def qaoa_ansatz(gammas, betas): """ ๊ฐ๋„ betas์™€ gammas์˜ ๋ฐฐ์—ด๋กœ ์ฃผ์–ด์ง€๋Š” QAOA ๊ฐ€์ •๋ฒ•(ansatz) ํ”„๋กœ๊ทธ๋žจ์„ ๋ฐ˜ํ™˜ํ•˜๋Š” ํ•จ์ˆ˜. ์ฐจ์ˆ˜(order) P์ธ QAOA program์€ len(betas) == len(gammas) == P๋ฅผ ๊ฐ–๋Š”๋‹ค. :param list(float) gammas: ๋น„์šฉ ํ•ด๋ฐ€ํ† ๋‹ˆ์•ˆ์„ ๋งค๊ฐœ๋ณ€์ˆ˜ํ™”ํ•˜๋Š” ๊ฐ๋„๊ฐ’๋“ค์˜ ๋ฐฐ์—ด. :param list(float) betas: ๊ตฌ๋™ ํ•ด๋ฐ€ํ† ๋‹ˆ์•ˆ์„ ๋งค๊ฐœ๋ณ€์ˆ˜ํ™”ํ•˜๋Š” ๊ฐ๋„๊ฐ’๋“ค์˜ ๋ฐฐ์—ด. :return: QAOA ๊ฐ€์ •๋ฒ• ํ”„๋กœ๊ทธ๋žจ. :rtype: ํ”„๋กœ๊ทธ๋žจ. """ return Program([exponentiate_commuting_pauli_sum(h_cost)(g) + exponentiate_commuting_pauli_sum(h_driver)(b) for g, b in zip(gammas, betas)]) # ์ƒํƒœ ์ดˆ๊ธฐํ™” ํ”„๋กœ๊ทธ๋žจ๊ณผ ์ฐจ์ˆ˜ P = 2์ธ QAOA ๊ฐ€์ •๋ฒ• ํ”„๋กœ๊ทธ๋žจ์„ ๋”ํ•ด ์ „์ฒด ํ”„๋กœ๊ทธ๋žจ ์ƒ์„ฑํ•˜๊ธฐ. program = init_state_prog + qaoa_ansatz([0., 0.5], [0.75, 1.]) # ์–‘์ž ๊ฐ€์ƒ ๋จธ์‹  (QVM)์„ ์ดˆ๊ธฐํ™”ํ•˜๊ณ  ํ”„๋กœ๊ทธ๋žจ์„ ์ˆ˜ํ–‰ํ•ฉ๋‹ˆ๋‹ค. qc = get_qc('9q-generic-qvm') results = qc.run_and_measure(program, trials=2)
quantumcomputingbook/korean/chapter09/pyquil/qaoa.py/0
{ "file_path": "quantumcomputingbook/korean/chapter09/pyquil/qaoa.py", "repo_id": "quantumcomputingbook", "token_count": 1674 }
344
// 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. #pragma once #include <algorithm> #include <cstdint> #include <random> #include <stdexcept> #include <vector> namespace tket { // Something like this is needed for proper random test data generation // if you want to be platform-independent, as the C++ standard is stupid. // (A major scandal, in my opinion). // The random engines are mostly guaranteed by the standard, // but the DISTRIBUTIONS, e.g. uniform_distribution, are NOT // (i.e., the actual algorithm used to convert a string of bits to a number // in the range {0,1,2,...,N} is not specified at all by the C++ standard). // Thus, we are NOT guaranteed to get the same results, even with the same // (1) engine; (2) initial seed; (3) distribution, // if we use different platforms (or even different compilers // on the SAME platform), or even different compiler VERSIONS!!! // // The C++ standard as far as I know does not specify ANY distribution // implementations, not even optionally, so you HAVE to do this yourself, // even for something as simple as a uniform distribution. // The same applies to, e.g., std::random_shuffle. /** A random number generator class. * Of course, this is only for random test data generation, * or simple randomisation of algorithms, * definitely NOT suitable for any kind of cryptography! * Note that there are no functions involving doubles anywhere! * Actually, double calculations can give very slightly different answers * across platforms, compilers, compiler optimisation settings; * the numerical difference is absolutely negligible, * but it's worth being ultra cautious! (And it's much easier for testing * to get IDENTICAL results across platforms). */ class RNG { public: /** * Return a random integer from 0 to N, inclusive. * Approximately uniform, if max_value is much less than * the max possible value that can be returned. * N << sqrt(max uint64) ~ 2^32 ~ 4e9 will work well. * See the comments in the cpp file implementation for more detail. * * @param max_value The value N which is the (inclusive) maximum value * which can be returned. * @return A size_t from the inclusive range {0,1,2,...,N}. */ std::size_t get_size_t(std::size_t max_value); /** Returns the next 64-bit integer; guaranteed by the C++ standard * to be portable. * @return A 64-bit unsigned integer, should be roughly uniform. */ std::uint64_t operator()(); /** * Returns a number in the inclusive interval, including the endpoints. * @param min_value The smallest value (inclusive) that can be returned. * @param max_value The largest value (inclusive) that can be returned. * @return A size_t from the inclusive range {a, a+1, a+2, ... , b}. */ std::size_t get_size_t(std::size_t min_value, std::size_t max_value); /** * The behaviour of the RAW BITS of the Mersenne twister random engine * is guaranteed by the C++ standard. * The standard specifies 5489u as the default initial seed. * @param seed A seed value, to alter the RNG state. * By default, uses the value specified by the standard. */ void set_seed(std::size_t seed = 5489); /** Return true p% of the time. * (Very quick and dirty, doesn't check for, e.g., 110% effort...) * As mentioned above, we deliberately DON'T have a function returning * a uniform double. Sticking to integer values is safest. * @param percentage The probability of returning true, expressed as * a percentage. * @return A random bool, returns true with specified probability. */ bool check_percentage(std::size_t percentage); /** * Simply shuffle the elements around at random. * Approximately uniform "in practice" over all possible permutations. * (Although of course, strictly speaking very far from uniform for larger * vectors. The number of possible permutations grows very rapidly * and quickly becomes larger than the total number of distinct states * any fixed engine can take, no matter which is used. Thus, for larger * vectors, only a small proportion of permutations are actually possible). * This is necessary because C++ random_shuffle is * implementation-dependent (see above comments). * @param elements The vector to be shuffled randomly. */ template <class T> void do_shuffle(std::vector<T>& elements) { if (elements.size() < 2) { return; } m_shuffling_data.resize(elements.size()); for (std::size_t i = 0; i < m_shuffling_data.size(); ++i) { m_shuffling_data[i].first = m_engine(); // Tricky subtle point: without this extra entry to break ties, // std::sort could give DIFFERENT results across platforms and compilers, // if the object T allows unequal elements comparing equal. m_shuffling_data[i].second = i; } std::sort( m_shuffling_data.begin(), m_shuffling_data.end(), [](const std::pair<std::uintmax_t, std::size_t>& lhs, const std::pair<std::uintmax_t, std::size_t>& rhs) { return lhs.first < rhs.first || (lhs.first == rhs.first && lhs.second < rhs.second); }); // Don't need to make a copy of "elements"! Just do repeated swaps... for (std::size_t i = 0; i < m_shuffling_data.size(); ++i) { const std::size_t& j = m_shuffling_data[i].second; if (i != j) { std::swap(elements[i], elements[j]); } } } /** Return a random element from the vector. * @param elements The vector to be sampled from. * @return A reference to a random element, approximately uniform. */ template <class T> const T& get_element(const std::vector<T>& elements) { if (elements.empty()) { throw std::runtime_error("RNG: get_element called on empty vector"); } return elements[get_size_t(elements.size() - 1)]; } /** * Pick out a random element from the vector, copy and return it, * but also remove that element from the vector (swapping with * the back for efficiency, i.e. the ordering changes). * @param elements The vector to be sampled from. * Decreases size by one each time. * Time O(1) because the ordering is allowed to change. * @return A copy of the removed element. */ template <class T> T get_and_remove_element(std::vector<T>& elements) { if (elements.empty()) { throw std::runtime_error( "RNG: get_and_remove_element called on empty vector"); } std::size_t index = get_size_t(elements.size() - 1); const T copy = elements[index]; elements[index] = elements.back(); elements.pop_back(); return copy; } /** Returns the numbers {0,1,2,...,N-1} in some random order. * @param size The size of the returned vector. * @return An interval of nonnegative numbers, starting at zero, * but rearranged randomly. */ std::vector<std::size_t> get_permutation(std::size_t size); private: std::mt19937_64 m_engine; // Avoids repeated memory reallocation. std::vector<std::pair<std::uintmax_t, std::size_t>> m_shuffling_data; }; } // namespace tket
tket/libs/tkrng/include/tkrng/RNG.hpp/0
{ "file_path": "tket/libs/tkrng/include/tkrng/RNG.hpp", "repo_id": "tket", "token_count": 2414 }
345
// 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. #pragma once #include <optional> #include <set> #include <stdexcept> #include "VertexMappingFunctions.hpp" #include "tktokenswap/DistancesInterface.hpp" namespace tket { namespace tsa_internal { /** The sum of the distances of each nonempty token to its home. * (This is also referred to as "L" in various places, coming from the 2016 * paper "Approximation and Hardness of Token Swapping"). * @param vertex_mapping (current vertex where a token lies)->(target vertex) * mapping. * @param distances An object to calculate distances between vertices. * @return the sum, over all tokens, of (current vertex)->(target vertex) * distances. */ std::size_t get_total_home_distances( const VertexMapping& vertex_mapping, DistancesInterface& distances); /** For just the abstract move v1->v2, ignoring the token on v2, * by how much does L (the total distances to home) decrease? * @param vertex_mapping current source->target mapping. * @param v1 First vertex. * @param v2 Second vertex. Not required to be adjacent to v1. * @param distances An object to calculate distances between vertices. * @return The amount by which L = get_total_home_distances would decrease, * IF we moved the token on v1 to v2, IGNORING the token currently on v2 * (which of course is impossible to do in reality if there is a token on * v2), and leaving all other tokens unchanged. Doesn't have to be positive, of * course, although positive numbers are good. */ int get_move_decrease( const VertexMapping& vertex_mapping, std::size_t v1, std::size_t v2, DistancesInterface& distances); /** The same as get_move_decrease, but for an abstract swap(v1,v2). * @param vertex_mapping current source->target mapping. * @param v1 First vertex. * @param v2 Second vertex. Not required to be adjacent to v1. * @param distances An object to calculate distances between vertices. * @return The amount by which L = get_total_home_distances would decrease, * (which does not have to be a positive number), * IF the tokens currently on v1,v2 were swapped, and all other tokens * left unchanged. */ int get_swap_decrease( const VertexMapping& vertex_mapping, std::size_t v1, std::size_t v2, DistancesInterface& distances); } // namespace tsa_internal } // namespace tket
tket/libs/tktokenswap/include/tktokenswap/DistanceFunctions.hpp/0
{ "file_path": "tket/libs/tktokenswap/include/tktokenswap/DistanceFunctions.hpp", "repo_id": "tket", "token_count": 859 }
346
// 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. #pragma once #include <cstdint> #include <map> #include <vector> namespace tket { namespace tsa_internal { /** For swaps on vertices {0,1,2,...,5}, return precomputed short swap * sequences using given sets of edges. Should be close to optimal. * (Every sequence should have the joint-shortest length amongst all sequences * using those particular swaps, but not every possible sequence is included). * * (The only possibility of non-optimality is that some solutions * using many edges might be missing. It was constructed using breadth-first * searches of all possible sequences up to certain depths on various graphs * with <= 6 vertices. Due to time/space limitations some non-complete graphs * were searched as well as complete graphs K4, K5, K6. * * Note that, by token tracking, any swap sequence of n vertices of length * > n(n-1)/2 can be reduced in length, so in fact any optimal swap sequence * on n vertices has length <= n(n-1)/2, the number of edges in * the complete graph K(n). * * Of course, ideally we'd search K6 up to depth 15, but searching up to depth 9 * already consumed ~30 mins of CPU time and most of the memory capacity of an * ordinary laptop. More efficient exhaustive search algorithms with clever * pruning might cut it down a bit, but (since each added depth increases the * difficulty roughly by a factor of 14) it would require significant * computational effort to reach even depth 12 for K6, and depth 15 probably * requires a supercomputer, or a very large distributed computation, * or significantly more intelligent methods). * * The table size is far smaller than the precomputation needed to create it. * The creation considered millions of sequences, but the table has only a few * thousand entries. * * The table currently contains ALL optimal swap sequences on <= 5 vertices, * and also all swap sequences of length: * <= 9 on 6 vertices (K6, depth 9); * <= 12 on cycles with <= 6 vertices (C5, C6); * <= 12 on a few other special graphs with 6 vertices. * * Superficially redundant solutions have been removed: * * (a): If sequences S1, S2 have equal length but the edges set E1 is a subset * of E2, keep only S1, since every graph allowing S2 would also allow S1. * * (b): If sequences S1, S2 have len(S1) < len(S2), keep S2 exactly when E2 is * NOT a subset of E1 (since, then there are graphs containing E2 which do NOT * contain E1, so that S2 may be possible when S1 is impossible). * * Finally, to save space, every sequence was checked before insertion, and * inserted ONLY if its inverse was not already present in the table (since * inverting permutations is trivial for swaps: just reverse the order). Hence, * the table is only about half the size that it would otherwise be. * * But, whilst these sequences are universally valid, * this class knows nothing about HOW to look up results in the table * efficiently. The current lookup algorithms are quite crude (but actually * faster than fancier algorithms for this table size), but there is some * possibility of speedup (although not result improvements) if a really fancy * search/filtering algorithm can be found. * * NOTE: the format is reasonable, but still not as compressed as possible; * it still contains multiple isomorphic entries. A more complicated hashing * scheme is required to cut down on these isomorphic copies. (E.g., perm hash * 2, meaning the mapping 0->1, 1->0, i.e. (01), contains 0x262, 0x484, 0x737, * meaning swap sequences [02 12 02], [04 14 04], [13 03 13]. It is easily seen * that all 3 are isomorphic. The first two are of the form [ab cb ab] == [ac], * and the third has the form [ab cb ab] == [ca].) It seems like we'd need a * scheme involving integer hashing of graphs, with few isomorphic collisions, * but such algoritms need to be pretty simple and fast or they're not worth * doing except for much larger table sizes. */ struct SwapSequenceTable { /** The integer type used to encode a swap sequence on vertices {0,1,2,3,4,5}. */ typedef std::uint_fast64_t Code; /** The KEY is a "permutation hash", i.e. a number representing a permutation * on {0,1,2,3,4,5}. (Not all possible permutations are represented, though; * suitable vertex relabelling changes many different permutations to the same * hash). * * See CanonicalRelabelling.hpp, SwapConversion.hpp for more explanation. * * The VALUE is a list of integers encoding a swap sequence, which all induce * the permutation on {0,1,2,3,4,5} with the given hash. * (Obviously, different sequences are allowed, because some swaps might not * be possible, i.e. the graph might be incomplete). */ typedef std::map<unsigned, std::vector<Code>> Table; /** The actual large precomputed table. The entries are already sorted * and duplications/redundancies/suboptimality have been removed. * However, currently this raw data is processed by * FilteredSwapSequences which tolerates such imperfections. * Thus it is easy to add more sequences to the table without worrying * about them (as long as the newly added data is actually correct). * @return A large precomputed raw table of data. */ static Table get_table(); }; } // namespace tsa_internal } // namespace tket
tket/libs/tktokenswap/include/tktokenswap/SwapSequenceTable.hpp/0
{ "file_path": "tket/libs/tktokenswap/include/tktokenswap/SwapSequenceTable.hpp", "repo_id": "tket", "token_count": 1591 }
347
// 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 "tktokenswap/SwapSequenceTable.hpp" namespace tket { namespace tsa_internal { SwapSequenceTable::Table SwapSequenceTable::get_table() { Table map; // clang-format off map[2] = { 0x1, 0x262, 0x373, 0x484, 0x595, 0x27a72, 0x28b82, 0x29c92, 0x36a63, 0x38d83, 0x39e93, 0x46b64, 0x47d74, 0x49f94, 0x56c65, 0x57e75, 0x58f85, 0x27dbd72, 0x27ece72, 0x28dad82, 0x28fcf82, 0x29eae92, 0x29fbf92, 0x36bdb63, 0x36cec63, 0x38bab83, 0x38fef83, 0x39cac93, 0x39fdf93, 0x46ada64, 0x46cfc64, 0x47aba74, 0x47efe74, 0x49cbc94, 0x49ede94, 0x56aea65, 0x56bfb65, 0x57aca75, 0x57dfd75, 0x58bcb85, 0x58ded85, 0x2a8fea2f8, 0x2a9fda2f9, 0x2b7efb2e7, 0x2b9edb2e9, 0x2c7dfc2d7, 0x2c8dec2d8, 0x3a8fca3f8, 0x3a9fba3f9, 0x3d6cfd3c6, 0x3d9cbd3c9, 0x3e6bfe3b6, 0x3e8bce3b8, 0x4b7ecb4e7, 0x4b9eab4e9, 0x4d6ced4c6, 0x4d9cad4c9, 0x4f6aef4a6, 0x4f7acf4a7, 0x5c7dbc5d7, 0x5c8dac5d8, 0x5e6bde5b6, 0x5e8bae5b8, 0x5f6adf5a6, 0x5f7abf5a7, }; map[3] = { 0x16, 0x21, 0x62, 0x17a7, 0x18b8, 0x19c9, 0x2373, 0x2484, 0x2595, 0x36a3, 0x3736, 0x3a31, 0x3a73, 0x46b4, 0x4846, 0x4b41, 0x4b84, 0x56c5, 0x5956, 0x5c51, 0x5c95, 0x7a27, 0x8b28, 0x9c29, 0x17bd7b, 0x17ce7c, 0x18ad8a, 0x18cf8c, 0x19ae9a, 0x19bf9b, 0x238d38, 0x239e39, 0x247d47, 0x249f49, 0x257e57, 0x258f58, 0x36bd3b, 0x36ce3c, 0x3738b8, 0x3739c9, 0x38d386, 0x38db83, 0x39e396, 0x39ec93, 0x3a3484, 0x3a3595, 0x3ad8d3, 0x3ae9e3, 0x3b8ba3, 0x3bdb73, 0x3c9ca3, 0x3cec73, 0x3dbd31, 0x3ece31, 0x46ad4a, 0x46cf4c, 0x47d476, 0x47da74, 0x4847a7, 0x4849c9, 0x49f496, 0x49fc94, 0x4a7ab4, 0x4ada84, 0x4b4373, 0x4b4595, 0x4bd7d4, 0x4bf9f4, 0x4c9cb4, 0x4cfc84, 0x4dad41, 0x4fcf41, 0x56ae5a, 0x56bf5b, 0x57e576, 0x57ea75, 0x58f586, 0x58fb85, 0x5957a7, 0x5958b8, 0x5a7ac5, 0x5aea95, 0x5b8bc5, 0x5bfb95, 0x5c5373, 0x5c5484, 0x5ce7e5, 0x5cf8f5, 0x5eae51, 0x5fbf51, 0x7bd7b2, 0x7ce7c2, 0x8ad8a2, 0x8cf8c2, 0x9ae9a2, 0x9bf9b2, 0x17bfe7fb, 0x17cfd7fc, 0x18aef8ea, 0x18ced8ec, 0x19adf9da, 0x19bde9db, 0x238fe3f8, 0x239fd3f9, 0x247ef4e7, 0x249ed4e9, 0x257df5d7, 0x258de5d8, 0x3738fcf8, 0x3739fbf9, 0x38dfcf83, 0x38fca3f8, 0x38fe3cf8, 0x39efbf93, 0x39fba3f9, 0x39fd3bf9, 0x3a349f94, 0x3a358f85, 0x3ad9f9d3, 0x3ae8f8e3, 0x3b8bcec3, 0x3b8fefb3, 0x3bdb3595, 0x3bdbe9e3, 0x3bfe31fb, 0x3bfefb73, 0x3c9cbdb3, 0x3c9fdfc3, 0x3cec3484, 0x3cecd8d3, 0x3cfd31fc, 0x3cfdfc73, 0x3d6cfcd3, 0x3d89c9d3, 0x3d9f96d3, 0x3e6bfbe3, 0x3e8f86e3, 0x3e98b8e3, 0x47dece74, 0x47ecb4e7, 0x47ef4ce7, 0x4847ece7, 0x4849eae9, 0x49eab4e9, 0x49ed4ae9, 0x49feae94, 0x4a7acfc4, 0x4a7efea4, 0x4ada4595, 0x4adaf9f4, 0x4aef41ea, 0x4aefea84, 0x4b439e93, 0x4b457e75, 0x4bd9e9d4, 0x4bf7e7f4, 0x4c9cada4, 0x4c9edec4, 0x4ced41ec, 0x4cedec84, 0x4cfc4373, 0x4cfcd7d4, 0x4d6cecd4, 0x4d79c9d4, 0x4d9e96d4, 0x4f6aeaf4, 0x4f7e76f4, 0x4f97a7f4, 0x57dbc5d7, 0x57df5bd7, 0x57edbd75, 0x58dac5d8, 0x58de5ad8, 0x58fdad85, 0x5957dbd7, 0x5958dad8, 0x5a7abfb5, 0x5a7dfda5, 0x5adf51da, 0x5adfda95, 0x5aea5484, 0x5aeaf8f5, 0x5b8baea5, 0x5b8dedb5, 0x5bde51db, 0x5bdedb95, 0x5bfb5373, 0x5bfbe7e5, 0x5c538d83, 0x5c547d74, 0x5ce8d8e5, 0x5cf7d7f5, 0x5e6bdbe5, 0x5e78b8e5, 0x5e8d86e5, 0x5f6adaf5, 0x5f7d76f5, 0x5f87a7f5, 0x7dcfc2d7, 0x7ebfb2e7, 0x8dcec2d8, 0x8faea2f8, 0x9ebdb2e9, 0x9fada2f9, }; map[4] = { 0x16a, 0x176, 0x1a7, 0x21a, 0x316, 0x321, 0x362, 0x62a, 0x6a3, 0x736, 0xa31, 0xa73, 0x12712, 0x16bdb, 0x16cec, 0x178b8, 0x179c9, 0x18ad8, 0x18b8a, 0x18d86, 0x18db8, 0x19ae9, 0x19c9a, 0x19e96, 0x19ec9, 0x1bd7b, 0x1ce7c, 0x21bdb, 0x21cec, 0x23273, 0x2484a, 0x2595a, 0x26276, 0x318b8, 0x319c9, 0x32484, 0x32595, 0x346b4, 0x34846, 0x34b41, 0x34b84, 0x356c5, 0x35956, 0x35c51, 0x35c95, 0x38b28, 0x39c29, 0x46ad4, 0x46ba4, 0x47d46, 0x4846a, 0x48476, 0x484a7, 0x4a7d4, 0x4ad41, 0x4ad84, 0x4b41a, 0x4ba84, 0x4d416, 0x4d421, 0x4d462, 0x4d6b4, 0x4d846, 0x4db41, 0x4db84, 0x56ae5, 0x56ca5, 0x57e56, 0x5956a, 0x59576, 0x595a7, 0x5a7e5, 0x5ae51, 0x5ae95, 0x5c51a, 0x5ca95, 0x5e516, 0x5e521, 0x5e562, 0x5e6c5, 0x5e956, 0x5ec51, 0x5ec95, 0x62bdb, 0x62cec, 0x6bdb3, 0x6cec3, 0x738b8, 0x739c9, 0x7a27a, 0x8a348, 0x8ad38, 0x8b82a, 0x8b8a3, 0x8d386, 0x8d3b8, 0x9a359, 0x9ae39, 0x9c92a, 0x9c9a3, 0x9e396, 0x9e3c9, 0xbdb31, 0xbdb73, 0xcec31, 0xcec73, 0x128d812, 0x129e912, 0x16bfefb, 0x16cfdfc, 0x1714b41, 0x1715c51, 0x178cfc8, 0x179bfb9, 0x18aef8e, 0x18b8cec, 0x18ced8c, 0x18cfca8, 0x18cfec8, 0x18d8c9c, 0x18dcfc8, 0x18efb8e, 0x18efe86, 0x19adf9d, 0x19bde9b, 0x19bfba9, 0x19bfdb9, 0x19c9bdb, 0x19dfc9d, 0x19dfd96, 0x19e9b8b, 0x19ebfb9, 0x1bfe7fb, 0x1cfd7fc, 0x21befbe, 0x21cdfcd, 0x232d8d3, 0x232e9e3, 0x2484cec, 0x2595bdb, 0x2628d86, 0x2629e96, 0x28b2db8, 0x29c2ec9, 0x2a49f49, 0x2a58f58, 0x2d4284d, 0x2e5295e, 0x318fcf8, 0x319fbf9, 0x3249f94, 0x3258f85, 0x346cf4c, 0x34849c9, 0x349cb49, 0x349f964, 0x349fc94, 0x34b4373, 0x34b4959, 0x34b9f94, 0x34cf84c, 0x34cfc41, 0x356bf5b, 0x358bc58, 0x358f865, 0x358fb85, 0x35958b8, 0x35bf95b, 0x35bfb51, 0x35c5373, 0x35c5848, 0x35c8f85, 0x38fc2f8, 0x39fb2f9, 0x46bcec4, 0x46ced4c, 0x46cf4ec, 0x46cfca4, 0x4787b84, 0x47d4c9c, 0x47ef4e6, 0x4846cec, 0x48479c9, 0x4849e96, 0x4849ec9, 0x484ae9e, 0x484c9ca, 0x484cec7, 0x49cad49, 0x49ed496, 0x49f4976, 0x49f4e96, 0x49f4ec9, 0x49fca49, 0x4a7ef4e, 0x4ab7ab4, 0x4ad4595, 0x4ad9f49, 0x4ae9ed4, 0x4ae9f4e, 0x4aefe41, 0x4aefe84, 0x4b41cec, 0x4b4595a, 0x4b67b64, 0x4baf9f4, 0x4bd7bd4, 0x4c9cba4, 0x4c9ed4c, 0x4ced41c, 0x4ced84c, 0x4cf41ca, 0x4cf41ec, 0x4cf84ca, 0x4d419c9, 0x4d42595, 0x4d456c5, 0x4d45956, 0x4d45c95, 0x4d4c9c2, 0x4d849c9, 0x4db4595, 0x4dcfc84, 0x4df6cf4, 0x4df96f4, 0x4dfc9f4, 0x4ece7d4, 0x4ef421e, 0x4ef84e6, 0x4efb41e, 0x4efb84e, 0x4efe6b4, 0x4f6aef4, 0x4f9f46a, 0x4f9f4a7, 0x4fecf84, 0x4fef416, 0x4fef462, 0x56bde5b, 0x56bf5db, 0x56bfba5, 0x56cbdb5, 0x5797c95, 0x57df5d6, 0x57e5b8b, 0x58bae58, 0x58de586, 0x58f5876, 0x58f5d86, 0x58f5db8, 0x58fba58, 0x5956bdb, 0x59578b8, 0x5958d86, 0x5958db8, 0x595ad8d, 0x595b8ba, 0x595bdb7, 0x5a7df5d, 0x5ac7ac5, 0x5ad8de5, 0x5ad8f5d, 0x5adfd51, 0x5adfd95, 0x5ae5484, 0x5ae8f58, 0x5b8bca5, 0x5b8de5b, 0x5bde51b, 0x5bde95b, 0x5bf51ba, 0x5bf51db, 0x5bf95ba, 0x5c51bdb, 0x5c5484a, 0x5c67c65, 0x5caf8f5, 0x5ce7ce5, 0x5dbd7e5, 0x5df521d, 0x5df95d6, 0x5dfc51d, 0x5dfc95d, 0x5dfd6c5, 0x5e518b8, 0x5e52484, 0x5e546b4, 0x5e54846, 0x5e54b84, 0x5e5b8b2, 0x5e958b8, 0x5ebfb95, 0x5ec5484, 0x5ef6bf5, 0x5ef86f5, 0x5efb8f5, 0x5f6adf5, 0x5f8f56a, 0x5f8f5a7, 0x5fdbf95, 0x5fdf516, 0x5fdf562, 0x62befeb, 0x62cdfdc, 0x6befe3b, 0x6cdfd3c, 0x738cf8c, 0x739bf9b, 0x84b8cec, 0x85ecf85, 0x8aefe38, 0x8b2cec8, 0x8b8c5ec, 0x8b8ece3, 0x8ce348c, 0x8cf8c2a, 0x8cfe38c, 0x8d389c9, 0x8d3fcf8, 0x8da2da8, 0x8eced38, 0x8ef86e3, 0x8efb8e3, 0x8fa35f8, 0x8fcf8a3, 0x94dbf94, 0x95c9bdb, 0x9adfd39, 0x9bd359b, 0x9bf9b2a, 0x9bfd39b, 0x9c2bdb9, 0x9c9b4db, 0x9c9dbd3, 0x9dbde39, 0x9df96d3, 0x9dfc9d3, 0x9e398b8, 0x9e3fbf9, 0x9ea2ea9, 0x9fa34f9, 0x9fbf9a3, 0xb5e541b, 0xb5efb51, 0xbefbe73, 0xbfefb31, 0xc4d451c, 0xc4dfc41, 0xcdfcd73, 0xcfdfc31, 0x128fef812, 0x129fdf912, 0x1714cfc41, 0x1715bfb51, 0x18d8c515c, 0x19e9b414b, 0x2328fe3f8, 0x2329fd3f9, 0x242d427d4, 0x252e527e5, 0x2628fef86, 0x2629fdf96, 0x28b2878b8, 0x28bfef2b8, 0x28fc2ecf8, 0x29c2979c9, 0x29cfdf2c9, 0x29fb2dbf9, 0x2d4f9f24d, 0x2df5295fd, 0x2e5f8f25e, 0x2ef4284fe, 0x34b49e3e9, 0x34cfc4373, 0x35bfb5373, 0x35c58d3d8, 0x428427842, 0x46b469e96, 0x4787fcf84, 0x4849e98b8, 0x49f4befb9, 0x4a7acfca4, 0x4abe9eab4, 0x4cb9cb4ec, 0x4cef7efc4, 0x4cf97f9c4, 0x4cfdfc7d4, 0x4d45c5848, 0x4fc67c6f4, 0x529527952, 0x56c568d86, 0x5797fbf95, 0x58f5cdfc8, 0x5958d89c9, 0x5a7abfba5, 0x5acd8dac5, 0x5bc8bc5db, 0x5bdf7dfb5, 0x5bf87f8b5, 0x5bfefb7e5, 0x5e54b4959, 0x5fb67b6f5, 0x7bd7b2bdb, 0x7ce7c2cec, 0x8edce5de8, 0x8fea2eaf8, 0x9debd4ed9, 0x9fda2daf9, 0x242d42e9ed4, 0x252e52d8de5, 0x2b28b29e98b, 0x2c29c28d89c, 0x428429e9842, 0x47ecb47e7ce, 0x487845c5484, 0x49cb479c797, 0x4d45c54d7d4, 0x4fb9f479fbf, 0x529528d8952, 0x57dbc57d7bd, 0x58bc578b787, 0x597954b4595, 0x5e54b45e7e5, 0x5fc8f578fcf, 0x8ced82ce2c2, 0x8fdcf82cfdf, 0x9bde92bd2b2, 0x9febf92bfef, 0xbf4efb7ef4f, 0xcf5dfc7df5f, 0xdf85fd25f8f, 0xef94fe24f9f, }; map[5] = { 0x16ad, 0x16ba, 0x16db, 0x176d, 0x186a, 0x1876, 0x18a7, 0x1ad8, 0x1b8a, 0x1d86, 0x1db8, 0x21ad, 0x21ba, 0x21db, 0x321d, 0x3d16, 0x3d62, 0x416a, 0x4176, 0x41a7, 0x421a, 0x4316, 0x4321, 0x4362, 0x46a3, 0x4736, 0x4a31, 0x4a73, 0x62ad, 0x62ba, 0x62db, 0x642a, 0x6a3d, 0x6ad4, 0x6b4a, 0x6d42, 0x73d6, 0x76d4, 0x846a, 0x8476, 0x84a7, 0xa17d, 0xa31d, 0xa73d, 0xa7d4, 0xad41, 0xad84, 0xb84a, 0xba41, 0xd416, 0xd421, 0xd6b4, 0xd846, 0xdb41, 0xdb84, 0x12712d, 0x12812a, 0x12d812, 0x132813, 0x138136, 0x167b67, 0x16aefe, 0x16bcec, 0x16cdfc, 0x16cecd, 0x16cfca, 0x16cfec, 0x16efbe, 0x176efe, 0x1787b8, 0x179c9d, 0x17a7ba, 0x186cec, 0x187121, 0x187c9c, 0x189ae9, 0x189c9a, 0x189ec9, 0x18a313, 0x18ce7c, 0x18e9e6, 0x19adf9, 0x19ae9d, 0x19bf9a, 0x19c9ad, 0x19c9db, 0x19dbf9, 0x19df96, 0x19e96d, 0x19f96a, 0x19f9a7, 0x19fae9, 0x19fca9, 0x19fe96, 0x19fec9, 0x1a7efe, 0x1aef8e, 0x1b8cec, 0x1bd7bd, 0x1c9cba, 0x1c9dfc, 0x1c9ecd, 0x1cdf8c, 0x1ce7dc, 0x1ced8c, 0x1cf8ec, 0x1d89c9, 0x1ef86e, 0x1efb8e, 0x1f976f, 0x1fcf8a, 0x213b23, 0x21aefe, 0x21bcec, 0x21cdfc, 0x21cecd, 0x21cfca, 0x21ecfe, 0x232473, 0x23273d, 0x237b23, 0x242a84, 0x243284, 0x2595ad, 0x2595ba, 0x2595db, 0x26276d, 0x26286a, 0x262876, 0x262d86, 0x2d4284, 0x316efe, 0x321efe, 0x327387, 0x32959d, 0x3436b4, 0x343846, 0x343b41, 0x343b84, 0x356c5d, 0x35956d, 0x35c95d, 0x36a3ba, 0x373876, 0x373a87, 0x3a31ba, 0x3a73ba, 0x3c51dc, 0x3d19c9, 0x3efe62, 0x412712, 0x416cec, 0x4179c9, 0x419ae9, 0x419c9a, 0x419e96, 0x419ec9, 0x41ce7c, 0x421cec, 0x42595a, 0x426276, 0x4319c9, 0x432959, 0x4356c5, 0x435956, 0x435c95, 0x439c29, 0x43c5c1, 0x456ae5, 0x456c5a, 0x457e56, 0x45956a, 0x4595a7, 0x45a7e5, 0x45ae51, 0x45c51a, 0x45e516, 0x45e562, 0x45e6c5, 0x45e965, 0x45ec51, 0x45ec95, 0x462cec, 0x46ce3c, 0x4739c9, 0x47a27a, 0x48a348, 0x495976, 0x495ae9, 0x495c9a, 0x49ae39, 0x49c2a9, 0x49ca39, 0x49e3c9, 0x4a3595, 0x4ce31c, 0x4ce73c, 0x4e521e, 0x4e9e36, 0x56adf5, 0x56ae5d, 0x56bf5a, 0x56c5ad, 0x56c5ba, 0x56c5db, 0x57df56, 0x57e56d, 0x58f56a, 0x58f576, 0x58f5a7, 0x5956ad, 0x5956ba, 0x59576d, 0x59586a, 0x595876, 0x5958a7, 0x595a7d, 0x595ad8, 0x595b8a, 0x595d6b, 0x595d86, 0x595db8, 0x5a7df5, 0x5a7e5d, 0x5ad8f5, 0x5adf51, 0x5adf95, 0x5ae51d, 0x5ae95d, 0x5b8f5a, 0x5bf51a, 0x5bf95a, 0x5c51ad, 0x5c51ba, 0x5c51db, 0x5c95ad, 0x5c95ba, 0x5c95db, 0x5d6bf5, 0x5d8f56, 0x5db8f5, 0x5dbf95, 0x5df516, 0x5df521, 0x5df562, 0x5df6c5, 0x5df956, 0x5dfc51, 0x5dfc95, 0x5e516d, 0x5e521d, 0x5e956d, 0x5ed562, 0x5ed6c5, 0x5edc51, 0x5edc95, 0x5f516a, 0x5f5176, 0x5f51a7, 0x5f521a, 0x5f5316, 0x5f5362, 0x5f56a3, 0x5f5736, 0x5f6ae5, 0x5f6c5a, 0x5f7e56, 0x5f956a, 0x5f9576, 0x5fa7e5, 0x5fae95, 0x5fca95, 0x5fe516, 0x5fe521, 0x5fe562, 0x5fe6c5, 0x5fe956, 0x5fec51, 0x5fec95, 0x623b23, 0x62aefe, 0x62b676, 0x62bece, 0x62cdfc, 0x62cecd, 0x62cfec, 0x62efbe, 0x62fcfa, 0x65f52a, 0x67b674, 0x6a3efe, 0x6aef4e, 0x6b4cec, 0x6bd3bd, 0x6cd45c, 0x6cdf4c, 0x6cecd4, 0x6cf4ca, 0x6ece3d, 0x6ecf4e, 0x6ef42e, 0x6efb4e, 0x7387b8, 0x73d9c9, 0x73fef6, 0x76efe4, 0x787b84, 0x79c9d4, 0x7a2b7a, 0x7a72ad, 0x7a7ba4, 0x846cec, 0x8479c9, 0x849ae9, 0x849c9a, 0x849e96, 0x84c9ec, 0x87b82b, 0x8ad83d, 0x8b28ba, 0x8b28db, 0x8d863d, 0x8db83d, 0x95f9a7, 0x9a359d, 0x9ad459, 0x9adf49, 0x9ae3d9, 0x9ae9d4, 0x9b459a, 0x9bf49a, 0x9c2ad9, 0x9c2ba9, 0x9c92db, 0x9c932d, 0x9c9a3d, 0x9c9ad4, 0x9c9ba4, 0x9c9d42, 0x9c9db4, 0x9d4259, 0x9d4596, 0x9d45c9, 0x9db459, 0x9dbf49, 0x9df496, 0x9dfc94, 0x9e963d, 0x9e96d4, 0x9ec93d, 0x9ec9d4, 0x9f496a, 0x9f4976, 0x9f49a7, 0x9f4ae9, 0x9f4e96, 0x9f4ec9, 0x9fc9a4, 0xa31efe, 0xa5f531, 0xa73fef, 0xa75f53, 0xa7efe4, 0xaef41e, 0xafe51f, 0xafef84, 0xb238b2, 0xb41cec, 0xb84cec, 0xbd73bd, 0xbdb3d1, 0xbdb7d4, 0xc51fca, 0xcd419c, 0xcd451c, 0xcd89c4, 0xcdf41c, 0xcdf84c, 0xce73dc, 0xce7d4c, 0xcec3d1, 0xcec874, 0xcecd41, 0xcecd84, 0xcfca41, 0xcfca84, 0xcfec41, 0xcfec84, 0xdbf5f1, 0xefb41e, 0xefb84e, 0xefe2b1, 0xefe416, 0xefe421, 0xefe846, 0xf5321f, 0x12712efe, 0x12812cec, 0x129df912, 0x129e912d, 0x129f912a, 0x12fe912f, 0x12fef812, 0x1329f913, 0x1361b613, 0x13813c9c, 0x139f9136, 0x16b6e96e, 0x16cfc676, 0x17a7cfca, 0x1813c5c1, 0x1815ae51, 0x1815c51a, 0x1815e516, 0x181c5ec1, 0x181e5e21, 0x181ece31, 0x18715c51, 0x189e9b8b, 0x18b318b3, 0x18e9e121, 0x197f97c9, 0x19bde9bd, 0x19eabea9, 0x19f9a313, 0x19fbefb9, 0x1c9cbece, 0x1cdfd7dc, 0x1ce7cfef, 0x1d815c51, 0x1f97121f, 0x213cfc23, 0x217b2172, 0x21b2e52e, 0x2324e9e3, 0x2325f573, 0x2328d38d, 0x232e9e3d, 0x237cfc23, 0x242af9f4, 0x242cec84, 0x2432f9f4, 0x245e5284, 0x24d427d4, 0x25efb7e5, 0x26276efe, 0x26286232, 0x2629df96, 0x2629e96d, 0x262e96fe, 0x262fef86, 0x26826ece, 0x26f9726f, 0x27842784, 0x27a27a87, 0x2953b239, 0x29c2fec9, 0x29ced2c9, 0x2b25e562, 0x2b32e9e3, 0x2bc9579c, 0x2be5295e, 0x2d42f9f4, 0x2e52495e, 0x2e5295ed, 0x2e5295fe, 0x2ef4284e, 0x2f52a95f, 0x2f53295f, 0x2f9579fb, 0x2fc2632f, 0x2fcf6276, 0x32373fef, 0x325fe8f5, 0x32739f97, 0x329e3fe9, 0x3436cf4c, 0x343849c9, 0x3439f4c9, 0x343b4373, 0x343c9cb4, 0x343f9f46, 0x34b34959, 0x34cf834c, 0x35c57387, 0x35c5d737, 0x36a3686a, 0x36a3cfca, 0x3739f976, 0x373a9f97, 0x373b67b6, 0x373ce87c, 0x38ba38ba, 0x39ca3ba9, 0x39e3afe9, 0x39e3fe96, 0x39e3fec9, 0x3a31cfca, 0x3a3595ba, 0x3a73cfca, 0x3abe9e3a, 0x3c53473c, 0x3c5c4384, 0x3ce31fec, 0x3ce73fec, 0x3cfe8fc2, 0x3e9c289e, 0x3f53c95f, 0x3f59635f, 0x4171b41b, 0x4171c51c, 0x419e9121, 0x42629e96, 0x434b9f94, 0x434cfc41, 0x457ac57a, 0x45ae5484, 0x45c5484a, 0x45c67c65, 0x45e54864, 0x45e54b84, 0x45e56b4b, 0x45e7ce75, 0x48ec548e, 0x48ece348, 0x49597c9c, 0x49aea2a9, 0x49c29ece, 0x4a34f9f4, 0x4b5e541b, 0x53f53c51, 0x56c5686a, 0x56c56876, 0x56c5b676, 0x56c5bcec, 0x578795b8, 0x579c795d, 0x579c8795, 0x57ac57ba, 0x57e57876, 0x57e578a7, 0x57e587b8, 0x57eab7a5, 0x5878b8f5, 0x5898ae95, 0x5898c95a, 0x5898ec95, 0x58bc578b, 0x59567b67, 0x5957a7ba, 0x595cd89c, 0x595d7bd7, 0x5989e956, 0x598c9532, 0x5a7abf5a, 0x5a7acad5, 0x5ade8de5, 0x5ae51bab, 0x5ae95aba, 0x5aefe8f5, 0x5b6bf576, 0x5b8bc5db, 0x5b8bcba5, 0x5bce8bc5, 0x5bcebc51, 0x5bcebc95, 0x5bdb7df5, 0x5bde95bd, 0x5c67c6d5, 0x5c6c5d86, 0x5cb79c53, 0x5cbec7e5, 0x5cfca8f5, 0x5d8ded56, 0x5db8de5d, 0x5dbd7e5d, 0x5de6bde5, 0x5debde51, 0x5df52959, 0x5dfcf8f5, 0x5e78ce75, 0x5ed7ce75, 0x5f526276, 0x5f571721, 0x5f57a27a, 0x5f797c95, 0x5fa35935, 0x5fac7ac5, 0x5fe6bf5b, 0x5feb8f5b, 0x5febfb95, 0x5fec7e57, 0x5fec8f58, 0x6268e9e6, 0x6269f96a, 0x62b69e96, 0x63f5c35f, 0x65fc5676, 0x67cfc674, 0x6a5e5aba, 0x6cfd3fdc, 0x6ece3fef, 0x717d5c51, 0x73787c9c, 0x7387fcf8, 0x73ec9bce, 0x73f97c9f, 0x7871fcf8, 0x787fcf84, 0x79f53bf9, 0x7a27afef, 0x7a7cfca4, 0x7bd7bd2b, 0x7cef47ec, 0x7f97c9f4, 0x849e98b8, 0x8795f259, 0x87cf85fc, 0x89e9b82b, 0x8ad8a2ad, 0x8b28efbe, 0x8ced38dc, 0x8d3fcf8d, 0x8d89c93d, 0x8e5f25e7, 0x8ef865fe, 0x8fce72cf, 0x92c2dfc9, 0x9ae9a2ad, 0x9ae9a2ba, 0x9b2bc932, 0x9bce2bc9, 0x9bcebc94, 0x9bde9b3d, 0x9bf92b32, 0x9bf9b2ba, 0x9bf9b2db, 0x9bfd3bd9, 0x9c2cfc9a, 0x9c2ec987, 0x9c9bdb3d, 0x9d3bd359, 0x9dbded49, 0x9df963d3, 0x9dfc9d3d, 0x9e3bce98, 0x9e3febf9, 0x9eabea49, 0x9f4befb9, 0x9fb2efb9, 0xa72cfca2, 0xad9f9d3d, 0xb6b49e96, 0xb82b5e52, 0xb8b2bece, 0xb8fec3ef, 0xbc59835c, 0xbef51bfe, 0xc537f53c, 0xcdfcd73d, 0xcdfcd7d4, 0xce7fec2b, 0xcf538f5c, 0xcfd3fd1c, 0xd45c5484, 0xe529589e, 0xe98b598e, 0xef5bfe73, 0xf5395fb8, 0xf97c92cf, 0xfc239c2f, 0x131813fcf8, 0x1361cfc613, 0x16b615e516, 0x17ce7bcebc, 0x1815e518b8, 0x197c9bc979, 0x1bfe7bfebf, 0x2171cfc217, 0x2329fd3fd9, 0x24d42e9ed4, 0x252f52a8f5, 0x252f5328f5, 0x254e5247e5, 0x25e7b25e25, 0x26239f9623, 0x28429e9842, 0x2a27a29f97, 0x2b2129e912, 0x2c29c279cd, 0x2c29c2d89c, 0x2e5f825f5e, 0x2ec982c9e2, 0x2f5e75e25f, 0x2f952795f2, 0x32e39e389e, 0x3437fcf437, 0x353f536bf5, 0x353f538f56, 0x35c5d8d3d8, 0x37367cfc67, 0x395fb35f93, 0x39ecb3ece9, 0x39fbafb3a9, 0x3a6a39f96a, 0x3ce98e93ec, 0x3cfe38fec3, 0x3e3ce31bce, 0x3e3ce73bce, 0x3ea9e3a89e, 0x41714fcf41, 0x419e914b41, 0x429c279c79, 0x434b439e39, 0x4529579525, 0x47ec27ec7e, 0x513c51bc53, 0x529527952d, 0x529528952a, 0x52952d8952, 0x5295895325, 0x52e527e587, 0x535f53bf51, 0x53bc538bc5, 0x53c537bc53, 0x579f97bf95, 0x598a359353, 0x5ac7ac5878, 0x5ac8dac58d, 0x5bcb9c79c5, 0x5bfbefb7e5, 0x5c6c586cec, 0x5dbc7dbc57, 0x5e6ae5868a, 0x5e7e5b6b76, 0x5e8bae58ba, 0x5f517c515c, 0x626862e52e, 0x6befb3ef3e, 0x6cbec3ecbc, 0x7397f97bf9, 0x7845c57848, 0x791f971bf9, 0x7975987259, 0x7e7ce7bce4, 0x7fec27ecf7, 0x87f8cf82cf, 0x8c953895c8, 0x8efc2fc8fe, 0x8f8ef863ef, 0x8f8efb83ef, 0x8fdcf8d2cf, 0x953c5bc593, 0x9596be969e, 0x968e963e98, 0x97c92c9879, 0x97c97bc974, 0x97f97bf92b, 0x9895395896, 0x98e98b3e98, 0x9debde92b2, 0x9eae92aefe, 0x9fadf92a2d, 0xa353f538f5, 0xae3fe8fe3e, 0xbc65cb635c, 0xbcb9c2b79c, 0xbfbefb3ef1, 0xc2bec27ec2, 0xc2c98c92ca, 0xc2fc238fc2, 0xc2fca8fc2c, 0xc5d45c7d74, 0xc9ca3fcacf, 0xcfdfc7df5f, 0xdf85f25f8f, 0xe3febfe73e, 0xe52d7e5de7, 0xe545eb4595, 0xe7ec2ec7ed, 0xece5de8de5, 0xf4b9f479fb, 0xf53b8f5bfb, 0xf919f319c9, 0xfbfe7febf4, 0xfef429f4f9, 0x13191f913bf9, 0x1391c91bc913, 0x232e3fe38fe3, 0x24f4ef427ef4, 0x2528f5278f52, 0x252e52de8de5, 0x252fdf527df5, 0x2a2ea9ea289e, 0x2b2529527952, 0x2c29c2389c23, 0x2c2ec27ec287, 0x2f49f4279f42, 0x3539538953b8, 0x353f537bf537, 0x37397c97bc97, 0x39ca3989ca98, 0x3cafca38fca3, 0x3e39e369b69e, 0x3e3bce38bce3, 0x3e3c6ce386ce, 0x4597954b4595, 0x4b454e54b7e5, 0x5395369b6953, 0x53c6c5386c53, 0x5c51715bc517, 0x5f51715fbf51, 0x7d7fdcfd72cf, 0x7e7fe7bfe72b, 0x8ced8c2cedc2, 0x8f8eaef82aef, }; map[6] = { 0x16adf, 0x16aed, 0x16afe, 0x16baf, 0x16cad, 0x16cba, 0x16cdb, 0x16dfc, 0x16fec, 0x176df, 0x176ed, 0x176fe, 0x186af, 0x18f76, 0x18fa7, 0x196ad, 0x196ba, 0x196db, 0x197d6, 0x1986a, 0x19876, 0x198a7, 0x19ad8, 0x19b8a, 0x19d86, 0x19db8, 0x1a7ed, 0x1a7fe, 0x1ad8f, 0x1adf9, 0x1ae9d, 0x1afe9, 0x1b8fa, 0x1bf9a, 0x1c9ad, 0x1c9ba, 0x1c9db, 0x1d86f, 0x1db8f, 0x1dbf9, 0x1df96, 0x1dfc9, 0x1e96d, 0x1ec9d, 0x1f96a, 0x1f976, 0x1f9a7, 0x1fc9a, 0x1fe96, 0x1fec9, 0x21adf, 0x21aed, 0x21afe, 0x21baf, 0x21cad, 0x21cba, 0x21cdb, 0x21dbf, 0x21dfc, 0x21ecd, 0x21fca, 0x21fec, 0x316df, 0x316fe, 0x321df, 0x321ed, 0x321fe, 0x3df62, 0x3ed16, 0x3ed62, 0x41a7f, 0x421af, 0x4362f, 0x4f16a, 0x4f176, 0x4f316, 0x4f321, 0x4f62a, 0x4f6a3, 0x4f736, 0x4fa31, 0x4fa73, 0x516ad, 0x516ba, 0x516db, 0x5176d, 0x5186a, 0x51876, 0x518a7, 0x51ad8, 0x51db8, 0x521ad, 0x521ba, 0x521db, 0x5316d, 0x53d21, 0x53d62, 0x5416a, 0x54176, 0x541a7, 0x542a1, 0x54316, 0x54321, 0x54362, 0x546a3, 0x54736, 0x54a31, 0x54a73, 0x562ba, 0x562db, 0x56a3d, 0x56ad4, 0x56b4a, 0x56db4, 0x573d6, 0x57d46, 0x5846a, 0x58476, 0x584a7, 0x5a31d, 0x5a73d, 0x5a7d4, 0x5ad41, 0x5ad84, 0x5b41a, 0x5b84a, 0x5d416, 0x5d421, 0x5d462, 0x5d846, 0x5db41, 0x5db84, 0x62adf, 0x62aed, 0x62afe, 0x62bfa, 0x62cad, 0x62cba, 0x62cdb, 0x62dfc, 0x62ecd, 0x62fca, 0x62fec, 0x632fe, 0x652ad, 0x6542a, 0x6a3df, 0x6a3ed, 0x6a3fe, 0x6ad4f, 0x6adf5, 0x6ae5d, 0x6af53, 0x6b4fa, 0x6baf5, 0x6c5ad, 0x6c5ba, 0x6c5db, 0x6d42f, 0x6db4f, 0x6df52, 0x6dfc5, 0x6e52d, 0x6ec5d, 0x6f52a, 0x6f532, 0x6fca5, 0x6fe52, 0x6fec5, 0x73fe6, 0x763df, 0x763ed, 0x76d4f, 0x76df5, 0x76ed5, 0x76f53, 0x76fe5, 0x84f6a, 0x84f76, 0x84fa7, 0x86af5, 0x876f5, 0x8f5a7, 0x956ad, 0x956ba, 0x956db, 0x9576d, 0x9586a, 0x95876, 0x958a7, 0x95a7d, 0x95ad8, 0x95b8a, 0x95d86, 0x95db8, 0xa17df, 0xa197d, 0xa31df, 0xa31ed, 0xa31fe, 0xa517d, 0xa73df, 0xa73ed, 0xa73fe, 0xa7d4f, 0xa7df5, 0xa7e5d, 0xa7f53, 0xad41f, 0xad84f, 0xad8f5, 0xadf51, 0xadf95, 0xae51d, 0xae95d, 0xaf517, 0xaf531, 0xaf975, 0xafe95, 0xb4f1a, 0xba518, 0xba84f, 0xba8f5, 0xbaf51, 0xbaf95, 0xc51ad, 0xc51db, 0xc95ad, 0xc95ba, 0xc95db, 0xcba51, 0xd16bf, 0xd416f, 0xd421f, 0xd5186, 0xd62bf, 0xd6bf5, 0xd864f, 0xd86f5, 0xdb41f, 0xdb84f, 0xdb8f5, 0xdbf51, 0xdbf95, 0xdf516, 0xdf521, 0xdf956, 0xdfc51, 0xdfc95, 0xe956d, 0xed16c, 0xed516, 0xed521, 0xedc51, 0xedc95, 0xf16ca, 0xf516a, 0xf5176, 0xf521a, 0xf5316, 0xf5321, 0xf6ae5, 0xf956a, 0xf9576, 0xfa7e5, 0xfae51, 0xfc51a, 0xfca95, 0xfe516, 0xfe521, 0xfe965, 0xfec51, 0xfec95, 0x12712df, 0x12712ed, 0x12712fe, 0x12812af, 0x128132f, 0x128712f, 0x12912ad, 0x12912ba, 0x129132d, 0x129712d, 0x12d812f, 0x12d9812, 0x12df912, 0x12e912d, 0x12f912a, 0x12f9712, 0x12fe912, 0x1329813, 0x132f913, 0x1343fc9, 0x138136f, 0x139163d, 0x1391643, 0x1396b23, 0x1398136, 0x13f9136, 0x142a914, 0x146ca34, 0x149146a, 0x1491476, 0x167b67f, 0x167c67d, 0x167fc67, 0x168c68a, 0x16abeab, 0x16bdbed, 0x16cb676, 0x16cd868, 0x16efbef, 0x178be78, 0x1797dc9, 0x17a7baf, 0x17a7cad, 0x17a7fca, 0x17e7876, 0x18789b8, 0x187b8cb, 0x18d86ed, 0x18f78b8, 0x18fa313, 0x19121db, 0x1914321, 0x191ad41, 0x191b41a, 0x191d416, 0x191db41, 0x197a7ba, 0x198121a, 0x1987121, 0x19879c9, 0x1989ca9, 0x1989e96, 0x1989ec9, 0x198a313, 0x19a3143, 0x19b67b6, 0x19bd7bd, 0x19cd89c, 0x19d4214, 0x1a7acba, 0x1a7e787, 0x1a7eaba, 0x1ad8ede, 0x1aef8ef, 0x1b8acbc, 0x1b8bcdb, 0x1b8cbec, 0x1b8dbed, 0x1bcb6ec, 0x1bcbec9, 0x1bd7bdf, 0x1bd7ebd, 0x1bde9bd, 0x1c687c6, 0x1cdf8cf, 0x1ce7bce, 0x1ce7cfe, 0x1e78ce7, 0x1e7ce7d, 0x1eae9ba, 0x1ecf8ef, 0x1ef86ef, 0x1efb8ef, 0x1efebf9, 0x1f8cf8a, 0x1f91a31, 0x213b23f, 0x213cb23, 0x213fc23, 0x214c24a, 0x21abeab, 0x21bdbed, 0x21c232d, 0x21cebce, 0x21efbef, 0x2324f73, 0x2325473, 0x23273ed, 0x232d8f5, 0x23723fe, 0x2372f53, 0x237c23d, 0x237c243, 0x237cb23, 0x237fc23, 0x23c2187, 0x23d8fc2, 0x2432584, 0x243c284, 0x24854ec, 0x248c24a, 0x252ad95, 0x252ba95, 0x253d295, 0x2542a95, 0x2543295, 0x25925db, 0x259d425, 0x26276df, 0x26276ed, 0x26276fe, 0x26286af, 0x262876f, 0x26296ad, 0x262976d, 0x2629876, 0x2629d86, 0x262d86f, 0x262df96, 0x262e96d, 0x262f96a, 0x262f976, 0x262fe96, 0x26926db, 0x28478fc, 0x2ae8748, 0x2bf3273, 0x2c14324, 0x2c23d62, 0x2c24176, 0x2c24362, 0x2c26d42, 0x2c2d421, 0x2c62d86, 0x2c68132, 0x2c87124, 0x2ca7387, 0x2ca8781, 0x2cd4284, 0x2d42584, 0x2d4284f, 0x2df5295, 0x2e5295d, 0x2ec8478, 0x2f52a95, 0x2f53295, 0x2fc2362, 0x2fc6276, 0x2fe5295, 0x3164e34, 0x3189eb8, 0x323573d, 0x3248e34, 0x324f9e3, 0x327387f, 0x327397d, 0x3273987, 0x3273f97, 0x329589e, 0x329e3d8, 0x32d373f, 0x32e3431, 0x32e3473, 0x32e7387, 0x34356b4, 0x3435846, 0x3435b84, 0x3436b4f, 0x34384f6, 0x343b84f, 0x343bf95, 0x347396b, 0x3486e34, 0x34b8e34, 0x34be341, 0x34bf9e3, 0x34bfe73, 0x353d6c5, 0x353d956, 0x353dc51, 0x353dc95, 0x35436c5, 0x3543956, 0x3543c95, 0x36a3baf, 0x36a3cad, 0x36a3cba, 0x36a3fca, 0x373876f, 0x37396ba, 0x3739876, 0x373a87f, 0x373a987, 0x373af97, 0x373f976, 0x3743bf9, 0x3796243, 0x3796b23, 0x389eb28, 0x3986235, 0x39e6b23, 0x3a31baf, 0x3a31cad, 0x3a31cba, 0x3a31fca, 0x3a73baf, 0x3a73cba, 0x3a73fca, 0x3b2f9e3, 0x3b8fe3a, 0x3d8b298, 0x3e3186a, 0x3e346a3, 0x3e34a31, 0x3e436b4, 0x3e6ab3a, 0x3e76b23, 0x3ea31ba, 0x3eb2318, 0x3eba8b2, 0x3f536c5, 0x3f53956, 0x3f53c51, 0x3f53c95, 0x417c9bc, 0x42a8498, 0x42af484, 0x43198c9, 0x432484f, 0x4328498, 0x434b41f, 0x435cf84, 0x436b4cb, 0x4384986, 0x4384b98, 0x4384fc9, 0x43b41cb, 0x43b84cb, 0x43c9f4b, 0x4546ae5, 0x4546c5a, 0x4546ec5, 0x4547e56, 0x454956a, 0x4549576, 0x45495a7, 0x454a7e5, 0x454ae51, 0x454ae95, 0x454c51a, 0x454c95a, 0x454e516, 0x454e956, 0x454ec95, 0x45e4562, 0x46ad4ed, 0x46b4cba, 0x46b4dcb, 0x473cb9c, 0x47d4ed6, 0x4846cad, 0x4849876, 0x484ba98, 0x484db98, 0x486ca34, 0x48948a7, 0x4894ad8, 0x489a348, 0x4a34584, 0x4a3484f, 0x4a35495, 0x4a7d4ed, 0x4ad41ed, 0x4ad84ed, 0x4b84dcb, 0x4bcdb73, 0x4cb9ca3, 0x4d416ed, 0x4d421ed, 0x4d864ed, 0x4db41ed, 0x4db84ed, 0x4de4d62, 0x4de6b4d, 0x4f12712, 0x4f26276, 0x4f7a27a, 0x512712d, 0x512812a, 0x512d812, 0x5138136, 0x5167b67, 0x517a7ba, 0x5186cec, 0x5187121, 0x518a313, 0x51bd7bd, 0x5237b23, 0x5242a84, 0x526276d, 0x526286a, 0x5262d86, 0x52b2321, 0x5327387, 0x53a31ba, 0x54179c9, 0x5426276, 0x5434b41, 0x543c5c1, 0x545ec51, 0x5471271, 0x547a27a, 0x54e5e21, 0x5626876, 0x562b232, 0x562b676, 0x56a3bab, 0x56bd3bd, 0x5736878, 0x57378a7, 0x57387b8, 0x573a7ba, 0x57871b8, 0x5787b84, 0x57a27ad, 0x57a2b7a, 0x57ab47a, 0x5813281, 0x58ad38d, 0x58b278b, 0x58b28db, 0x59a359d, 0x59ad459, 0x59b459a, 0x59d4596, 0x59db459, 0x5b238b2, 0x5b28b2a, 0x5b6b476, 0x5b8d3bd, 0x5bd31bd, 0x5bd73bd, 0x5bdb7d4, 0x5c9d45c, 0x5cd45c1, 0x5cecd84, 0x5d38d36, 0x5d456c5, 0x623b23f, 0x624c24a, 0x626986a, 0x62969ba, 0x62ae787, 0x62bdbed, 0x62c676d, 0x62c6876, 0x62c868a, 0x62cb232, 0x62cb676, 0x62cbcec, 0x62eabea, 0x62efbef, 0x6324e34, 0x672b67f, 0x67b674f, 0x67b67f5, 0x67c67d5, 0x67c6875, 0x67cb675, 0x67f5267, 0x67fc675, 0x68c68a5, 0x69a3d89, 0x6abeab5, 0x6aef4ef, 0x6b4cbec, 0x6bdb3df, 0x6bdbed5, 0x6c5bcec, 0x6c5d868, 0x6cbec3e, 0x6cf4cfa, 0x6db3ed3, 0x6dfc4f4, 0x6ec3e43, 0x6ecd3e3, 0x6ece3fe, 0x6ecf4ef, 0x6ef42ef, 0x6efb4ef, 0x6efbef5, 0x73697d9, 0x73876cb, 0x73879b8, 0x7387b8f, 0x7397dc9, 0x73987c9, 0x73ac687, 0x73cb679, 0x73db8cb, 0x73dcbc6, 0x73e6878, 0x73e87b8, 0x73f97c9, 0x7634e34, 0x768e785, 0x76efe4f, 0x78795b8, 0x787b84f, 0x787fc51, 0x78fc537, 0x79c1943, 0x7a27adf, 0x7a27afe, 0x7a2cb7a, 0x7a2fc7a, 0x7a72baf, 0x7a7ba4f, 0x7a7baf5, 0x7a7cad5, 0x7a7cba5, 0x7a7f52a, 0x7a7fca5, 0x7c9bc53, 0x7d4cb9c, 0x7e587b8, 0x7f51721, 0x7f971c9, 0x7f97c95, 0x846898a, 0x8478b98, 0x84798c9, 0x8489d86, 0x8498ae9, 0x8498c9a, 0x8498e96, 0x8498ec9, 0x84bae78, 0x84bc78b, 0x84e786c, 0x84edce7, 0x86c24ec, 0x8795248, 0x87b82bf, 0x87b82cb, 0x87b8cb5, 0x87f8b85, 0x8981ae9, 0x898ae95, 0x898c95a, 0x898e521, 0x898ec95, 0x89b82ae, 0x89e5248, 0x89e54b8, 0x8ad3e8d, 0x8ad83df, 0x8ad8ed5, 0x8b2a798, 0x8b2ae78, 0x8b2c8ba, 0x8b82aed, 0x8b8cba5, 0x8b8d2cb, 0x8b8dcb5, 0x8b98e52, 0x8d863df, 0x8d863ed, 0x8d86ed5, 0x8db83ed, 0x8db8ed5, 0x8e75248, 0x8fce72c, 0x91491a7, 0x919a31d, 0x9567b67, 0x957a7ba, 0x95879c9, 0x95bd7bd, 0x95c79cd, 0x95cd89c, 0x95e89e6, 0x97dc92c, 0x98135c9, 0x9862c32, 0x987c92c, 0x98ae93e, 0x98c92ca, 0x98c9532, 0x98c9e2c, 0x98e963e, 0x98ec93e, 0x9adf94f, 0x9ae39ed, 0x9ae9f3e, 0x9bf94fa, 0x9c29cba, 0x9c29cdb, 0x9c29dfc, 0x9c29ecd, 0x9c29fec, 0x9c2d89c, 0x9c9a3df, 0x9ca3d89, 0x9dbf49f, 0x9df964f, 0x9dfc94f, 0x9e3c9fe, 0x9e3feb8, 0x9f49f6a, 0x9f49fa7, 0x9f4ae9f, 0x9f4c9fa, 0x9f4ec9f, 0x9f9764f, 0x9fe964f, 0xa27a2ed, 0xa2c7a2d, 0xa2d8fc2, 0xa348e34, 0xa3e3473, 0xa73797d, 0xa73cacd, 0xa73e787, 0xa73eaba, 0xa78e785, 0xa7d4bcb, 0xa7ef4ef, 0xab7eab5, 0xabeab51, 0xabeab95, 0xae349e3, 0xaef41ef, 0xaefe8f5, 0xaf53959, 0xafe84f8, 0xb236298, 0xb238b2f, 0xb238cb2, 0xb41abcb, 0xb41cbec, 0xb84acbc, 0xb84cbec, 0xb8a2bf2, 0xb8cb2ec, 0xb8cba3e, 0xb8cbec5, 0xb8d3acb, 0xb8fec3e, 0xbc5318b, 0xbcb5316, 0xbcbec95, 0xbd73ebd, 0xbd7bdf5, 0xbdb3df1, 0xbdb3ed1, 0xbdb7ed5, 0xbdbed51, 0xbdbed95, 0xc23d9c2, 0xc24179c, 0xc2419ec, 0xc2439c2, 0xc249c2a, 0xc2ec7d4, 0xc51ebce, 0xc534b73, 0xc92cd42, 0xc9ac2cd, 0xc9b2c32, 0xc9bce2c, 0xc9c2fca, 0xc9e3bce, 0xc9ed4bc, 0xca37943, 0xcb2179c, 0xcbec3e1, 0xcbec73e, 0xcbec7e5, 0xcdf84cf, 0xcdfc4f1, 0xcdfc8f5, 0xce2c417, 0xce73ced, 0xce7d4bc, 0xce7db2c, 0xcec3ed1, 0xcec7d4f, 0xcecf3e1, 0xcecf73e, 0xcfca4f1, 0xcfca84f, 0xcfca8f5, 0xcfec4f1, 0xcfec84f, 0xd3b8d3f, 0xd3bdf73, 0xd3bf9e3, 0xd428498, 0xd4b41cb, 0xd7bd74f, 0xd7fc537, 0xd8498c9, 0xdb28b2f, 0xe3186ce, 0xe34c9e3, 0xe34ce31, 0xe34ce73, 0xe3ced84, 0xe73ce87, 0xe78a72c, 0xe78ce75, 0xe963e43, 0xe96de3e, 0xec54384, 0xec9d3e3, 0xecd7e57, 0xecf8d3e, 0xefb84ef, 0xefbef51, 0xefe4f16, 0xefe4f21, 0xefe84f6, 0xefe8f56, 0xefeb4f1, 0xf5318b8, 0xf8e5248, 0xf8ecf85, 0xf8ef5b8, 0xf97c92c, 0xf9e39e6, 0xfbefb95, 0xfc239c2, 0xfe7ce75, 0x124914712, 0x127128e78, 0x128d812ed, 0x129e8912e, 0x12f8ef812, 0x1315813b8, 0x1319143c9, 0x132b9123b, 0x1361b613f, 0x1361c613d, 0x1361c6143, 0x1361fc613, 0x136813c68, 0x136cb6136, 0x1396b6136, 0x1461c6a14, 0x1467c6147, 0x14712e714, 0x1476e7147, 0x14914c9ca, 0x14e714ce7, 0x168a6ea68, 0x16c6d4164, 0x16c868cec, 0x176be76b7, 0x179f97bf9, 0x17a7ca787, 0x17d7bd7cb, 0x18131b8cb, 0x1898be98b, 0x18b8abeab, 0x18ced8ced, 0x18dad8cad, 0x18fb318b3, 0x18fc78fc8, 0x191319c9d, 0x1913a31ba, 0x191419ae9, 0x1914b34b1, 0x191d3bd31, 0x1941479c9, 0x194149ec9, 0x196be969e, 0x1983138b8, 0x1983139c9, 0x19cd419c4, 0x1a7e71417, 0x1c979bc97, 0x1cfd7fdcf, 0x1ebfe7bfe, 0x1f91319c9, 0x214717c24, 0x214aea24a, 0x217b2172f, 0x217cb2172, 0x217fc2127, 0x2183c2183, 0x23258d38d, 0x2328d38df, 0x2329e389e, 0x2329e39fe, 0x232de8d3e, 0x232e349e3, 0x232e39e3d, 0x2378c2378, 0x23d8c23d3, 0x242a9f49f, 0x242c2ec84, 0x24329f49f, 0x248a2ea24, 0x248e5e254, 0x24d427d4f, 0x24d47dc24, 0x254e527e5, 0x25df85f25, 0x25f52a8f5, 0x26239623d, 0x2623f9623, 0x26249624a, 0x26286232f, 0x2628d86ed, 0x262962d42, 0x26298e96e, 0x262e7e876, 0x262f8ef86, 0x26b96b276, 0x278425784, 0x27952795d, 0x279528795, 0x27a27a87f, 0x27a27a97d, 0x27a27a987, 0x27a27af97, 0x27a2e7a87, 0x27a2eab7a, 0x2842784f2, 0x286239862, 0x28952a895, 0x289532895, 0x28b278b98, 0x28b28ba98, 0x28b28db98, 0x28b2db8ed, 0x2952d8952, 0x296243962, 0x296b23962, 0x2989e5925, 0x2b238b298, 0x2c1287128, 0x2c1424cec, 0x2c212712d, 0x2c212812a, 0x2c212d812, 0x2c6286cec, 0x2c7842784, 0x2ca27a287, 0x2d425d7d4, 0x2d4284ded, 0x2d42f49f4, 0x2e527e587, 0x2e52e7e5d, 0x2e52e7fe5, 0x2e52fe8f5, 0x2ea2462ea, 0x2ea6826ea, 0x2ef4824ef, 0x2f532f8f5, 0x2f9527952, 0x3168e3183, 0x318be3183, 0x3218e3183, 0x327349734, 0x32be32b73, 0x32d38d398, 0x3436cf4cf, 0x3438498c9, 0x3439bf49f, 0x3439f49f6, 0x3439f4c9f, 0x343cf41cf, 0x343f84cf8, 0x34be34737, 0x35378c537, 0x353dc5373, 0x35483c548, 0x35c813581, 0x35f536bf5, 0x35f538f56, 0x35f53bf51, 0x36a3696ad, 0x36a3696ba, 0x36a36986a, 0x36a36f96a, 0x36a3c686a, 0x36a68f36a, 0x36aca34a3, 0x37367b67f, 0x373687c68, 0x3736c67d6, 0x37387b8cb, 0x373b67cb6, 0x373b967b6, 0x373fc67c6, 0x3793bd7bd, 0x389538956, 0x38ba38baf, 0x38d38d986, 0x38d38db98, 0x38d3a8d98, 0x38d3b8dcb, 0x397349736, 0x39734a973, 0x3979a73ba, 0x39895c935, 0x39ca389ca, 0x39ca39cad, 0x39ca39fca, 0x3a31ca343, 0x3a348ca34, 0x3a783ca78, 0x3ac8d3a8d, 0x3b2e328b2, 0x3b4375b43, 0x3b437b43f, 0x3b459b435, 0x3b8bacb3a, 0x3bc538bc5, 0x3bc53b6c5, 0x3bc53bc51, 0x3bd31bdcb, 0x3bd73bdcb, 0x3c537bc53, 0x3c537c543, 0x3c537cf53, 0x3c9cacb3a, 0x3ca349ca3, 0x3ca34ca73, 0x3cbc5c935, 0x3cf53c8f5, 0x3d36bd3cb, 0x3e213b23b, 0x3e318a313, 0x3e3b2b632, 0x3e73b67b6, 0x3ea6a386a, 0x3eba8ba3a, 0x3f53fb8f5, 0x3f53fbf95, 0x414914e96, 0x41714b4f1, 0x4171b41cb, 0x436b4696b, 0x437b437cb, 0x438468c68, 0x439cb49cb, 0x452e52495, 0x454797c95, 0x4548ae548, 0x4548e5486, 0x454ac7ac5, 0x454be541b, 0x454c5484a, 0x454c6c576, 0x454e546b4, 0x454ec7e57, 0x462ce42c4, 0x46ad4cadc, 0x46b4696ba, 0x46b4abeab, 0x46b4cb676, 0x46b4d696b, 0x46ced4ced, 0x47145b471, 0x4715c4571, 0x47abc4b7a, 0x47d4797d6, 0x47d479a7d, 0x47d497dc9, 0x47d4a7cad, 0x48467c687, 0x48478be78, 0x48478e786, 0x484c68c6a, 0x484dc68c6, 0x484e78ce7, 0x484e78ea7, 0x49cb4d9cb, 0x49ed49ed6, 0x49ed4c9ed, 0x4a34f49f4, 0x4ad41acad, 0x4ad84acad, 0x4aed49ed4, 0x4b41abeab, 0x4b84eabea, 0x4bc7d74db, 0x4c2462c76, 0x4c249c2ec, 0x4c548ec54, 0x4c9cbc4ba, 0x4ced41ced, 0x4ced84ced, 0x4db7d497d, 0x4e54b8e54, 0x4ece7de4d, 0x51361b613, 0x5181ae51e, 0x5181ec51e, 0x518c515ca, 0x51d81c51c, 0x5217b2172, 0x521b2e52e, 0x526286232, 0x52a27a287, 0x52be5295e, 0x537367b67, 0x538ba38ba, 0x53a3595ba, 0x53a6a386a, 0x562b25e52, 0x5715c571d, 0x5715c5871, 0x5815e5281, 0x5815e5816, 0x58da2da8d, 0x592593b23, 0x59d3bd359, 0x5b25e58b2, 0x5b7db27db, 0x5d45c5484, 0x62c868232, 0x67cfc674f, 0x68a6ea685, 0x69b674b69, 0x6bfbefb3e, 0x6c5e86ce8, 0x6c686ec3e, 0x6cfdfc3df, 0x719417b41, 0x71f5c1571, 0x7349734c9, 0x7387cf8cf, 0x739f97bf9, 0x73bc97bc9, 0x76be76b75, 0x787489248, 0x787cf8cf5, 0x787f4cf84, 0x79f97bf95, 0x7a72c42a4, 0x7a7ca7875, 0x7a7cfca4f, 0x7bd74debd, 0x7bd7bd2bf, 0x7bd7bd2cb, 0x7bd7bdcb5, 0x7c97bc957, 0x7ce7bce2c, 0x7ce7ced2c, 0x7ce7cfe2c, 0x7ce7fec4f, 0x7e78ce72c, 0x7f97c94f4, 0x8468c68ec, 0x8498be98b, 0x87f8cf82c, 0x898a35935, 0x898c92c32, 0x8ad82adf2, 0x8ad8a2aed, 0x8ad8a2cad, 0x8adac58ad, 0x8b28efbef, 0x8b2eae8ba, 0x8b8abeab5, 0x8b8cbec3e, 0x8ced8ced5, 0x8cf8cf2ca, 0x8cf8cfe2c, 0x8cf8dcf2c, 0x8cf8ecf3e, 0x8d3cf8dcf, 0x8d89c3d89, 0x8e318ce31, 0x8e98be985, 0x8eced3e8d, 0x8ef86ef3e, 0x8efb8ef3e, 0x8f8aef83e, 0x95e6b69e6, 0x96b6e963e, 0x98ae9a2ae, 0x98be98b3e, 0x9adf93df3, 0x9ae93eaba, 0x9ae9a2aed, 0x9ae9fa2ae, 0x9bde39ebd, 0x9bf92bf32, 0x9bf9b2bfa, 0x9bf9b2dbf, 0x9bf9db3df, 0x9c9bce4bc, 0x9df96d3df, 0x9dfc9d3df, 0x9e3bfb9fe, 0x9febf92bf, 0xa2eab9ea2, 0xa35f538f5, 0xb6296be96, 0xbcb9c279c, 0xbefb9f4ef, 0xbefbef3e1, 0xbefbef73e, 0xbefbef7e5, 0xcdfc7df57, 0xcdfcd73df, 0xcdfcd7d4f, 0xcdfd31cdf, 0xce348ce34, 0xcfc238fc2, 0xd427d4ed7, 0xea72ae42a, 0xf97bf94fb, 0x1241914e912, 0x131813f8cf8, 0x1319f913bf9, 0x131c91bc913, 0x14161c614ec, 0x1461a6ea614, 0x147a71ca714, 0x14b714be714, 0x2181a2ea218, 0x21c21812ece, 0x232be32b9e3, 0x232d3fd9fd3, 0x232ef8fe3fe, 0x252be5257e5, 0x258f5278f52, 0x25e52de8de5, 0x25fdf527df5, 0x262b76e76b6, 0x28b298be98b, 0x2a2da8da298, 0x2b87eb872b8, 0x31e31b613b6, 0x32739732b23, 0x3437f4cf437, 0x34b43e349e3, 0x359538953b8, 0x35f537bf537, 0x36a96a3a439, 0x36c686c53c5, 0x373467c6734, 0x395369b6953, 0x3aba38ba398, 0x3ba3fb9fba3, 0x3cfca38fca3, 0x3d38d368c68, 0x3d3b6bd396b, 0x3d3cbd9cbd3, 0x3e326238623, 0x4171f4fcf41, 0x42c249c279c, 0x42d427d497d, 0x45295795245, 0x48427842e78, 0x48468a6ea68, 0x4847a78ca78, 0x4c24ec27ec2, 0x4c9acad4adc, 0x4d7d467c67d, 0x4da6ad496ad, 0x516be51615e, 0x51e51815eb8, 0x526826e525e, 0x535c538d38d, 0x59e545eb459, 0x5c54d45c7d4, 0x5c58457845c, 0x67962462967, 0x69eb69e4b69, 0x715f517bf51, 0x71c517bc517, 0x7a7eba4baea, 0x7d7fdcfd72c, 0x7ecb4ecb7ec, 0x83a318ca318, 0x842984e9842, 0x8ded8ced82c, 0x8f8eaef82ae, 0x91721b21791, 0x9379437b437, 0x97f97bf92bf, 0x9c97bc974bc, 0x9fdadf92adf, 0xa24ea249ea2, 0xa2a79a72bab, 0xbd4ed9ed4bd, 0xd7db2db7ede, 0xef94f24f9ef, 0xf4bfe7febf4, }; map[22] = { 0x1a, 0x1232, 0x1676, 0x1bdb, 0x1cec, 0x2362, 0x262a, 0x3273, 0x373a, 0x484a, 0x595a, 0x6276, 0x7367, 0x121712, 0x124d42, 0x125e52, 0x131613, 0x134b43, 0x135c53, 0x168d86, 0x169e96, 0x178b87, 0x179c97, 0x1bfefb, 0x1cfdfc, 0x232484, 0x232595, 0x238b28, 0x239c29, 0x24d462, 0x25e562, 0x262bdb, 0x262cec, 0x27a27a, 0x28b2a8, 0x29c2a9, 0x328d38, 0x329e39, 0x34b473, 0x35c573, 0x36a36a, 0x373bdb, 0x373cec, 0x38d3a8, 0x39e3a9, 0x467684, 0x46b46a, 0x46b476, 0x47d467, 0x47d47a, 0x484cec, 0x48bdb4, 0x4b6db4, 0x4d7bd4, 0x4f9f4a, 0x567695, 0x56c56a, 0x56c576, 0x57e567, 0x57e57a, 0x595bdb, 0x59cec5, 0x5c6ec5, 0x5e7ce5, 0x5f8f5a, 0x628d86, 0x629e96, 0x738b87, 0x739c97, 0x8b2db8, 0x8d3bd8, 0x9c2ec9, 0x9e3ce9, 0xb4384b, 0xb8478b, 0xc5395c, 0xc9579c, 0xd4284d, 0xd8468d, 0xe5295e, 0xe9569e, 0x1218d812, 0x1219e912, 0x124efe42, 0x125dfd52, 0x1318b813, 0x1319c913, 0x134cfc43, 0x135bfb53, 0x1614d416, 0x1615e516, 0x168efe86, 0x169dfd96, 0x1714b417, 0x1715c517, 0x178cfc87, 0x179bfb97, 0x1b45e54b, 0x1b89e98b, 0x1c54d45c, 0x1c98d89c, 0x23249f94, 0x23258f85, 0x238cfc28, 0x239bfb29, 0x24d42959, 0x24d49c29, 0x24efe462, 0x25dfd562, 0x25e52848, 0x25e58b28, 0x262befeb, 0x262cdfdc, 0x28b82cec, 0x28dad82a, 0x28fcf82a, 0x29c92bdb, 0x29eae92a, 0x29fbf92a, 0x328efe38, 0x329dfd39, 0x34b43959, 0x34b49e39, 0x34cfc473, 0x35bfb573, 0x35c53848, 0x35c58d38, 0x373dcfcd, 0x373ebfbe, 0x38bab83a, 0x38d83ece, 0x38fef83a, 0x39cac93a, 0x39e93dbd, 0x39fdf93a, 0x42d427d4, 0x43b436b4, 0x46769f94, 0x469e9684, 0x46ad46a6, 0x46b49e96, 0x46b6cec4, 0x46cfc6a4, 0x479c9784, 0x47ab47a7, 0x47d49c97, 0x47d7ece4, 0x47efe7a4, 0x484befbe, 0x484cfdfc, 0x49cb4ec9, 0x49ed4ce9, 0x49f49cec, 0x49f4bdb9, 0x4abc9cb4, 0x4ade9ed4, 0x4b6efb4e, 0x4bc9cdb4, 0x4c9f479c, 0x4cfd9f4c, 0x4d7cfd4c, 0x4db9ed49, 0x4e9f469e, 0x4efb9f4e, 0x4f6cf476, 0x4f7ef467, 0x4fc6ecf4, 0x4fe7cef4, 0x52e527e5, 0x53c536c5, 0x56768f85, 0x568d8695, 0x56ae56a6, 0x56bfb6a5, 0x56c58d86, 0x56c6bdb5, 0x578b8795, 0x57ac57a7, 0x57dfd7a5, 0x57e58b87, 0x57e7dbd5, 0x58bc5db8, 0x58de5bd8, 0x58f58bdb, 0x58f5cec8, 0x595bfefb, 0x595cdfcd, 0x5acb8bc5, 0x5aed8de5, 0x5b8f578b, 0x5bfe8f5b, 0x5c6dfc5d, 0x5cb8bec5, 0x5d8f568d, 0x5dfc8f5d, 0x5e7bfe5b, 0x5ec8de58, 0x5f6bf576, 0x5f7df567, 0x5fb6dbf5, 0x5fd7bdf5, 0x628ef86e, 0x629df96d, 0x738cf87c, 0x739bf97b, 0x86d863d8, 0x87b872b8, 0x8b2efb8e, 0x8c5f835c, 0x8d3cfd8c, 0x8e5f825e, 0x8fc2ecf8, 0x8fe3cef8, 0x96e963e9, 0x97c972c9, 0x9b4f934b, 0x9c2dfc9d, 0x9d4f924d, 0x9e3bfe9b, 0x9fb2dbf9, 0x9fd3bdf9, 0xb45e584b, 0xb849e98b, 0xbe54b95e, 0xbe98b59e, 0xbf5395fb, 0xbf9579fb, 0xc54d495c, 0xc958d89c, 0xcd45c84d, 0xcd89c48d, 0xcf4384fc, 0xcf8478fc, 0xdf5295fd, 0xdf9569fd, 0xef4284fe, 0xef8468fe, 0x1218ef812e, 0x1219df912d, 0x1318cf813c, 0x1319bf913b, 0x1614ef416e, 0x1615df516d, 0x1714cf417c, 0x1715bf517b, 0x1b419e914b, 0x1b815e518b, 0x1c518d815c, 0x1c914d419c, 0x2428427842, 0x2529527952, 0x2a28fea2f8, 0x2a29fda2f9, 0x2b2db27db2, 0x2c2ec27ec2, 0x3438436843, 0x3539536953, 0x3a38fca3f8, 0x3a39fba3f9, 0x3bd3bd6bd3, 0x3ce3ce6ce3, 0x42d42e9ed4, 0x43b43c9cb4, 0x49cb4797c9, 0x49ed4696e9, 0x4a6aef4ea6, 0x4a7acf4ca7, 0x4ab9eab4e9, 0x4ad9cad4c9, 0x4b45e546b4, 0x4d45c547d4, 0x4fbefb7ef4, 0x4fc6dfcdf4, 0x52e52d8de5, 0x53c53b8bc5, 0x58bc5787b8, 0x58de5686d8, 0x5a6adf5da6, 0x5a7abf5ba7, 0x5ac8dac5d8, 0x5ae8bae5b8, 0x5c54d456c5, 0x5e54b457e5, 0x5fb6efbef5, 0x5fcdfc7df5, 0x8b289e98b8, 0x8d389c98d8, 0x8fbefb3ef8, 0x8fc2dfcdf8, 0x9c298d89c9, 0x9e398b89e9, 0x9fb2efbef9, 0x9fcdfc3df9, 0xbf49f479fb, 0xbf538f58fb, 0xcf439f49fc, 0xcf58f578fc, 0xdf49f469fd, 0xdf528f58fd, 0xef429f49fe, 0xef58f568fe, 0x2428429e9842, 0x2529528d8952, 0x2b29edbed2b9, 0x2c28decde2c8, 0x3438439c9843, 0x3539538b8953, 0x3d39cbdcb3d9, 0x3e38bcebc3e8, 0x42f4ef427ef4, 0x43f4cf436cf4, 0x4846845e5486, 0x4847845c5487, 0x4b7ecb47e7ce, 0x4ced6ced46c6, 0x52f5df527df5, 0x53f5bf536bf5, 0x5956954d4596, 0x5957954b4597, 0x5bde6bde56b6, 0x5c7dbc57d7bd, 0x86f8ef863ef8, 0x87f8cf872cf8, 0x96f9df963df9, 0x97f9bf972bf9, }; map[32] = { 0x16d, 0x21d, 0x62d, 0x16343, 0x16787, 0x16efe, 0x178a7, 0x187b8, 0x19c9d, 0x1a7ba, 0x1aba6, 0x1b8ab, 0x21343, 0x21aba, 0x21efe, 0x23473, 0x24384, 0x2595d, 0x27387, 0x27871, 0x28478, 0x3186a, 0x34362, 0x346a3, 0x34736, 0x34a31, 0x34a73, 0x373d6, 0x3a31d, 0x3a73d, 0x3ad84, 0x4176b, 0x436b4, 0x43846, 0x43b41, 0x43b84, 0x484d6, 0x4b41d, 0x4b84d, 0x4bd73, 0x56c5d, 0x595d6, 0x5c51d, 0x5c95d, 0x62787, 0x62aba, 0x62efe, 0x6a3ba, 0x6b4ab, 0x73a87, 0x73db8, 0x76b23, 0x78376, 0x78a72, 0x7a27d, 0x84b78, 0x84da7, 0x86a24, 0x87486, 0x87b82, 0x8b28d, 0x9c2d9, 0xa2417, 0xa31ba, 0xa73ba, 0xa7d4b, 0xab7a2, 0xb2318, 0xb41ab, 0xb84ab, 0xb8d3a, 0xba8b2, 0xd17a7, 0xd18b8, 0xd2373, 0xd2484, 0xd36a3, 0xd46b4, 0x1318163, 0x13439c9, 0x13813b8, 0x1417164, 0x14714a7, 0x1635f53, 0x1645e54, 0x178ce7c, 0x179f9a7, 0x17d7bd7, 0x187cf8c, 0x189e9b8, 0x18d8ad8, 0x19ae9ba, 0x19bf9ab, 0x19eae9d, 0x19eafe9, 0x19fbef9, 0x19fbf9d, 0x1a686a6, 0x1a7aefe, 0x1a7cfca, 0x1acfca6, 0x1b676b6, 0x1b8bfef, 0x1b8cecb, 0x1bcecb6, 0x1c9787c, 0x1c9caba, 0x1c9cefe, 0x1ce7fec, 0x1cf8efc, 0x1d7ece7, 0x1d8fcf8, 0x1e9896e, 0x1e98c9e, 0x1ec9bce, 0x1f9796f, 0x1f97c9f, 0x1fc9acf, 0x2132b23, 0x2142a24, 0x21acfca, 0x21bcecb, 0x232b273, 0x2349e39, 0x235f573, 0x23d38d3, 0x242a284, 0x2439f49, 0x245e584, 0x24d47d4, 0x257e587, 0x258f578, 0x2595aba, 0x25e7e5d, 0x25e7fe5, 0x25f8ef5, 0x25f8f5d, 0x2714171, 0x2737efe, 0x2739f97, 0x279f971, 0x2813181, 0x2848fef, 0x2849e98, 0x289e981, 0x2953439, 0x2959787, 0x2959efe, 0x29e3fe9, 0x29f4ef9, 0x2d3e9e3, 0x2d4f9f4, 0x2e5451e, 0x2e5495e, 0x2e9589e, 0x2f5351f, 0x2f5395f, 0x2f9579f, 0x3181a31, 0x31f96af, 0x3435956, 0x343c95c, 0x343c9c2, 0x346ce3c, 0x34739c9, 0x348a348, 0x349ca39, 0x349e396, 0x349e3c9, 0x34a3595, 0x34ae9e3, 0x34ce31c, 0x34ce73c, 0x35f5362, 0x35f56a3, 0x35f5736, 0x35f5a73, 0x362b232, 0x36a3efe, 0x37387b8, 0x3763fef, 0x39ca3d9, 0x39e3d96, 0x39e3dc9, 0x3a3595d, 0x3a5f531, 0x3a73fef, 0x3b238b2, 0x3ce3d1c, 0x3ce73dc, 0x3cecd84, 0x3d36bd3, 0x3d38d36, 0x3d3bd31, 0x3db8d3d, 0x3dbd73d, 0x4171b41, 0x41e96be, 0x436cf4c, 0x437b437, 0x43849c9, 0x439cb49, 0x439f496, 0x439f4c9, 0x43b4595, 0x43bf9f4, 0x43cf41c, 0x43cf84c, 0x45e5462, 0x45e56b4, 0x45e5846, 0x45e5b84, 0x462a242, 0x46b4fef, 0x48478a7, 0x4864efe, 0x49cb4d9, 0x49f4d96, 0x49f4dc9, 0x4a247a2, 0x4b4595d, 0x4b5e541, 0x4b84efe, 0x4cf4d1c, 0x4cf84dc, 0x4cfcd73, 0x4d46ad4, 0x4d47d46, 0x4d4ad41, 0x4da7d4d, 0x4dad84d, 0x56ae5ba, 0x56bf5ab, 0x56c5343, 0x56c5787, 0x56c5aba, 0x56c5efe, 0x5787956, 0x57ac587, 0x57e576d, 0x57e5876, 0x57e5a7d, 0x57e5a87, 0x57e5db8, 0x58bc578, 0x58f5786, 0x58f586d, 0x58f5b78, 0x58f5b8d, 0x58f5da7, 0x59578a7, 0x59587b8, 0x595a7ad, 0x595a7ba, 0x595aba6, 0x595b8ab, 0x595b8bd, 0x5a7ac5d, 0x5a7df5b, 0x5a7e5ba, 0x5ab7ac5, 0x5ae51ad, 0x5ae51ba, 0x5ae95ad, 0x5ae95ba, 0x5b8bc5d, 0x5b8de5a, 0x5b8f5ab, 0x5ba8bc5, 0x5bf51ab, 0x5bf51bd, 0x5bf95ab, 0x5bf95bd, 0x5c53473, 0x5c54384, 0x5c57387, 0x5c58478, 0x5c78795, 0x5c7e587, 0x5c8f578, 0x5c95aba, 0x5c95efe, 0x5ce7e5d, 0x5ce7fe5, 0x5cf8ef5, 0x5cf8f5d, 0x5e6ae5d, 0x5ea7fe5, 0x5ead8f5, 0x5ef6ae5, 0x5ef7e56, 0x5efae51, 0x5efae95, 0x5f6bf5d, 0x5fb8ef5, 0x5fbd7e5, 0x5fe6bf5, 0x5fe8f56, 0x5febf51, 0x5febf95, 0x6279f97, 0x6289e98, 0x62a686a, 0x62b676b, 0x67b674b, 0x68a683a, 0x6a3cfca, 0x6b4cecb, 0x6ce3ecd, 0x6ce3fec, 0x6cf4efc, 0x6cf4fcd, 0x6e5c45e, 0x6ecb5ce, 0x6ecbc2e, 0x6f5c35f, 0x6fca5cf, 0x6fcac2f, 0x7367b67, 0x7379c9d, 0x73879c9, 0x739f976, 0x73a9f97, 0x76fc23f, 0x783ece7, 0x7875c51, 0x7879c92, 0x78ce7c2, 0x79f9a72, 0x7a27fef, 0x7a7ba4b, 0x7c537dc, 0x7ce7dc2, 0x7d4bd7d, 0x7d7bd72, 0x8468a68, 0x84789c9, 0x8489c9d, 0x849e986, 0x84b9e98, 0x86ec24e, 0x874fcf8, 0x87cf8c2, 0x89e9b82, 0x8b28efe, 0x8b8ab3a, 0x8c548dc, 0x8cf8dc2, 0x8d3ad8d, 0x8d8ad82, 0x93adf49, 0x94bde39, 0x9a359ba, 0x9abac92, 0x9ae93ad, 0x9ae93ba, 0x9ae9a2d, 0x9ae9ba2, 0x9ae9d4b, 0x9b459ab, 0x9bf94ab, 0x9bf94bd, 0x9bf9ab2, 0x9bf9b2d, 0x9bf9d3a, 0x9c9ab3a, 0x9c9ba4b, 0x9e3afe9, 0x9e3dbf9, 0x9ef3e96, 0x9ef3ec9, 0x9efae92, 0x9f4bef9, 0x9f4dae9, 0x9fe4f96, 0x9fe4fc9, 0x9febf92, 0xa2f517f, 0xa31afef, 0xa31cfca, 0xa73cfca, 0xa7cfca2, 0xabac5c1, 0xb2e518e, 0xb41befe, 0xb41cecb, 0xb84cecb, 0xb8cecb2, 0xc3435c1, 0xc73df8c, 0xc84de7c, 0xce73fec, 0xce7d4fc, 0xcef3ec1, 0xcef7ec2, 0xcf84efc, 0xcf8d3ec, 0xcfe4fc1, 0xcfe8fc2, 0xe5186ce, 0xe5495e6, 0xe54c95e, 0xe5c45e1, 0xe9589e6, 0xe95c89e, 0xe96b25e, 0xe98c9e2, 0xec2419e, 0xec51bce, 0xec95bce, 0xec9bce2, 0xefe5956, 0xefe9c92, 0xefec5c1, 0xf5176cf, 0xf5395f6, 0xf53c95f, 0xf5c35f1, 0xf9579f6, 0xf95c79f, 0xf96a25f, 0xf97c9f2, 0xfc2319f, 0xfc51acf, 0xfc95acf, 0xfc9acf2, 0x13129f913, 0x13161b613, 0x131813c9c, 0x135c9bc53, 0x13813fcf8, 0x13f913c9f, 0x14129e914, 0x14161a614, 0x141714c9c, 0x145c9ac54, 0x14714ece7, 0x14e914c9e, 0x16715f517, 0x16815e518, 0x1715f51a7, 0x17d7fcfd7, 0x1815e51b8, 0x18d8eced8, 0x197f97bf9, 0x198e98ae9, 0x19edbede9, 0x19fdafdf9, 0x1a6a9f96a, 0x1b6b9e96b, 0x1ce7bcebc, 0x1cf8acfac, 0x1e512815e, 0x1e914196e, 0x1ec6c86ce, 0x1f512715f, 0x1f913196f, 0x1fc6c76cf, 0x2132cfc23, 0x2142cec24, 0x232b29e39, 0x232cfc273, 0x23d3f9fd3, 0x242a29f49, 0x242cec284, 0x24d4e9ed4, 0x253f538f5, 0x254e547e5, 0x25ed8ede5, 0x25fd7fdf5, 0x2712b2171, 0x2812a2181, 0x29532b239, 0x29542a249, 0x29e389e89, 0x29f479f79, 0x2a25f562a, 0x2ac9589ca, 0x2af52a95f, 0x2b25e562b, 0x2bc9579cb, 0x2be52b95e, 0x2e52b251e, 0x2ec2642ce, 0x2f52a251f, 0x2fc2632cf, 0x3181ce31c, 0x326286232, 0x34ece3484, 0x3589ca895, 0x359c89532, 0x37387cf8c, 0x373f97c9f, 0x381835c51, 0x38dfcf83d, 0x39c2b2329, 0x39efb3ef9, 0x3a19f9131, 0x3a343f9f4, 0x3a953f539, 0x3b23f9fb2, 0x3bc5395c8, 0x3bdbe9e3d, 0x3c537f53c, 0x3cecd38d3, 0x3cf538f5c, 0x3d36cfd3c, 0x3d39fd396, 0x3d39fd3c9, 0x3d3bd3595, 0x3d3fcfd31, 0x3d9cb3d39, 0x3dfcfd73d, 0x3fc239c2f, 0x4171cf41c, 0x426276242, 0x43fcf4373, 0x4579cb795, 0x459c79542, 0x471745c51, 0x47dece74d, 0x48478ce7c, 0x484e98c9e, 0x49c2a2429, 0x49fea4fe9, 0x4a24e9ea2, 0x4ac5495c7, 0x4adaf9f4d, 0x4b19e9141, 0x4b434e9e3, 0x4b954e549, 0x4c548e54c, 0x4ce547e5c, 0x4cfcd47d4, 0x4d46ced4c, 0x4d49ed496, 0x4d49ed4c9, 0x4d4ad4595, 0x4d4eced41, 0x4d9ca4d49, 0x4deced84d, 0x4ec249c2e, 0x53f536bf5, 0x53f538f56, 0x53f53b8f5, 0x53f53bf51, 0x54e546ae5, 0x54e547e56, 0x54e54a7e5, 0x54e54ae51, 0x5676b6c57, 0x5686a6c58, 0x56ae5686a, 0x56bf5676b, 0x576b67956, 0x579c9bc53, 0x579f795a7, 0x57abf57ab, 0x57dbc57d7, 0x57e567b67, 0x57e587b8b, 0x57edb7d75, 0x586a68956, 0x589c9ac54, 0x589e895b8, 0x58bae58ba, 0x58dac58d8, 0x58f568a68, 0x58f578a7a, 0x58fda8d85, 0x595ada8da, 0x595bdb7db, 0x5acfc7ac5, 0x5ada8dea5, 0x5adf51ada, 0x5adf95ada, 0x5aeafe8f5, 0x5bcec8bc5, 0x5bdb7dfb5, 0x5bde51bdb, 0x5bde95bdb, 0x5bfbef7e5, 0x5c53d38d3, 0x5c54d47d4, 0x5cafca8f5, 0x5cbecb7e5, 0x5ded8de56, 0x5dedb8de5, 0x5dfd7df56, 0x5dfda7df5, 0x5e5945ae9, 0x5e9589ae9, 0x5ed6bde5d, 0x5f5935bf9, 0x5f9579bf9, 0x5fd6adf5d, 0x62a69f96a, 0x62b69e96b, 0x67954c597, 0x67fc675cf, 0x68953c598, 0x68ec685ce, 0x6a369f96a, 0x6b469e96b, 0x6cafca4fc, 0x6cbecb3ec, 0x6ec686c2e, 0x6fc676c2f, 0x736cfc676, 0x79c5bc971, 0x7cef47efc, 0x7d74d79c9, 0x7d75cfd75, 0x7d7cfd7c2, 0x7f517c51f, 0x846cec686, 0x89c5ac981, 0x8cfe38fec, 0x8d83d89c9, 0x8d85ced85, 0x8d8ced8c2, 0x8e518c51e, 0x97f974bf9, 0x97f974f96, 0x97f97bf92, 0x98e983ae9, 0x98e983e96, 0x98e98ae92, 0x9acfac93a, 0x9ae9ba4b4, 0x9aed4ada9, 0x9bcebc94b, 0x9bf9ab3a3, 0x9bfd3bdb9, 0x9ded4bde9, 0x9dedbde92, 0x9dfd3adf9, 0x9dfdadf92, 0x9e398c9ec, 0x9e3bcebc9, 0x9f497c9fc, 0x9f4acfac9, 0xa725f52a2, 0xac5945ca6, 0xaf96a596f, 0xb825e52b2, 0xbc5935cb6, 0xbe96b596e, 0xcafca4fc1, 0xcafca84fc, 0xcafca8fc2, 0xcbecb3ec1, 0xcbecb73ec, 0xcbecb7ec2, 0x13161cfc613, 0x1391f913bf9, 0x14161cec614, 0x1491e914ae9, 0x16a615f516a, 0x16b615e516b, 0x17e7fe7bfe7, 0x18f8ef8aef8, 0x21712cfc217, 0x21812cec218, 0x21a21f912af, 0x21b21e912be, 0x23e3fe38fe3, 0x24f4ef47ef4, 0x25e52b257e5, 0x25f52a258f5, 0x32629f96232, 0x35295895325, 0x353c51bc535, 0x3598a359535, 0x35bc5358bc5, 0x395cb35c593, 0x3a353f538f5, 0x3c2fc238fc2, 0x3c5953895c3, 0x3e3fe3bfe31, 0x3e3fe6bfe3e, 0x3e3febfe73e, 0x42629e96242, 0x45295795425, 0x454c51ac545, 0x4597b459545, 0x45ac5457ac5, 0x495ca45c594, 0x4b454e547e5, 0x4c2ec247ec2, 0x4c5954795c4, 0x4f4ef4aef41, 0x4f4ef6aef4f, 0x4f4efaef84f, 0x535c537bc53, 0x539589535b8, 0x53f53bf5373, 0x545c548ac54, 0x549579545a7, 0x54e54ae5484, 0x5aca9c89ca5, 0x5bcb9c79cb5, 0x5e51815ae51, 0x5f51715bf51, 0x62762f5267f, 0x62862e5268e, 0x67c6fc674fc, 0x68c6ec683ec, 0x73797f97bf9, 0x73cbc97c9bc, 0x791c9bc9719, 0x79759645979, 0x7e7fe4fea7e, 0x7e7fe74fe76, 0x84898e98ae9, 0x84cac98c9ac, 0x891c9ac9819, 0x89859635989, 0x8f8ef3efb8f, 0x8f8ef83ef86, 0x97c9bc9794b, 0x97f974f97a7, 0x98c9ac9893a, 0x98e983e98b8, 0x9e396b69e96, 0x9f496a69f96, 0xa7acafca4fc, 0xac65c45ca6c, 0xaca9c289cac, 0xaeafe8fe3ae, 0xaeafea8fea2, 0xb8bcbecb3ec, 0xbc65c35cb6c, 0xbcb9c279cbc, 0xbfbef7ef4bf, 0xbfbefb7efb2, 0xcafca8fca3a, 0xcbecb7ecb4b, }; map[33] = { 0x16df, 0x16ed, 0x16fe, 0x21df, 0x21ed, 0x21fe, 0x62df, 0x62ed, 0x62fe, 0x1343f6, 0x1454e6, 0x1535d6, 0x163543, 0x163f53, 0x164e34, 0x165d45, 0x16787f, 0x16797d, 0x167987, 0x16898e, 0x16abaf, 0x16acad, 0x16bcbe, 0x16dbcb, 0x16eaba, 0x16fcac, 0x178fa7, 0x1796ba, 0x1798a7, 0x179a7d, 0x17a7df, 0x17a7ed, 0x17af97, 0x17dbf9, 0x1876cb, 0x1879b8, 0x187b8f, 0x189eb8, 0x18b8df, 0x18b8fe, 0x18be78, 0x18fce7, 0x197dc9, 0x1986ac, 0x1987c9, 0x198c9e, 0x19c9ed, 0x19c9fe, 0x19cd89, 0x19ead8, 0x1a7afe, 0x1a7baf, 0x1a7cad, 0x1a7cba, 0x1a7fca, 0x1ac687, 0x1acba6, 0x1ad8fc, 0x1b8abf, 0x1b8acb, 0x1b8bed, 0x1b8cbe, 0x1b8eab, 0x1ba698, 0x1bf9ea, 0x1c9acd, 0x1c9bac, 0x1c9bce, 0x1c9cdf, 0x1c9dbc, 0x1cb679, 0x1ce7db, 0x1d8986, 0x1d89b8, 0x1db8cb, 0x1e7876, 0x1e78a7, 0x1ea7ba, 0x1f9796, 0x1f97c9, 0x1fc9ac, 0x21343f, 0x21353d, 0x213543, 0x21454e, 0x21787f, 0x21797d, 0x21898e, 0x21abaf, 0x21acba, 0x21afca, 0x21bcbe, 0x21beab, 0x21cacd, 0x21cdbc, 0x21d898, 0x21e787, 0x21f979, 0x234f73, 0x235187, 0x235473, 0x23573d, 0x2373df, 0x2373ed, 0x237f53, 0x23d8f5, 0x243198, 0x243584, 0x24384f, 0x245e84, 0x2484df, 0x2484fe, 0x248e34, 0x24f9e3, 0x253d95, 0x254179, 0x254395, 0x25495e, 0x2595ed, 0x2595fe, 0x259d45, 0x25e7d4, 0x2737fe, 0x27387f, 0x27397d, 0x273987, 0x273f97, 0x279143, 0x279871, 0x27d4f9, 0x28478f, 0x284798, 0x2848ed, 0x28498e, 0x284e78, 0x287154, 0x28f5e7, 0x29579d, 0x295879, 0x29589e, 0x2959df, 0x295d89, 0x298135, 0x29e3d8, 0x2d4541, 0x2d4584, 0x2d8498, 0x2e3431, 0x2e3473, 0x2e7387, 0x2f5351, 0x2f5395, 0x2f9579, 0x3186af, 0x3196ad, 0x3196ba, 0x3196db, 0x31986a, 0x319ad8, 0x319b8a, 0x31dbf9, 0x31f96a, 0x34f362, 0x34f6a3, 0x34f736, 0x34fa31, 0x34fa73, 0x3516ba, 0x35186a, 0x351876, 0x3518a7, 0x351db8, 0x3521ba, 0x354362, 0x3546a3, 0x354a31, 0x354a73, 0x3562ba, 0x356a3d, 0x3573d6, 0x35a31d, 0x35a73d, 0x35ad84, 0x36a3df, 0x36a3ed, 0x36a3fe, 0x3763fe, 0x376543, 0x376f53, 0x3956ba, 0x39586a, 0x395ba8, 0x3a31df, 0x3a73ed, 0x3a73fe, 0x3a7f53, 0x3ad84f, 0x3ad8f5, 0x3adf95, 0x3aed95, 0x3af531, 0x3afe95, 0x3ba8f5, 0x3baf95, 0x3d6bf5, 0x3d86f5, 0x3db8f5, 0x3db985, 0x3dbf51, 0x3dbf95, 0x3f5362, 0x4176bf, 0x4176cb, 0x4176fc, 0x41796b, 0x417bf9, 0x417c9b, 0x4196be, 0x41e76b, 0x41fce7, 0x4316cb, 0x43196b, 0x431986, 0x4319b8, 0x431fc9, 0x4321cb, 0x4356b4, 0x435b41, 0x435b84, 0x4362cb, 0x436b4f, 0x4384f6, 0x43b41f, 0x43b84f, 0x43bf95, 0x45e462, 0x45e6b4, 0x45e846, 0x45eb41, 0x45eb84, 0x46b4df, 0x46b4ed, 0x46b4fe, 0x4736cb, 0x47396b, 0x473cb9, 0x486354, 0x4864ed, 0x486e34, 0x4b41fe, 0x4b84df, 0x4b84ed, 0x4b8e34, 0x4bdf73, 0x4be341, 0x4bed73, 0x4bf95e, 0x4bf9e3, 0x4bfe73, 0x4cb9e3, 0x4cbe73, 0x4e3462, 0x4f6ce3, 0x4f96e3, 0x4fc793, 0x4fc9e3, 0x4fce31, 0x4fce73, 0x5176cd, 0x5186ac, 0x5186ce, 0x5186ea, 0x51876c, 0x518a7c, 0x518ce7, 0x51d86c, 0x51ead8, 0x53d562, 0x53d6c5, 0x53d956, 0x53dc51, 0x53dc95, 0x5416ac, 0x54176c, 0x541796, 0x5417c9, 0x541ea7, 0x5421ac, 0x5436c5, 0x543c51, 0x543c95, 0x5462ac, 0x546c5e, 0x5495e6, 0x54c51e, 0x54c95e, 0x54ce73, 0x56c5df, 0x56c5ed, 0x56c5fe, 0x5846ac, 0x58476c, 0x584ac7, 0x596435, 0x5965df, 0x596d45, 0x5ac7d4, 0x5acd84, 0x5c51ed, 0x5c95df, 0x5c95fe, 0x5c9d45, 0x5cd451, 0x5cdf84, 0x5ce73d, 0x5ce7d4, 0x5ced84, 0x5cfe84, 0x5d4562, 0x5e6ad4, 0x5e76d4, 0x5ea7d4, 0x5ea874, 0x5ead41, 0x5ead84, 0x62787f, 0x627987, 0x627f97, 0x62898e, 0x628e78, 0x62979d, 0x629d89, 0x62abaf, 0x62acad, 0x62acba, 0x62bcbe, 0x63af53, 0x64be34, 0x65cd45, 0x6a3baf, 0x6a3cad, 0x6a3cba, 0x6a3fca, 0x6ac243, 0x6ad4fc, 0x6b4abf, 0x6b4acb, 0x6b4cbe, 0x6b4eab, 0x6ba254, 0x6bf5ea, 0x6c5acd, 0x6c5bac, 0x6c5bce, 0x6c5dbc, 0x6cb235, 0x6ce3db, 0x6d4b54, 0x6dbc4b, 0x6dbcb2, 0x6e3a43, 0x6eab3a, 0x6eaba2, 0x6f5c35, 0x6fca5c, 0x6fcac2, 0x7376df, 0x73876f, 0x7396ba, 0x7397d6, 0x739876, 0x73a97d, 0x73a987, 0x73af97, 0x73d6cb, 0x73db8f, 0x73db98, 0x73dbf9, 0x73dfc9, 0x73edc9, 0x73f976, 0x73fec9, 0x743bf9, 0x76b23f, 0x76c23d, 0x76c243, 0x76c2d4, 0x76cb23, 0x76d4fc, 0x76fc23, 0x78f3a7, 0x78fa72, 0x791643, 0x796243, 0x796b23, 0x796ba2, 0x796d4b, 0x79a7d2, 0x7a27fe, 0x7a2987, 0x7a2f97, 0x7c9243, 0x7c9b23, 0x7d4bf9, 0x7d4cb9, 0x7d4f96, 0x7d4fc9, 0x7db2f9, 0x8476cb, 0x8478f6, 0x847986, 0x8486fe, 0x84986e, 0x84b78f, 0x84b798, 0x84be78, 0x84dfa7, 0x84e786, 0x84eda7, 0x84f6ac, 0x84fc79, 0x84fc9e, 0x84fce7, 0x84fea7, 0x854ce7, 0x86a24f, 0x86a254, 0x86a2f5, 0x86ac24, 0x86c24e, 0x86ea24, 0x86f5ea, 0x871654, 0x876254, 0x876c24, 0x876cb2, 0x876f5c, 0x87b8f2, 0x89e4b8, 0x89eb82, 0x8a7254, 0x8a7c24, 0x8b2798, 0x8b28ed, 0x8b2e78, 0x8f5ac7, 0x8f5ce7, 0x8f5e76, 0x8f5ea7, 0x8fc2e7, 0x935ad8, 0x95796d, 0x9586ac, 0x958796, 0x9589e6, 0x9596ed, 0x95c879, 0x95c89e, 0x95cd89, 0x95d896, 0x95dfb8, 0x95e6ba, 0x95ea7d, 0x95ea87, 0x95ead8, 0x95edb8, 0x95feb8, 0x96a25d, 0x96b235, 0x96b25e, 0x96b2e3, 0x96ba25, 0x96db25, 0x96e3db, 0x97d5c9, 0x97dc92, 0x981635, 0x986235, 0x986a25, 0x986ac2, 0x986e3a, 0x98c9e2, 0x9b8235, 0x9b8a25, 0x9c2879, 0x9c29df, 0x9c2d89, 0x9e3ad8, 0x9e3ba8, 0x9e3d86, 0x9e3db8, 0x9ea2d8, 0xa2417f, 0xa2517d, 0xa25187, 0xa251d8, 0xa25417, 0xa257d4, 0xa2d8f5, 0xa2f517, 0xa31afe, 0xa31baf, 0xa31cad, 0xa31cba, 0xa31fca, 0xa5c417, 0xa73cad, 0xa73cba, 0xa73fca, 0xa7a2df, 0xa7ba2f, 0xa7c243, 0xa7cad2, 0xa7cba2, 0xa7d4bf, 0xa7d4cb, 0xa7d4fc, 0xa7df5c, 0xa7ed5c, 0xa7fca2, 0xa7fe5c, 0xa874fc, 0xabf73a, 0xac2187, 0xac2417, 0xac2431, 0xac2d84, 0xac6287, 0xad41fc, 0xad84fc, 0xad8f5c, 0xad8fc2, 0xb2318f, 0xb23198, 0xb231f9, 0xb23518, 0xb238f5, 0xb2518e, 0xb2e318, 0xb2f9e3, 0xb3a518, 0xb41abf, 0xb41acb, 0xb41bed, 0xb41cbe, 0xb41eab, 0xb84abf, 0xb84acb, 0xb84eab, 0xb8a254, 0xb8abf2, 0xb8acb2, 0xb8b2fe, 0xb8cb2e, 0xb8df3a, 0xb8eab2, 0xb8ed3a, 0xb8f5ac, 0xb8f5ce, 0xb8f5ea, 0xb8fe3a, 0xb985ea, 0xba2198, 0xba2518, 0xba2541, 0xba2f95, 0xba6298, 0xbce84b, 0xbf51ea, 0xbf95ea, 0xbf9e3a, 0xbf9ea2, 0xc2319d, 0xc24179, 0xc2419e, 0xc241e7, 0xc24319, 0xc249e3, 0xc2d419, 0xc2e7d4, 0xc4b319, 0xc51acd, 0xc51bac, 0xc51bce, 0xc51cdf, 0xc51dbc, 0xc793db, 0xc95bac, 0xc95bce, 0xc95dbc, 0xc9ac2d, 0xc9b235, 0xc9bac2, 0xc9bce2, 0xc9c2ed, 0xc9dbc2, 0xc9df4b, 0xc9e3ad, 0xc9e3ba, 0xc9e3db, 0xc9ed4b, 0xc9fe4b, 0xcad95c, 0xcb2179, 0xcb2319, 0xcb2351, 0xcb2e73, 0xcb6279, 0xce31db, 0xce73db, 0xce7d4b, 0xce7db2, 0xd4196b, 0xd45846, 0xd45b41, 0xd45b84, 0xd4b4f1, 0xd4bf95, 0xd848f6, 0xd84986, 0xd84b98, 0xd84fc9, 0xd86c24, 0xd89b82, 0xdb2518, 0xdb41cb, 0xdb84cb, 0xdb8bf2, 0xdb8cb2, 0xdb8f5c, 0xdf3a73, 0xe3186a, 0xe34736, 0xe34a31, 0xe34a73, 0xe3a3d1, 0xe3ad84, 0xe737d6, 0xe73876, 0xe73a87, 0xe73db8, 0xe76b23, 0xe78a72, 0xea2417, 0xea31ba, 0xea73ba, 0xea7ad2, 0xea7ba2, 0xea7d4b, 0xed5c95, 0xf5176c, 0xf53956, 0xf53c51, 0xf53c95, 0xf5c5e1, 0xf5ce73, 0xf95796, 0xf959e6, 0xf95c79, 0xf95ea7, 0xf96a25, 0xf97c92, 0xfc2319, 0xfc51ac, 0xfc95ac, 0xfc9ac2, 0xfc9ce2, 0xfc9e3a, 0xfe4b84, 0x1312813f, 0x13129813, 0x1312f913, 0x13191436, 0x13196b23, 0x13198163, 0x131f9163, 0x1321fc23, 0x132c6813, 0x135813b8, 0x1369193d, 0x138136cb, 0x138139b8, 0x13913dc9, 0x139143c9, 0x13cb6139, 0x13f913c9, 0x14127914, 0x1412914e, 0x1412e714, 0x14171546, 0x14176c24, 0x14179164, 0x141e7164, 0x1421ea24, 0x142a6914, 0x1467174f, 0x14714fa7, 0x147154a7, 0x149146ac, 0x149147c9, 0x14ac6147, 0x14e714a7, 0x1512715d, 0x15128715, 0x1512d815, 0x15181356, 0x15186a25, 0x15187165, 0x151d8165, 0x1521db25, 0x152b6715, 0x1568185e, 0x157156ba, 0x157158a7, 0x15815eb8, 0x15ba6158, 0x15d815b8, 0x1671f517, 0x1676fc67, 0x1681e318, 0x1686ea68, 0x1691d419, 0x1696db69, 0x16a986a9, 0x16ac86a8, 0x16af96a9, 0x16b796b7, 0x16ba96b9, 0x16be76b7, 0x16c876c8, 0x16cb76c7, 0x16cd86c8, 0x17151a7d, 0x176bf676, 0x176c67d6, 0x17941a74, 0x1797a7ba, 0x179bd7bd, 0x17af5175, 0x17ce7bce, 0x17cecf7e, 0x17e78ce7, 0x18131b8f, 0x186a68f6, 0x186ce686, 0x18751b85, 0x1878b8cb, 0x187cf8cf, 0x18ad8cad, 0x18adae8d, 0x18be3183, 0x18d89ad8, 0x19141c9e, 0x196ad696, 0x196b69e6, 0x19831c93, 0x1989c9ac, 0x198ae9ae, 0x19bf9abf, 0x19bfbd9f, 0x19cd4194, 0x19f97bf9, 0x1a78ca78, 0x1ab89ab8, 0x1ae9aeba, 0x1afe9aea, 0x1bc97bc9, 0x1bd7bdcb, 0x1bed7bdb, 0x1cdf8cfc, 0x1cf8cfac, 0x1d412914, 0x1d421c24, 0x1d7dbd7f, 0x1d7ecde7, 0x1d8dad8f, 0x1dae9dea, 0x1e312813, 0x1e321b23, 0x1e9fbef9, 0x1ecf8efc, 0x1f512715, 0x1f521a25, 0x2132b23f, 0x2132cb23, 0x2135b23b, 0x2142ac24, 0x2142c24e, 0x2143c24c, 0x2152a25d, 0x2152ba25, 0x2154a25a, 0x21754175, 0x21835183, 0x21943194, 0x231913d1, 0x232bf273, 0x232c2187, 0x232c273d, 0x23537387, 0x2358d38d, 0x235b273b, 0x237b23cb, 0x237c243c, 0x237fc23c, 0x239e389e, 0x239e9f3e, 0x23e349e3, 0x241714f1, 0x242a2198, 0x242a284f, 0x242ce284, 0x24348498, 0x2439f49f, 0x243c284c, 0x247d497d, 0x247d7e4d, 0x248a254a, 0x248ac24a, 0x248ea24a, 0x24d457d4, 0x251815e1, 0x252ad295, 0x252b2179, 0x252b295e, 0x25459579, 0x2547e57e, 0x254a295a, 0x258f578f, 0x258f8d5f, 0x259a25ba, 0x259b235b, 0x259db25b, 0x25f538f5, 0x27349734, 0x27845784, 0x27912b23, 0x27e57e87, 0x27fe57e7, 0x28712c24, 0x28953895, 0x28d38d98, 0x28ed38d8, 0x29812a25, 0x29df49f9, 0x29f49f79, 0x2a24f62a, 0x2a25462a, 0x2a26f52a, 0x2a62f96a, 0x2af52a95, 0x2b23562b, 0x2b25e62b, 0x2b26e32b, 0x2b62e76b, 0x2be32b73, 0x2c23d62c, 0x2c24362c, 0x2c26d42c, 0x2c62d86c, 0x2cd42c84, 0x2d3d8d3f, 0x2d3e9de3, 0x2d4d7d4f, 0x2d7e5de7, 0x2db2562b, 0x2db6296b, 0x2e5f8ef5, 0x2e9f4ef9, 0x2ea2462a, 0x2ea6286a, 0x2fc2362c, 0x2fc6276c, 0x3138163f, 0x314a3914, 0x319121ba, 0x319a313d, 0x321c232d, 0x3436b4cb, 0x34384986, 0x34384b98, 0x343b41cb, 0x343b84cb, 0x3489a348, 0x34a3484f, 0x3516b676, 0x3518a313, 0x35373876, 0x35373a87, 0x353a31ba, 0x353a73ba, 0x3548a348, 0x354a3595, 0x3562686a, 0x356a3bab, 0x356bd3bd, 0x357387b8, 0x358ad38d, 0x358d38d6, 0x358d3b8d, 0x359a359d, 0x35b238b2, 0x35bd73bd, 0x35d3bd31, 0x362bf232, 0x362cb232, 0x36bdb3ed, 0x36ce3bce, 0x373879b8, 0x37387b8f, 0x37397dc9, 0x373987c9, 0x373e87b8, 0x373f97c9, 0x3818fa31, 0x38d38df6, 0x38d3b8df, 0x38d3e8d6, 0x38d3eb8d, 0x398623c2, 0x39e389e6, 0x39e38c9e, 0x39e39ed6, 0x39e39fe6, 0x39e3c9ed, 0x39e3c9fe, 0x39e3feb8, 0x3a13f913, 0x3a348e34, 0x3a813981, 0x3a9e389e, 0x3ad38d3f, 0x3ad9f49f, 0x3af53959, 0x3af9e39e, 0x3afe8f58, 0x3b236298, 0x3b238b2f, 0x3b238cb2, 0x3b8fe3ce, 0x3bd31bdf, 0x3bd31ebd, 0x3bd73bdf, 0x3bd73ebd, 0x3bdbed95, 0x3c23d9c2, 0x3c2439c2, 0x3c9e3bce, 0x3cb239c2, 0x3ce31bce, 0x3ce31ced, 0x3ce31cfe, 0x3ce73bce, 0x3ce73ced, 0x3ce73cfe, 0x3d36bdf3, 0x3dbf9e3e, 0x3e346ce3, 0x3e349e36, 0x3e34ce31, 0x3e34ce73, 0x3e73ce87, 0x3ecf8d3e, 0x3ed6ce3e, 0x3fc239c2, 0x4149164e, 0x415b4715, 0x417121cb, 0x417b414f, 0x421a242f, 0x4316c686, 0x4319b414, 0x4359b459, 0x435b4373, 0x4362696b, 0x436cf4cf, 0x437b437f, 0x438498c9, 0x439bf49f, 0x439f49f6, 0x439f4c9f, 0x43cf84cf, 0x43f4cf41, 0x4546c5ac, 0x45495796, 0x45495c79, 0x454c51ac, 0x454c95ac, 0x4597b459, 0x45b4595e, 0x462ac242, 0x462ce242, 0x46ad4cad, 0x46cfc4df, 0x479624a2, 0x47d47df6, 0x47d47ed6, 0x47d497d6, 0x47d49a7d, 0x47d4a7df, 0x47d4a7ed, 0x47d4edc9, 0x48478fa7, 0x484798a7, 0x484987c9, 0x48498c9e, 0x484d98c9, 0x484e78a7, 0x4919eb41, 0x49f49fe6, 0x49f4c9fe, 0x49f4d9f6, 0x49f4dc9f, 0x4a24f7a2, 0x4a2547a2, 0x4a7d4cad, 0x4ac247a2, 0x4ad41adf, 0x4ad41aed, 0x4ad41cad, 0x4ad84adf, 0x4ad84aed, 0x4ad84cad, 0x4b14e714, 0x4b459d45, 0x4b7d497d, 0x4b914791, 0x4be34737, 0x4be7d47d, 0x4bed9e39, 0x4bf49f4e, 0x4bf7e57e, 0x4c246279, 0x4c249ac2, 0x4c249c2e, 0x4c9ed4ad, 0x4cf41cfe, 0x4cf41dcf, 0x4cf84cfe, 0x4cf84dcf, 0x4cfcdf73, 0x4d456ad4, 0x4d457d46, 0x4d45ad41, 0x4d45ad84, 0x4d84ad98, 0x4dae9f4d, 0x4df6ad4d, 0x4ea247a2, 0x4f46cfe4, 0x4fce7d4d, 0x513c5813, 0x5157165d, 0x518121ac, 0x518c515e, 0x521b252e, 0x5378c537, 0x53c5373d, 0x5416a696, 0x5417c515, 0x5437c537, 0x543c5484, 0x5462676c, 0x546ae5ae, 0x547ce57e, 0x547e57e6, 0x547e5a7e, 0x548c548e, 0x549579a7, 0x54ae95ae, 0x54e5ae51, 0x562ad252, 0x562ba252, 0x56aea5fe, 0x56bf5abf, 0x5717dc51, 0x57e57ed6, 0x57e5a7ed, 0x57e5f7e6, 0x57e5fa7e, 0x587625b2, 0x58f578f6, 0x58f57b8f, 0x58f58df6, 0x58f58fe6, 0x58f5b8df, 0x58f5b8fe, 0x58f5dfa7, 0x595798a7, 0x59579a7d, 0x595879b8, 0x59589eb8, 0x595d89b8, 0x595f79a7, 0x5a256287, 0x5a257a2d, 0x5a257ba2, 0x5a7df5bf, 0x5ae51aed, 0x5ae51fae, 0x5ae95aed, 0x5ae95fae, 0x5aeafe84, 0x5b25e8b2, 0x5b8f5abf, 0x5ba258b2, 0x5bf51abf, 0x5bf51bdf, 0x5bf51bfe, 0x5bf95abf, 0x5bf95bdf, 0x5bf95bfe, 0x5c15d815, 0x5c537f53, 0x5c715871, 0x5c8f578f, 0x5cd45848, 0x5cd8f58f, 0x5cdf7d47, 0x5ce57e5d, 0x5ce8d38d, 0x5db258b2, 0x5e56aed5, 0x5ead8f5f, 0x5f536bf5, 0x5f538f56, 0x5f53bf51, 0x5f53bf95, 0x5f95bf79, 0x5fbd7e5f, 0x5fe6bf5f, 0x62a686af, 0x62a6986a, 0x62ac86a8, 0x62b6796b, 0x62b696be, 0x62ba96b9, 0x62c676cd, 0x62c6876c, 0x62cb76c7, 0x63fec3e3, 0x64eda4d4, 0x65dfb5f5, 0x679b674b, 0x67b67254, 0x67b67c4b, 0x67c67d5c, 0x67c6875c, 0x67fc675c, 0x68a68f3a, 0x68a6983a, 0x68c68235, 0x68c68a5c, 0x68ea683a, 0x69a69243, 0x69a69b3a, 0x69b69e4b, 0x69db694b, 0x6a34ca34, 0x6a3696ad, 0x6a3c86a8, 0x6a3f96a9, 0x6aeab5ea, 0x6b45ab45, 0x6b4676bf, 0x6b4a96b9, 0x6b4e76b7, 0x6bdbc3db, 0x6c53bc53, 0x6c5686ce, 0x6c5b76c7, 0x6c5d86c8, 0x6cfca4fc, 0x73497346, 0x734a9734, 0x7367b67f, 0x7367c67d, 0x7367fc67, 0x7387b8cb, 0x73967b67, 0x73a97aba, 0x73b67cb6, 0x73bdb97d, 0x73c687c6, 0x73dcf8cf, 0x73febf9b, 0x767b627f, 0x76c61643, 0x7845b784, 0x78748654, 0x787b84cb, 0x787b8cb2, 0x797a7ba2, 0x79a7ba4b, 0x79bd7bd2, 0x7a7ba4bf, 0x7a7bac4b, 0x7a7cad5c, 0x7a7cba5c, 0x7a7eba4b, 0x7a7fca5c, 0x7bd74bdf, 0x7bd7bdf2, 0x7bd7ebd2, 0x7cb21571, 0x7ce75bce, 0x7ce75cfe, 0x7ce7bce2, 0x7ce7ced2, 0x7ce7cfe2, 0x7ce7fe4b, 0x7e57e876, 0x7e5a7eba, 0x7e785ea7, 0x7e78ce72, 0x7f517c51, 0x8468a68f, 0x8468c68e, 0x8468ea68, 0x84768c68, 0x8498c9ac, 0x84a698a6, 0x84c68ac6, 0x84cfc78f, 0x84edce7c, 0x84fae9ae, 0x868c628e, 0x86a61654, 0x87b8cb5c, 0x87cf8cf2, 0x8953c895, 0x89859635, 0x898c95ac, 0x898c9ac2, 0x8ac21381, 0x8ad83aed, 0x8ad83cad, 0x8ad8adf2, 0x8ad8aed2, 0x8ad8cad2, 0x8ad8ed5c, 0x8b8abf3a, 0x8b8acb3a, 0x8b8cb5ce, 0x8b8cba5c, 0x8b8dcb5c, 0x8b8eab3a, 0x8cf85cfe, 0x8cf8cfe2, 0x8cf8dcf2, 0x8d38d986, 0x8d3b8dcb, 0x8d893db8, 0x8d89ad82, 0x8e318a31, 0x9569a69d, 0x9569b69e, 0x9569db69, 0x9579a7ba, 0x95869a69, 0x95a69ba6, 0x95aea89e, 0x95b679b6, 0x95dfad8a, 0x95ebd7bd, 0x969a629d, 0x96b61635, 0x98ae9ae2, 0x98c9ac3a, 0x9ae93aed, 0x9ae9aed2, 0x9ae9fae2, 0x9ba21491, 0x9bf94abf, 0x9bf94bdf, 0x9bf9abf2, 0x9bf9bdf2, 0x9bf9bfe2, 0x9bf9df3a, 0x9c9ac3ad, 0x9c9acb3a, 0x9c9bac4b, 0x9c9bce4b, 0x9c9dbc4b, 0x9c9fac3a, 0x9d419b41, 0x9f49f796, 0x9f4c9fac, 0x9f974fc9, 0x9f97bf92, 0xa314ca34, 0xa348ca34, 0xa72af52a, 0xa734ca34, 0xa73ca787, 0xa78ca782, 0xa7ba4b54, 0xa7fe4fc4, 0xab45ab41, 0xab45ab84, 0xab894ab8, 0xaba8b298, 0xae349ae3, 0xae9aeba2, 0xaeab5ea1, 0xaeab9e3a, 0xaf96a596, 0xb459ab45, 0xb82be32b, 0xb8cb5c35, 0xb8ed5ea5, 0xbc53bc51, 0xbc53bc95, 0xbc975bc9, 0xbcb9c279, 0xbd457bd4, 0xbd7bdcb2, 0xbdbc3db1, 0xbdbc7d4b, 0xbe76b376, 0xc537bc53, 0xc92cd42c, 0xc9ac3a43, 0xc9df3db3, 0xcd86c486, 0xcf538cf5, 0xcf8cfac2, 0xcfca4fc1, 0xcfca8f5c, 0xd38d3fc9, 0xd3a8d398, 0xd3bd73cb, 0xd457d4a7, 0xd4adaf95, 0xd7bd7f5c, 0xe349e3c9, 0xe3cecd84, 0xe57e5db8, 0xe5ae95ba, 0xe5c7e587, 0xe9ae9d4b, 0xf49f4ea7, 0xf4b9f479, 0xf4cf84ac, 0xf538f5b8, 0xf5bfbe73, 0xf8cf8e3a, 0x13161b613f, 0x13161c613d, 0x13161c6143, 0x13161fc613, 0x131813b8cb, 0x13218c2138, 0x135161b613, 0x13813cfc8f, 0x139f913bf9, 0x13bc913bc9, 0x14161a614f, 0x14161a6154, 0x14161c614e, 0x14161ea614, 0x141914c9ac, 0x14219a2149, 0x147e714ce7, 0x14914aea9e, 0x14a71ca714, 0x15161a615d, 0x15161b615e, 0x15161db615, 0x151715a7ba, 0x15217b2157, 0x15715bdb7d, 0x158d815ad8, 0x15ab815ab8, 0x16a61f516a, 0x16b61e316b, 0x16c61d416c, 0x17bfe7bfeb, 0x17cfdfc7df, 0x18aefea8fe, 0x18ced8cedc, 0x19adf9adfa, 0x19bdedb9ed, 0x21712fc217, 0x21812ea218, 0x21912db219, 0x21a21812af, 0x21a21912ad, 0x21a21f912a, 0x21b21712bf, 0x21b21912be, 0x21b21e712b, 0x21c21712cd, 0x21c21812ce, 0x21c21d812c, 0x232c237387, 0x232c28d38d, 0x238fe38fe8, 0x239fdf93df, 0x23e32b29e3, 0x242a248498, 0x242a29f49f, 0x247efe74fe, 0x249ed49ed9, 0x24d42c27d4, 0x252b259579, 0x252b27e57e, 0x257df57df7, 0x258ded85ed, 0x25f52a28f5, 0x2a212912ba, 0x2a624962a4, 0x2a8952a895, 0x2ac212812a, 0x2b212712cb, 0x2b625762b5, 0x2b7329732b, 0x2c623862c3, 0x2c7842c784, 0x3132b9123b, 0x3191d3bd31, 0x326239623d, 0x326286232f, 0x3262962432, 0x3262f96232, 0x32b238b298, 0x3436b496b9, 0x3437b437cb, 0x3438468c68, 0x3439cb49cb, 0x34a349f49f, 0x3526286232, 0x3537367b67, 0x353a3595ba, 0x353a68a63a, 0x353ba38ba3, 0x359d3bd359, 0x36ce3686ce, 0x37349734c9, 0x37387cf8cf, 0x3739f97bf9, 0x373bc97bc9, 0x3816c31681, 0x389c2389c2, 0x38bce38bce, 0x38dfc3df8d, 0x38fe38fe86, 0x39e369b69e, 0x39e389eb8b, 0x39efb3e9f9, 0x39fd3fd9f6, 0x3a13913aba, 0x3a35f538f5, 0x3a39538953, 0x3aefe8fe3e, 0x3b239fb29f, 0x3b26932b6b, 0x3bdbed39e3, 0x3bfe3bfe1b, 0x3cecde8d3e, 0x3cfc238fc2, 0x3d36cfd3cf, 0x3d38d398c9, 0x3d3cfd31cf, 0x3e3181ce31, 0x3e348ce348, 0x3e6bfbef3e, 0x3efebfe73e, 0x4142c7124c, 0x4171f4cf41, 0x426247624f, 0x4262762542, 0x426296242e, 0x4262e76242, 0x42c249c279, 0x437f4cf437, 0x4546c576c7, 0x4547ac57ac, 0x4548c548ac, 0x4549569a69, 0x45b457e57e, 0x46ad4696ad, 0x479a7a24a2, 0x47d467c67d, 0x47d497dc9c, 0x47dec4d7e7, 0x47ef4ef7e6, 0x48457845a7, 0x4847e78ce7, 0x48498ae9ae, 0x484a78ca78, 0x4916a41691, 0x49cad49cad, 0x49ed49ed96, 0x49fea4fe9f, 0x4adafd9f4d, 0x4aea249ea2, 0x4b14714bcb, 0x4b43e349e3, 0x4b47349734, 0x4bded9ed4d, 0x4c247ec27e, 0x4c26742c6c, 0x4ced4ced1c, 0x4cfcdf47d4, 0x4d4191ad41, 0x4d459ad459, 0x4d6cecde4d, 0x4dedced84d, 0x4f46aef4ae, 0x4f49f479a7, 0x4f4aef41ae, 0x5152a8125a, 0x5181e5ae51, 0x526258625e, 0x526276252d, 0x5262d86252, 0x52a257a287, 0x53c538d38d, 0x548e5ae548, 0x56bf5676bf, 0x5716b51671, 0x578b2578b2, 0x57abf57abf, 0x57df57df76, 0x57edb5ed7e, 0x58de5de8d6, 0x58f568a68f, 0x58f578fa7a, 0x58fda5f8d8, 0x59538953b8, 0x59579bd7bd, 0x5958d89ad8, 0x595ab89ab8, 0x5a258da28d, 0x5a26852a6a, 0x5adf5adf1a, 0x5aeafe58f5, 0x5bdb257db2, 0x5bfbef7e5f, 0x5c15815cac, 0x5c54d457d4, 0x5c58457845, 0x5cfdf7df5f, 0x5df56adf5a, 0x5e56bde5bd, 0x5e57e587b8, 0x5e5bde51bd, 0x5f5171bf51, 0x5f537bf537, 0x5fdfadf95f, 0x62762f5267, 0x62862e3268, 0x62962d4269, 0x6762562687, 0x676b456b47, 0x6796246267, 0x67cfc674fc, 0x6862362698, 0x686c536c58, 0x68aea685ea, 0x696a346a39, 0x69bdb693db, 0x7121c21871, 0x73467c6734, 0x76714c6174, 0x79121b2171, 0x7a78ca785c, 0x7a7cfca4fc, 0x7bc517bc51, 0x7bdf57dfbd, 0x7bfe7bfeb2, 0x7ce7bce4b4, 0x7cef47ecfc, 0x7cfd7fdcf2, 0x7d7bd7c5bc, 0x7e57e6b676, 0x7efe4fea7e, 0x8121a21981, 0x84568a6845, 0x86815a6185, 0x8a318ca318, 0x8ad8cad5c5, 0x8ade58daea, 0x8aef8efae2, 0x8b89ab893a, 0x8b8aeab5ea, 0x8ced8cedc2, 0x8cfe38fecf, 0x8d38d6c686, 0x8ded5edb8d, 0x8f8cf8a3ca, 0x95369b6953, 0x96913b6193, 0x9ab419ab41, 0x9adf9adfa2, 0x9aed49edae, 0x9bde9debd2, 0x9bf9abf3a3, 0x9bfd39fbdb, 0x9c97bc974b, 0x9c9bdbc3db, 0x9e9ae9b4ab, 0x9f49f6a696, 0x9fdf3dfc9f, 0xa616516ba6, 0xac616416a6, 0xb616316cb6, 0xd3adf9dfd3, 0xd3dfcdfd73, 0xd7df5dfda7, 0xe5ced8ede5, 0xe5edbede95, 0xe9ed4edec9, 0xf4bfe7fef4, 0xf4feafef84, 0xf8fe3fefb8, }; map[42] = { 0x16af, 0x176f, 0x1a7f, 0x316f, 0x321f, 0x362f, 0x62af, 0x6a3f, 0xa31f, 0xa73f, 0xf21a, 0xf736, 0x14546a, 0x145476, 0x1454a7, 0x16abcb, 0x16bcdb, 0x16cbec, 0x16dbdf, 0x16dbed, 0x16ecde, 0x16ecef, 0x176898, 0x176ded, 0x1789b8, 0x1798c9, 0x17b8bf, 0x17b8cb, 0x17bcb6, 0x17c9bc, 0x17c9cf, 0x186cad, 0x189ad8, 0x189b8a, 0x189d86, 0x189db8, 0x18dfc9, 0x196bae, 0x198ae9, 0x198c9a, 0x198e96, 0x198ec9, 0x19efb8, 0x1a7898, 0x1a7bcb, 0x1a7ded, 0x1ad8ed, 0x1ae9de, 0x1b8baf, 0x1b8cba, 0x1b8dbf, 0x1b8dcb, 0x1b8fec, 0x1bae78, 0x1bd7cb, 0x1c9bca, 0x1c9caf, 0x1c9ebc, 0x1c9ecf, 0x1c9fdb, 0x1cad79, 0x1ce7bc, 0x1d86df, 0x1d86ed, 0x1db8ed, 0x1dbd7f, 0x1dbf9e, 0x1debd7, 0x1e96de, 0x1e96ef, 0x1ec9de, 0x1ece7f, 0x1ecf8d, 0x1edce7, 0x1f8ad8, 0x1f9ae9, 0x21bcdb, 0x21bdbf, 0x21cbec, 0x21cecf, 0x21dbed, 0x21deda, 0x21ecde, 0x23723f, 0x26726f, 0x2a4584, 0x2a484f, 0x2a5495, 0x2a595f, 0x2a8498, 0x2a8981, 0x2a9589, 0x316898, 0x316ded, 0x3189b8, 0x3198c9, 0x31b8bf, 0x31b8cb, 0x31c9bc, 0x31c9cf, 0x321454, 0x321bcb, 0x321ded, 0x324584, 0x325495, 0x32848f, 0x328498, 0x328981, 0x329589, 0x32959f, 0x34196b, 0x3456b4, 0x345846, 0x345b41, 0x345b84, 0x34bf95, 0x35186c, 0x3546c5, 0x354956, 0x354c51, 0x354c95, 0x35cf84, 0x362454, 0x362898, 0x362bcb, 0x36b4cb, 0x36c5bc, 0x38486f, 0x384986, 0x384b8f, 0x384b98, 0x384fc9, 0x386c24, 0x38b298, 0x395896, 0x39596f, 0x395c89, 0x395c9f, 0x395fb8, 0x396b25, 0x39c289, 0x3b41bf, 0x3b41cb, 0x3b84cb, 0x3b8b2f, 0x3b8f5c, 0x3bc8b2, 0x3c51bc, 0x3c51cf, 0x3c95bc, 0x3c9c2f, 0x3c9f4b, 0x3cb9c2, 0x3ded62, 0x3f46b4, 0x3f56c5, 0x416cad, 0x4196ad, 0x4196ba, 0x4196db, 0x41976d, 0x419a7d, 0x41c9ad, 0x41dfc9, 0x421cad, 0x4542a1, 0x454316, 0x45462a, 0x4546a3, 0x454736, 0x456ad4, 0x456b4a, 0x457d46, 0x45846a, 0x4584a7, 0x45a7d4, 0x45ad41, 0x45ad84, 0x45b41a, 0x45b84a, 0x45d416, 0x45d421, 0x45d6b4, 0x45d846, 0x45db41, 0x45db84, 0x462cad, 0x46ad4f, 0x46b4fa, 0x47d4f6, 0x487654, 0x4a7d4f, 0x4ad41f, 0x4ad84f, 0x4adf95, 0x4b41fa, 0x4baf95, 0x4d416f, 0x4d421f, 0x4d4f62, 0x4d5462, 0x4d6b4f, 0x4db84f, 0x4dbf95, 0x4dcb95, 0x4df6c5, 0x4df956, 0x4dfc51, 0x4dfc95, 0x516bae, 0x5186ae, 0x5186ca, 0x5186ec, 0x51876e, 0x518a7e, 0x51b8ae, 0x51efb8, 0x521bae, 0x546ae5, 0x546c5a, 0x547e56, 0x54956a, 0x5495a7, 0x54a7e5, 0x54ae51, 0x54ae95, 0x54c51a, 0x54c95a, 0x54e516, 0x54e521, 0x54e6c5, 0x54e956, 0x54ec51, 0x54ec95, 0x562bae, 0x56ae5f, 0x56c5fa, 0x57e5f6, 0x597645, 0x5a7e5f, 0x5ae51f, 0x5ae95f, 0x5aef84, 0x5c51fa, 0x5caf84, 0x5e4562, 0x5e516f, 0x5e521f, 0x5e5f62, 0x5e6c5f, 0x5ebc84, 0x5ec95f, 0x5ecf84, 0x5ef6b4, 0x5ef846, 0x5efb41, 0x5efb84, 0x62a898, 0x62abcb, 0x62bcdb, 0x62cbec, 0x62dbdf, 0x62dbed, 0x62deda, 0x62ecde, 0x62ecef, 0x6898a3, 0x6a3ded, 0x6ad4ed, 0x6ae5de, 0x6b4cba, 0x6b4dcb, 0x6b4fec, 0x6bae34, 0x6bcdb3, 0x6c5bca, 0x6c5ebc, 0x6c5fdb, 0x6cad35, 0x6cbec3, 0x6d352b, 0x6d42ed, 0x6db4ed, 0x6dbd3f, 0x6dbed3, 0x6dbf5e, 0x6e342c, 0x6e52de, 0x6ec5de, 0x6ecde3, 0x6ece3f, 0x6ecf4d, 0x71271f, 0x7389b8, 0x738b8f, 0x7398c9, 0x739c9f, 0x73b8cb, 0x73bcb6, 0x73c9bc, 0x76de4d, 0x76ed5e, 0x7a27af, 0x846cad, 0x8486af, 0x84876f, 0x848fa7, 0x8498a7, 0x84ba98, 0x84d986, 0x84db98, 0x84dfc9, 0x84edc9, 0x84fae9, 0x84fc9a, 0x84fe6c, 0x84fe96, 0x84fec9, 0x86ae34, 0x86c24a, 0x86ca34, 0x86cad3, 0x86ec34, 0x876e34, 0x89486a, 0x894876, 0x894ad8, 0x89816a, 0x898736, 0x898a31, 0x898a73, 0x89a348, 0x89ad83, 0x89b8a3, 0x89d863, 0x89db83, 0x8a348f, 0x8a7e34, 0x8ad8f3, 0x8b2a98, 0x8d3fc9, 0x8d86f3, 0x956bae, 0x9589a7, 0x9596af, 0x95976f, 0x959fa7, 0x95ca89, 0x95deb8, 0x95e896, 0x95ec89, 0x95efb8, 0x95fad8, 0x95fb8a, 0x95fd6b, 0x95fd86, 0x95fdb8, 0x96ad35, 0x96b25a, 0x96ba35, 0x96bae3, 0x96db35, 0x976d35, 0x98596a, 0x985976, 0x985ae9, 0x98a359, 0x98ae93, 0x98c9a3, 0x98e963, 0x98ec93, 0x9a359f, 0x9a7d35, 0x9ae9f3, 0x9c2a89, 0x9e3fb8, 0x9e96f3, 0xa31454, 0xa31bcb, 0xa34584, 0xa35495, 0xa73bcb, 0xa73ded, 0xa74543, 0xa7d4ed, 0xa7e5de, 0xad3518, 0xad41ed, 0xad84ed, 0xad8ed3, 0xad8f5e, 0xae3419, 0xae51de, 0xae95de, 0xae9de3, 0xae9f4d, 0xb2a518, 0xb32518, 0xb41dcb, 0xb41fec, 0xb84cba, 0xb84dcb, 0xb84fec, 0xb8ae34, 0xb8b2af, 0xb8ba3f, 0xb8d3cb, 0xb8f5ae, 0xb8f5ca, 0xb8f5ec, 0xb8fe3c, 0xba3518, 0xbae318, 0xbae341, 0xbae738, 0xbc4ba1, 0xbc8b2a, 0xbc8ba3, 0xbcb21a, 0xbcb316, 0xbcb6a3, 0xbcdb31, 0xbd73cb, 0xc2a419, 0xc32419, 0xc51ebc, 0xc51fdb, 0xc95bca, 0xc95ebc, 0xc95fdb, 0xc9ad35, 0xc9c2af, 0xc9ca3f, 0xc9e3bc, 0xc9f4ad, 0xc9f4ba, 0xc9f4db, 0xc9fd3b, 0xca3419, 0xcad319, 0xcad351, 0xcad739, 0xcb5ca1, 0xcb9c2a, 0xcb9ca3, 0xcbec31, 0xce73bc, 0xd1796b, 0xd3196b, 0xd3516b, 0xd35186, 0xd351b8, 0xd3521b, 0xd3bf95, 0xd416ed, 0xd421ed, 0xd7396b, 0xd864ed, 0xd86f5e, 0xdb41ed, 0xdb84ed, 0xdb8ed3, 0xdb8f5e, 0xdbd31f, 0xdbd73f, 0xdbf51e, 0xdbf95e, 0xdbf9e3, 0xde8d36, 0xdebd31, 0xdebd73, 0xded16a, 0xded763, 0xdeda31, 0xe1786c, 0xe3186c, 0xe3416c, 0xe34196, 0xe341c9, 0xe3421c, 0xe3cf84, 0xe516de, 0xe521de, 0xe7386c, 0xe965de, 0xe96f4d, 0xec51de, 0xec95de, 0xec9de3, 0xec9f4d, 0xece31f, 0xece73f, 0xecf41d, 0xecf84d, 0xecf8d3, 0xed9e36, 0xedce31, 0xedce73, 0xf4ba84, 0xf4d846, 0xf5ca95, 0xf5e956, 0xf8d3b8, 0xf9e3c9, 0xfb41db, 0xfc51ec, 0x12712898, 0x12712ded, 0x1289d812, 0x128d812f, 0x1298e912, 0x129e912f, 0x12bcb712, 0x12d812ed, 0x12e912de, 0x14139146, 0x1416ca34, 0x141914a7, 0x1419a314, 0x142ae714, 0x142c7124, 0x14712914, 0x14914ae9, 0x14914c9a, 0x14914e96, 0x14e7146c, 0x15138156, 0x1516ba35, 0x151815a7, 0x1518a315, 0x152ad715, 0x152b7125, 0x15712815, 0x15815ad8, 0x15815b8a, 0x15815d86, 0x15d7156b, 0x1686c6a8, 0x168c68ec, 0x1696b6a9, 0x169b69db, 0x16abeabe, 0x16acdacd, 0x16bfbefb, 0x16cfcdfc, 0x17145b41, 0x17154c51, 0x171b41cb, 0x171c51bc, 0x17419164, 0x17518165, 0x176b96b9, 0x176c86c8, 0x178151b8, 0x1787e7b8, 0x178f8cf8, 0x179141c9, 0x1797d7c9, 0x179f9bf9, 0x17d7976d, 0x17e7876e, 0x186c6d86, 0x189cd89c, 0x18b8cbec, 0x18f8aef8, 0x18f8cf8a, 0x18f8ef86, 0x196b6e96, 0x198be98b, 0x19c9bcdb, 0x19f9adf9, 0x19f9bf9a, 0x19f9df96, 0x1a7dacad, 0x1a7eabae, 0x1ad8acad, 0x1ae9abae, 0x1b8abeab, 0x1bde9bde, 0x1bef9ebf, 0x1bf9bfdb, 0x1bfe7bfb, 0x1c9acdac, 0x1cdf8dcf, 0x1ced8ced, 0x1cf8cfec, 0x1cfd7cfc, 0x1d797bd7, 0x1d797da7, 0x1e787ce7, 0x1e787ea7, 0x1fdfc9fd, 0x1fefb8fe, 0x2142c24a, 0x214c24ec, 0x2152b25a, 0x215b25db, 0x21bfbefb, 0x21cfcdfc, 0x21dacada, 0x21eabaea, 0x23289873, 0x2328d398, 0x2329e389, 0x232d8d3f, 0x232de8d3, 0x232e9e3f, 0x232ed9e3, 0x237bcb23, 0x242c2a84, 0x243e2384, 0x24546276, 0x248c24ec, 0x252b2a95, 0x253d2395, 0x259b25db, 0x26289d86, 0x2628d86f, 0x26298e96, 0x2629e96f, 0x262d86ed, 0x262ded76, 0x262e96de, 0x28986276, 0x28b2db8f, 0x28b2db98, 0x29c2ec89, 0x29c2ec9f, 0x2a4f49f4, 0x2a5f58f5, 0x2a815181, 0x2a914191, 0x2b6926db, 0x2c6826ec, 0x2d4284df, 0x2d4284ed, 0x2ded3273, 0x2e5295de, 0x2e5295ef, 0x314914c9, 0x315815b8, 0x3168c68c, 0x3169b69b, 0x318f8cf8, 0x319f9bf9, 0x32185185, 0x32194194, 0x3242c284, 0x324f49f4, 0x3252b295, 0x325f58f5, 0x32737454, 0x32b2521b, 0x32c2421c, 0x32d3531d, 0x32d3573d, 0x32d7397d, 0x32e3431e, 0x32e3473e, 0x32e7387e, 0x34191b41, 0x343e36b4, 0x343e3846, 0x343e3b41, 0x3459b459, 0x345b4373, 0x348498c9, 0x34f46cf4, 0x34f49f46, 0x34f4cf41, 0x35181c51, 0x353d36c5, 0x353d3956, 0x353d3c51, 0x3548c548, 0x354c5373, 0x359589b8, 0x35f56bf5, 0x35f58f56, 0x35f5bf51, 0x36243e34, 0x36253d35, 0x362b696b, 0x362c686c, 0x36b4696b, 0x36c5686c, 0x374b437f, 0x375c537f, 0x37b437cb, 0x37c537bc, 0x38468c68, 0x38bc58bc, 0x38cf5c8f, 0x38f58fb8, 0x38fc28f8, 0x39569b69, 0x39bf4b9f, 0x39cb49cb, 0x39f49fc9, 0x39fb29f9, 0x3b23e318, 0x3b2528b2, 0x3b252b62, 0x3c23d319, 0x3c2429c2, 0x3c242c62, 0x3d3196ad, 0x3d356a3d, 0x3d35a31d, 0x3d76c23d, 0x3e3186ae, 0x3e346a3e, 0x3e34a31e, 0x3e76b23e, 0x3fbf95fb, 0x3fcf84fc, 0x416c67d6, 0x4191ad41, 0x4191b41a, 0x4191d421, 0x419db414, 0x4237c243, 0x428478fc, 0x42c2d421, 0x42cd4284, 0x42d42584, 0x434b8e34, 0x43796243, 0x43e13436, 0x45471271, 0x4547a27a, 0x4578b784, 0x457ab47a, 0x459b459a, 0x459d4259, 0x459d4596, 0x459d45c9, 0x459db459, 0x45ad4595, 0x45b6b476, 0x45cd451c, 0x45db7d47, 0x462696ad, 0x462c242a, 0x46b4f676, 0x46bce4bc, 0x473e3436, 0x4787b84f, 0x48478b98, 0x484798c9, 0x48498ae9, 0x48498c9a, 0x48498e96, 0x48498ec9, 0x484bc78b, 0x48795248, 0x4914916a, 0x49f49f76, 0x49f4e9f6, 0x49f4ec9f, 0x49fca49f, 0x4a3e3473, 0x4ae349e3, 0x4b41cbec, 0x4b84cbec, 0x4c249c2a, 0x4ca34739, 0x4d4546c5, 0x4d62c242, 0x4d8498c9, 0x4dc249c2, 0x4dcfc84f, 0x4df49f46, 0x4e346ce3, 0x4e349e36, 0x4e34ce31, 0x4e34ce73, 0x4ef421ef, 0x4ef84ef6, 0x4efb41ef, 0x4efb84ef, 0x4efe6b4f, 0x4f46aef4, 0x4f46cf4a, 0x4f47ef46, 0x4f49f46a, 0x4f49f4a7, 0x4f4aef41, 0x4f4aef84, 0x4f4cf41a, 0x4f4ef416, 0x4f9c279c, 0x4fe4f462, 0x4fecf84f, 0x516b67e6, 0x5181ae51, 0x5181c51a, 0x5181e521, 0x518ec515, 0x5237b253, 0x529579fb, 0x52b2e521, 0x52be5295, 0x52e52495, 0x535c9d35, 0x53786253, 0x53d13536, 0x5479c795, 0x547ac57a, 0x548c548a, 0x548e5248, 0x548e5486, 0x548e54b8, 0x548ec548, 0x54ae5484, 0x54be541b, 0x54c6c576, 0x54ec7e57, 0x562686ae, 0x562b252a, 0x56c5f676, 0x56cbd5cb, 0x573d3536, 0x5797c95f, 0x5815816a, 0x58f58f76, 0x58f5d8f6, 0x58f5db8f, 0x58fba58f, 0x595789b8, 0x59579c89, 0x59589ad8, 0x59589b8a, 0x59589d86, 0x59589db8, 0x595cb79c, 0x5a3d3573, 0x5ad358d3, 0x5b258b2a, 0x5ba35738, 0x5c51bcdb, 0x5c95bcdb, 0x5d356bd3, 0x5d358d36, 0x5d35bd31, 0x5d35bd73, 0x5df521df, 0x5df95df6, 0x5dfc51df, 0x5dfc95df, 0x5dfd6c5f, 0x5e456b4b, 0x5e62b252, 0x5e9589b8, 0x5eb258b2, 0x5ebfb95f, 0x5ef58f56, 0x5f56adf5, 0x5f56bf5a, 0x5f57df56, 0x5f58f56a, 0x5f58f5a7, 0x5f5adf51, 0x5f5adf95, 0x5f5bf51a, 0x5f5df516, 0x5f8b278b, 0x5fd5f562, 0x5fdbf95f, 0x62767bcb, 0x6286c6a8, 0x6286c768, 0x62876e78, 0x6296b6a9, 0x6296b769, 0x62976d79, 0x62adcadc, 0x62aebaeb, 0x62b252db, 0x62bfbefb, 0x62c242ec, 0x62cfcdfc, 0x67bc4b67, 0x67cb5c67, 0x68c685ca, 0x68c68ec3, 0x69b694ba, 0x69b69db3, 0x6abaea3b, 0x6abeab5e, 0x6acada3c, 0x6acdac4d, 0x6b4abeab, 0x6bdbed5e, 0x6bfbefb3, 0x6c5acdac, 0x6cecde4d, 0x6cfcdfc3, 0x6dfcdf4d, 0x6efbef5e, 0x6f4fecf4, 0x6f5fdbf5, 0x7174b41f, 0x7175c51f, 0x738f8cf8, 0x739f9bf9, 0x73b696b6, 0x73c686c6, 0x73d7976d, 0x73d97dc9, 0x73e7876e, 0x73e87eb8, 0x768e785e, 0x769d794d, 0x7898a72a, 0x78be785e, 0x79cd794d, 0x7a7b4baf, 0x7a7bc4ba, 0x7a7c5caf, 0x7a7cb5ca, 0x7bcba27a, 0x7bd47dbf, 0x7bd74dcb, 0x7ce57ecf, 0x7ce75ebc, 0x7d4a7cad, 0x7e5a7bae, 0x812ca781, 0x818db518, 0x8467c687, 0x8478be78, 0x84a7e787, 0x84d68c68, 0x84e78ce7, 0x84e78e76, 0x84f8cf8a, 0x8518e516, 0x85f5ad8f, 0x86aea24a, 0x86c6d863, 0x8712e781, 0x87b82bfe, 0x894d2482, 0x89cd89c3, 0x89dad82a, 0x8a7aca34, 0x8a7e7873, 0x8ad8fa2a, 0x8ade58de, 0x8b28bcdb, 0x8b28dbed, 0x8b2c978b, 0x8b2ce8bc, 0x8b8cb5ca, 0x8b8cb5ec, 0x8b8cbec3, 0x8c68c6a3, 0x8cf85cfa, 0x8cf85ecf, 0x8cf8cf2a, 0x8cfe38cf, 0x8d86ed5e, 0x8db8ed5e, 0x8e312c81, 0x8e78ce73, 0x8f5efb8f, 0x8f8a35f8, 0x8f8aef83, 0x8f8cf8a3, 0x8f8ef863, 0x8fce72ce, 0x912ba791, 0x919ec419, 0x9419d416, 0x94f4ae9f, 0x9567b697, 0x9579cd79, 0x95a7d797, 0x95d79bd7, 0x95d79d76, 0x95e69b69, 0x95f9bf9a, 0x96ada25a, 0x96b6e963, 0x9712d791, 0x97c92cfd, 0x985e2592, 0x98be98b3, 0x98eae92a, 0x9a7aba35, 0x9a7d7973, 0x9ae9fa2a, 0x9aed49ed, 0x9b69b6a3, 0x9bf94bfa, 0x9bf94dbf, 0x9bf9bf2a, 0x9bfd39bf, 0x9c29cbec, 0x9c29ecde, 0x9c2bd9cb, 0x9c9bc4ba, 0x9c9bc4db, 0x9c9bcdb3, 0x9d312b91, 0x9d79bd73, 0x9e96de4d, 0x9ec9de4d, 0x9f4dfc9f, 0x9f9a34f9, 0x9f9adf93, 0x9f9bf9a3, 0x9f9df963, 0x9fbd72bd, 0xa27a2ded, 0xa2de8da2, 0xa2ed9ea2, 0xa348e34e, 0xa359d35d, 0xa7b2a52b, 0xa7bae2ab, 0xa7baea3b, 0xa7c2a42c, 0xa7cad2ac, 0xa7cada3c, 0xa7d4797d, 0xa7dfd5fd, 0xa7e5787e, 0xa7efe4fe, 0xabeab5e1, 0xabeab9e3, 0xacdac4d1, 0xacdac8d3, 0xaf8f5ef8, 0xaf9f4df9, 0xb2562b76, 0xb258b2db, 0xb2db7df5, 0xb41abeab, 0xb6b4d96b, 0xb84abeab, 0xb8a2eab2, 0xb8fbefb3, 0xb96b596a, 0xbd7bde4d, 0xbd7e5bde, 0xbd7ec2bd, 0xbdbed5e1, 0xbdbed95e, 0xbdbed9e3, 0xbeabea31, 0xbef51bef, 0xbefb9ef3, 0xbefbef73, 0xbfbefb31, 0xbfe527e5, 0xc2462c76, 0xc249c2ec, 0xc2ec7ef4, 0xc51acdac, 0xc6c5e86c, 0xc86c486a, 0xc95acdac, 0xc9a2dac2, 0xc9fcdfc3, 0xcdacda31, 0xcdf41cdf, 0xcdfc8df3, 0xcdfcdf73, 0xce7ced5e, 0xce7d4ced, 0xcecde4d1, 0xcecde84d, 0xcecde8d3, 0xcfcdfc31, 0xcfd427d4, 0xd35b8d3d, 0xd425e7d4, 0xd427d4f9, 0xd79a7d2a, 0xd79bd74d, 0xdad84cad, 0xdbf51fdf, 0xdcad9ca3, 0xdf597259, 0xe34c9e3e, 0xe527e5f8, 0xe78a7e2a, 0xe78ce75e, 0xeae95bae, 0xebae8ba3, 0xecf41fef, 0xef487248, 0x124914e912, 0x125815d812, 0x128f8ef812, 0x129f9df912, 0x141361c614, 0x141712e714, 0x141e714ce7, 0x1461c614ec, 0x151361b615, 0x151712d715, 0x151d715bd7, 0x1561b615db, 0x1714f4cf41, 0x1715f5bf51, 0x1b676be76b, 0x1c676cd76c, 0x2142a2ea24, 0x2152a2da25, 0x21b21912db, 0x21c21812ec, 0x2328fe38f8, 0x2329fd39f9, 0x234e3429e3, 0x235d3528d3, 0x242a2ea284, 0x242cd427d4, 0x252a2da295, 0x252be527e5, 0x2628f8ef86, 0x2629f9df96, 0x26b96b2e96, 0x26c86c2d86, 0x281832e318, 0x28b278be78, 0x28bfe2b8fb, 0x291932d319, 0x29c279cd79, 0x29cfd2c9fc, 0x2ab212912b, 0x2ac212812c, 0x2b258b278b, 0x2c249c279c, 0x2d427d497d, 0x2d4f924df4, 0x2dad6296ad, 0x2e527e587e, 0x2e5f825ef5, 0x2eae6286ae, 0x2f4d724d24, 0x2f5e725e25, 0x2fb872b82b, 0x2fc972c92c, 0x31813e31b8, 0x31913d31c9, 0x34b7e34e37, 0x34f4cf4373, 0x35c7d35d37, 0x35f5bf5373, 0x381218c218, 0x391219b219, 0x3d319a313d, 0x3d3237c23d, 0x3d3c23d9c2, 0x3e318a313e, 0x3e3237b23e, 0x3e3b23e8b2, 0x41467c6174, 0x41471e7164, 0x416cd41614, 0x419c1d419c, 0x424d4257d4, 0x42624962a4, 0x4262962432, 0x4262962d42, 0x42842784f2, 0x42c7842784, 0x4327397343, 0x43a31ca343, 0x43a348ca34, 0x43ca349ca3, 0x4528478424, 0x462ae42a24, 0x47397343c9, 0x473ac7a434, 0x4787f84cf8, 0x4846c686ec, 0x48498e98b8, 0x49fbefb49f, 0x4a37937434, 0x4cf97f9c4f, 0x4cfdfc7d4f, 0x4d4548c548, 0x4f47acf47a, 0x4f842ef482, 0x4f97bf94fb, 0x51567b6175, 0x51571d7165, 0x516be51615, 0x518b1e518b, 0x525e5247e5, 0x52625862a5, 0x5262862532, 0x5262862e52, 0x52952795f2, 0x52b7952795, 0x5327387353, 0x53a31ba353, 0x53a359ba35, 0x53ba358ba3, 0x5429579525, 0x562ad52a25, 0x57387353b8, 0x573ab7a535, 0x5797f95bf9, 0x58fcdfc58f, 0x5956b696db, 0x59589d89c9, 0x5a37837535, 0x5bf87f8b5f, 0x5bfefb7e5f, 0x5e5459b459, 0x5f57abf57a, 0x5f87cf85fc, 0x5f952df592, 0x674fc674f4, 0x675fb675f5, 0x678c685c67, 0x679b694b67, 0x6861a6ea68, 0x6862562768, 0x68a6ea5e68, 0x6961a6da69, 0x6962462769, 0x69a6da4d69, 0x7185187c51, 0x7194197b41, 0x73d767c67d, 0x73e767b67e, 0x7687357378, 0x7697347379, 0x76d76c674d, 0x76e76b675e, 0x7842784e78, 0x7952795d79, 0x7adcad75ca, 0x7aebae74ba, 0x7bd72bd52b, 0x7bdf57dbfd, 0x7ce72ce42c, 0x7cef47ecfe, 0x7d79bd72bd, 0x7e78ce72ce, 0x7fdb27db7d, 0x7fec27ec7e, 0x81316e3181, 0x81721c2181, 0x81e318ce31, 0x8468a6ea68, 0x847aca78a7, 0x8784284798, 0x87a78ca738, 0x87a7ca7817, 0x897b82b878, 0x8b8aeaba5e, 0x8b8cb5cbdb, 0x8efc2fce8f, 0x8fc2dfc8fd, 0x91316d3191, 0x91721b2191, 0x91d319bd31, 0x9569a6da69, 0x957aba79a7, 0x9795295789, 0x97a79ba739, 0x97a7ba7917, 0x987c92c979, 0x9c9adaca4d, 0x9c9bc4bcec, 0x9dfb2fbd9f, 0x9fb2efb9fe, 0xa28fea28f8, 0xa29fda29f9, 0xa2beab9ea2, 0xa2cdac8da2, 0xaba356a3ab, 0xaba79a72ab, 0xaca346a3ac, 0xaca78a72ac, 0xb232be321b, 0xb232e32b62, 0xb2b87b82cb, 0xb616a516b6, 0xb6276e76b6, 0xbc2db7db2b, 0xbd5359bd35, 0xbdbed9ed4d, 0xbf4efb7ef4, 0xc232cd321c, 0xc232d32c62, 0xc2c97c92bc, 0xc616a416c6, 0xc6276d76c6, 0xcb2ec7ec2c, 0xce4348ce34, 0xcecde8de5e, 0xcf5dfc7df5, 0xd717517da7, 0xd7db2db7ed, 0xda6a396ada, 0xda72a52ada, 0xde74d24d7d, 0xdf528f5df8, 0xe717417ea7, 0xe7ec2ec7de, 0xea6a386aea, 0xea72a42aea, 0xed75e25e7e, 0xef429f4ef9, 0x14161a6ea614, 0x141714be7141, 0x1417a71ca714, 0x14b914be914b, 0x15161a6da615, 0x151715cd7151, 0x1517a71ba715, 0x15c815cd815c, 0x1812cd812181, 0x1912be912191, 0x2181a2aea218, 0x2191a2ada219, 0x232b2e32b9e3, 0x232c2d32c8d3, 0x246249624e96, 0x24d429ed49ed, 0x256258625d86, 0x25e528de58de, 0x28b298be98be, 0x29c289cd89cd, 0x31d31c613dc6, 0x31e31b613eb6, 0x34379b437343, 0x343e93eb43e9, 0x35378c537353, 0x353d83dc53d8, 0x3d326239623d, 0x3e326238623e, 0x436a96a3a439, 0x437367c67343, 0x45c8457845c8, 0x47ecb4ecb7ec, 0x4842984e9842, 0x49cb49cb79c7, 0x4a24ea249ea2, 0x4b46b496be96, 0x4d454c54d7d4, 0x536a86a3a538, 0x537367b67353, 0x54b9547954b9, 0x57dbc5dbc7db, 0x58bc58bc78b7, 0x5952895d8952, 0x5a25da258da2, 0x5c56c586cd86, 0x5e545b45e7e5, 0x6b67e4b676b6, 0x6c67d5c676c6, 0x78a78ca785ca, 0x79a79ba794ba, 0x813a31ca3181, 0x8ced8ced2ce2, 0x8d8ad8cad5ca, 0x913a31ba3191, 0x9bde9bde2bd2, 0x9e9ae9bae4ba, }; map[222] = { 0x1af, 0x1232f, 0x1454a, 0x1676f, 0x1898a, 0x1abcb, 0x1aded, 0x1bcdb, 0x1bdbf, 0x1cbec, 0x1cecf, 0x1dbed, 0x1ecde, 0x2362f, 0x3273f, 0x4584a, 0x5495a, 0x6276f, 0x7367f, 0x8498a, 0x9589a, 0xa262f, 0xa373f, 0xa484f, 0xa595f, 0x121712f, 0x1232898, 0x1232ded, 0x1234542, 0x1245d42, 0x124d42f, 0x1254e52, 0x125e52f, 0x12bcb32, 0x131613f, 0x1345b43, 0x134b43f, 0x1354c53, 0x135c53f, 0x141914a, 0x1423c24, 0x142c24a, 0x1432e34, 0x143e34a, 0x1454676, 0x1454cec, 0x14bdb54, 0x151815a, 0x1523b25, 0x152b25a, 0x1532d35, 0x153d35a, 0x1676ded, 0x1678986, 0x1689d86, 0x168d86f, 0x1698e96, 0x169e96f, 0x16bcb76, 0x1789b87, 0x178b87f, 0x1798c97, 0x179c97f, 0x1867c68, 0x186c68a, 0x1876e78, 0x187e78a, 0x1898cec, 0x18bdb98, 0x1967b69, 0x196b69a, 0x1976d79, 0x197d79a, 0x1abaeab, 0x1acadac, 0x1b252db, 0x1b434cb, 0x1b696db, 0x1b878cb, 0x1befbef, 0x1c242ec, 0x1c535bc, 0x1c686ec, 0x1c979bc, 0x1cdfcdf, 0x1d353bd, 0x1d424ed, 0x1d797bd, 0x1d868ed, 0x1e343ce, 0x1e525de, 0x1e787ce, 0x1e969de, 0x2324584, 0x2325495, 0x232848f, 0x2328498, 0x2329589, 0x232959f, 0x234196b, 0x2345462, 0x235186c, 0x2362bcb, 0x2389862, 0x238b28f, 0x238b298, 0x239c289, 0x239c29f, 0x23b8cb2, 0x23c9bc2, 0x23ded62, 0x245462a, 0x245d462, 0x24d4f62, 0x24dfc95, 0x254e562, 0x25e5f62, 0x25efb84, 0x262a898, 0x262bcdb, 0x262cbec, 0x262dbdf, 0x262dbed, 0x262deda, 0x262ecde, 0x262ecef, 0x26bae34, 0x26cad35, 0x26d42ed, 0x26e52de, 0x27a27af, 0x28b2a8f, 0x28b2a98, 0x29c2a89, 0x29c2a9f, 0x2b8f5ec, 0x2bc8b2a, 0x2bcb62a, 0x2c9f4db, 0x2cb9c2a, 0x324197d, 0x3245473, 0x325187e, 0x3273ded, 0x3289873, 0x328d38f, 0x328d398, 0x329e389, 0x329e39f, 0x32bcb73, 0x32d8ed3, 0x32e9de3, 0x345473a, 0x345b473, 0x34b4f73, 0x34bfe95, 0x354c573, 0x35c5f73, 0x35cfd84, 0x36a36af, 0x373a898, 0x373bcba, 0x373bdbf, 0x373bdcb, 0x373cebc, 0x373cecf, 0x373dbed, 0x373ecde, 0x37b43cb, 0x37c53bc, 0x37dac24, 0x37eab25, 0x38d3a8f, 0x38d3a98, 0x39e3a89, 0x39e3a9f, 0x3d8f5ce, 0x3de8d3a, 0x3ded73a, 0x3e9f4bd, 0x3ed9e3a, 0x423c284, 0x42c2a84, 0x432e384, 0x43e3a84, 0x452178b, 0x453168d, 0x4546276, 0x4547367, 0x4567684, 0x456b46a, 0x456b476, 0x457d467, 0x457d47a, 0x4584bdb, 0x45b6db4, 0x45cec84, 0x45d7bd4, 0x467684f, 0x46b4f6a, 0x46b4f76, 0x47d4f67, 0x47d4f7a, 0x484abcb, 0x484aded, 0x484bcdb, 0x484cbec, 0x484cecf, 0x484dbed, 0x484edce, 0x48c24ec, 0x48e34ce, 0x49f49fa, 0x4b6a3ed, 0x4bd6b4f, 0x4bdb84f, 0x4d7a2cb, 0x4db7d4f, 0x523b295, 0x52b2a95, 0x532d395, 0x53d3a95, 0x542179c, 0x543169e, 0x5467695, 0x546c56a, 0x546c576, 0x547e567, 0x547e57a, 0x5495cec, 0x54bdb95, 0x54c6ec5, 0x54e7ce5, 0x567695f, 0x56c5f6a, 0x56c5f76, 0x57e5f67, 0x57e5f7a, 0x58f58fa, 0x595abcb, 0x595aded, 0x595bcdb, 0x595bdbf, 0x595cbec, 0x595debd, 0x595ecde, 0x59b25db, 0x59d35bd, 0x5c6a3de, 0x5ce6c5f, 0x5cec95f, 0x5e7a2bc, 0x5ec7e5f, 0x6276898, 0x6276bcb, 0x6289d86, 0x628d86f, 0x6298e96, 0x629e96f, 0x62bae78, 0x62cad79, 0x62d86ed, 0x62ded76, 0x62e96de, 0x6768498, 0x6769589, 0x678152b, 0x679142c, 0x67b4cb6, 0x67c5bc6, 0x68dfc59, 0x69efb48, 0x6b4f9ec, 0x6bc4b6a, 0x6c5f8db, 0x6cb5c6a, 0x7367898, 0x7367ded, 0x7389b87, 0x738b87f, 0x7398c97, 0x739c97f, 0x73b87cb, 0x73bcb67, 0x73c97bc, 0x73dac68, 0x73eab69, 0x768153d, 0x769143e, 0x76d4ed7, 0x76e5de7, 0x78bfe59, 0x79cfd48, 0x7d4f9ce, 0x7de4d7a, 0x7e5f8bd, 0x7ed5e7a, 0x8467c68, 0x846c68a, 0x8476e78, 0x847e78a, 0x8498bdb, 0x84c68ec, 0x84cec98, 0x84e78ce, 0x896134b, 0x897124d, 0x89b2db8, 0x89d3bd8, 0x8b2a7ed, 0x8bd2b8f, 0x8d3a6cb, 0x8db3d8f, 0x9567b69, 0x956b69a, 0x9576d79, 0x957d79a, 0x9589cec, 0x95b69db, 0x95bdb89, 0x95d79bd, 0x986135c, 0x987125e, 0x98c2ec9, 0x98e3ce9, 0x9c2a7de, 0x9ce2c9f, 0x9e3a6bc, 0x9ec3e9f, 0xab2562b, 0xab6296b, 0xac2462c, 0xac6286c, 0xad3573d, 0xad7397d, 0xae3473e, 0xae7387e, 0xb2562db, 0xb4384cb, 0xb4834bf, 0xb6296db, 0xb8478bf, 0xb8478cb, 0xc2462ec, 0xc5395bc, 0xc5935cf, 0xc6286ec, 0xc9579bc, 0xc9579cf, 0xd3573bd, 0xd4284ed, 0xd4824df, 0xd7397bd, 0xd8468df, 0xd8468ed, 0xe3473ce, 0xe5295de, 0xe5925ef, 0xe7387ce, 0xe9569de, 0xe9569ef, 0x12189d812, 0x12198e912, 0x121d812ed, 0x121d8df12, 0x121ded712, 0x121e912de, 0x121e9ef12, 0x123249149, 0x123258158, 0x124191d42, 0x1242c2d42, 0x124efe4f2, 0x125181e52, 0x1252b2e52, 0x125dfd5f2, 0x128157128, 0x128712e78, 0x129147129, 0x129712d79, 0x12bcb7127, 0x13189b813, 0x13198c913, 0x131b813cb, 0x131b8bf13, 0x131bcb613, 0x131c913bc, 0x131c9cf13, 0x134191b43, 0x1343e3b43, 0x134cfc4f3, 0x135181c53, 0x1353d3c53, 0x135bfb5f3, 0x138156138, 0x138613c68, 0x139146139, 0x139613b69, 0x13ded6136, 0x14167c614, 0x14176e714, 0x141c614ec, 0x141c6ca14, 0x141cec914, 0x141e714ce, 0x141e7ea14, 0x142171c24, 0x142a2ea24, 0x143161e34, 0x143a3ca34, 0x145427127, 0x145436136, 0x146914e96, 0x147914c97, 0x14bdb9149, 0x15167b615, 0x15176d715, 0x151b615db, 0x151b6ba15, 0x151bdb815, 0x151d715bd, 0x151d7da15, 0x152171b25, 0x152a2da25, 0x153161d35, 0x153a3ba35, 0x156815d86, 0x157815b87, 0x15cec8158, 0x16145d416, 0x16154e516, 0x161d416ed, 0x161d4df16, 0x161e516de, 0x161e5ef16, 0x167641914, 0x167651815, 0x1686c6d86, 0x168efe8f6, 0x1696b6e96, 0x169dfd9f6, 0x17145b417, 0x17154c517, 0x171b417cb, 0x171b4bf17, 0x171c517bc, 0x171c5cf17, 0x1787e7b87, 0x178cfc8f7, 0x1797d7c97, 0x179bfb9f7, 0x18123c218, 0x18132e318, 0x181c218ec, 0x181c2ca18, 0x181e318ce, 0x181e3ea18, 0x186a6ea68, 0x187a7ca78, 0x189821712, 0x189831613, 0x19123b219, 0x19132d319, 0x191b219db, 0x191b2ba19, 0x191d319bd, 0x191d3da19, 0x196a6da69, 0x197a7ba79, 0x232b2562b, 0x232b6296b, 0x232c2462c, 0x232c6286c, 0x232d3573d, 0x232d7397d, 0x232e3473e, 0x232e7387e, 0x232f49f49, 0x232f58f58, 0x234c249c2, 0x235b258b2, 0x238fc28f8, 0x239fb29f9, 0x23d62535d, 0x23d76c23d, 0x23e62434e, 0x23e76b23e, 0x24237c243, 0x242c26d42, 0x242cd4284, 0x243796243, 0x24547a27a, 0x2459d4259, 0x248795248, 0x24c249c2a, 0x24d542484, 0x24dc249c2, 0x24f4ef462, 0x25237b253, 0x252b26e52, 0x252be5295, 0x253786253, 0x2548e5248, 0x25b258b2a, 0x25e452595, 0x25eb258b2, 0x25f5df562, 0x26286c768, 0x262876e78, 0x26296b769, 0x262976d79, 0x262abaeab, 0x262acadac, 0x262fbefbe, 0x262fcdfcd, 0x27a27a898, 0x27a27abcb, 0x27a27aded, 0x28b28bcdb, 0x28b28dbed, 0x28b2ce8bc, 0x28fc2a8f8, 0x29c29cbec, 0x29c29ecde, 0x29c2bd9cb, 0x29fb2a9f9, 0x2a28da28f, 0x2a28da298, 0x2a29ea289, 0x2a29ea29f, 0x2a7b2a52b, 0x2a7bae2ab, 0x2a7c2a42c, 0x2a7cad2ac, 0x2ade8da2a, 0x2aed9ea2a, 0x2b2562b76, 0x2b258b2db, 0x2b8ab2eab, 0x2bd7ec2bd, 0x2c2462c76, 0x2c249c2ec, 0x2c9ac2dac, 0x2d42d8498, 0x2d7a297da, 0x2e52e9589, 0x2e7a287ea, 0x324e349e3, 0x325d358d3, 0x328fe38f8, 0x329fd39f9, 0x343e37b43, 0x343eb4384, 0x34546a36a, 0x3459b4359, 0x348695348, 0x34b543484, 0x34be349e3, 0x34e349e3a, 0x34f4cf473, 0x353d37c53, 0x353dc5395, 0x3548c5348, 0x35c453595, 0x35cd358d3, 0x35d358d3a, 0x35f5bf573, 0x36a36a898, 0x36a36abcb, 0x36a36aded, 0x373867c68, 0x37387e678, 0x373967b69, 0x37397d679, 0x373abeabe, 0x373acdacd, 0x373fbfefb, 0x373fcfdfc, 0x38d38bdcb, 0x38d38debd, 0x38d3ec8de, 0x38fe3a8f8, 0x39e39cebc, 0x39e39edce, 0x39e3db9ed, 0x39fd3a9f9, 0x3a38ba38f, 0x3a38ba398, 0x3a39ca389, 0x3a39ca39f, 0x3a6d3a53d, 0x3a6dac3ad, 0x3a6e3a43e, 0x3a6eab3ae, 0x3abc8ba3a, 0x3acb9ca3a, 0x3b43b8498, 0x3b6a396ba, 0x3c53c9589, 0x3c6a386ca, 0x3d3573d67, 0x3d358d3bd, 0x3d8ad3cad, 0x3db6ce3db, 0x3e3473e67, 0x3e349e3ce, 0x3e9ae3bae, 0x42a2ea284, 0x42cd427d4, 0x42d4257d4, 0x42d427d4f, 0x43a3ca384, 0x43b4356b4, 0x43b436b4f, 0x43eb436b4, 0x454b8478b, 0x454c9579c, 0x454d8468d, 0x454e9569e, 0x456ad46a6, 0x457ab47a7, 0x45c98d45c, 0x45e98b45e, 0x46ad4f6a6, 0x46b46bdcb, 0x46b46cbec, 0x46b4de6bd, 0x47ab4f7a7, 0x47d47dbed, 0x47d47edce, 0x47d4bc7db, 0x48468d986, 0x484698e96, 0x48478b987, 0x484798c97, 0x484abaeab, 0x484acadac, 0x484fbfefb, 0x484fcdfcd, 0x49f46769f, 0x49f49cecf, 0x49f49fbdb, 0x4a6cfc64f, 0x4a7efe74f, 0x4b436b4cb, 0x4b6fb4efb, 0x4bc9ed4bc, 0x4c9f479cf, 0x4cfd9f4cf, 0x4d427d4ed, 0x4d7fd4cfd, 0x4e9f469ef, 0x4efb9f4ef, 0x4f46cf476, 0x4f47ef467, 0x4f9b4f34b, 0x4f9d4f24d, 0x4fce6cf4f, 0x4fec7ef4f, 0x52a2da295, 0x52be527e5, 0x52e5247e5, 0x52e527e5f, 0x53a3ba395, 0x53c5346c5, 0x53c536c5f, 0x53dc536c5, 0x546ae56a6, 0x547ac57a7, 0x56ae5f6a6, 0x56c56bcdb, 0x56c56cebc, 0x56c5ed6ce, 0x57ac5f7a7, 0x57e57debd, 0x57e57ecde, 0x57e5cb7ec, 0x58f56768f, 0x58f58bdbf, 0x58f58fcec, 0x595689d86, 0x59569e896, 0x595789b87, 0x59579c897, 0x595abaeab, 0x595acadac, 0x595fbefbe, 0x595fcfdfc, 0x5a6bfb65f, 0x5a7dfd75f, 0x5b8f578bf, 0x5bfe8f5bf, 0x5c536c5bc, 0x5c6fc5dfc, 0x5cb8de5cb, 0x5d8f568df, 0x5dfc8f5df, 0x5e527e5de, 0x5e7fe5bfe, 0x5f56bf576, 0x5f57df567, 0x5f8c5f35c, 0x5f8e5f25e, 0x5fbd6bf5f, 0x5fdb7df5f, 0x6286c6d86, 0x628f8ef86, 0x6296b6e96, 0x629f9df96, 0x678c685c6, 0x679b694b6, 0x686cd8648, 0x68c685c6a, 0x68dc685c6, 0x696be9659, 0x69b694b6a, 0x69eb694b6, 0x6ade4da6a, 0x6aed5ea6a, 0x6b46bd96b, 0x6b4ab6eab, 0x6c56ce86c, 0x6c5ac6dac, 0x7387e7b87, 0x738f8cf87, 0x7397d7c97, 0x739f9bf97, 0x768e785e7, 0x769d794d7, 0x787eb8748, 0x78be785e7, 0x78e785e7a, 0x797dc9759, 0x79cd794d7, 0x79d794d7a, 0x7abc4ba7a, 0x7acb5ca7a, 0x7d47db97d, 0x7d4ad7cad, 0x7e57ec87e, 0x7e5ae7bae, 0x846a6ea68, 0x847a7ca78, 0x86cd863d8, 0x86d863d8f, 0x86d8693d8, 0x87b872b8f, 0x87b8792b8, 0x87eb872b8, 0x8b28bc78b, 0x8b2fb8efb, 0x8d38de68d, 0x8d3fd8cfd, 0x8fce2cf8f, 0x8fec3ef8f, 0x956a6da69, 0x957a7ba79, 0x96be963e9, 0x96e963e9f, 0x96e9683e9, 0x97c972c9f, 0x97c9782c9, 0x97dc972c9, 0x9c29cb79c, 0x9c2fc9dfc, 0x9e39ed69e, 0x9e3fe9bfe, 0x9fbd2bf9f, 0x9fdb3df9f, 0xaba3573ab, 0xaba7397ab, 0xaca3473ac, 0xaca7387ac, 0xada2562ad, 0xada6296ad, 0xaea2462ae, 0xaea6286ae, 0xb258b278b, 0xb436b496b, 0xbf5935fbf, 0xbf9579fbf, 0xc249c279c, 0xc536c586c, 0xcf4834fcf, 0xcf8478fcf, 0xd358d368d, 0xd427d497d, 0xdf5925fdf, 0xdf9569fdf, 0xe349e369e, 0xe527e587e, 0xef4824fef, 0xef8468fef, 0x1214914e912, 0x1215815d812, 0x1218ef812ef, 0x1219df912df, 0x1314914c913, 0x1315815b813, 0x1318cf813cf, 0x1319bf913bf, 0x1412712e714, 0x1413613c614, 0x1416a6ea614, 0x1417a7ca714, 0x1512712d715, 0x1513613b615, 0x1516a6da615, 0x1517a7ba715, 0x1614d914916, 0x1614ef416ef, 0x1615df516df, 0x1615e815816, 0x1714b914917, 0x1714cf417cf, 0x1715bf517bf, 0x1715c815817, 0x1812a2ea218, 0x1812c712718, 0x1813a3ca318, 0x1813e613618, 0x1912a2da219, 0x1912b712719, 0x1913a3ba319, 0x1913d613619, 0x1b2b32be32b, 0x1b4b54be54b, 0x1b6b76be76b, 0x1b8b98be98b, 0x1c2c32cd32c, 0x1c5c45cd45c, 0x1c6c76cd76c, 0x1c9c89cd89c, 0x23426249624, 0x23526258625, 0x23b23e38b2b, 0x23c23d39c2c, 0x24262962d42, 0x242842784f2, 0x24284784254, 0x242c7842784, 0x25262862e52, 0x252952795f2, 0x25295795245, 0x252b7952795, 0x26b232be32b, 0x26c232cd32c, 0x27842784e78, 0x27952795d79, 0x27db27db97d, 0x27ec27ec87e, 0x2a28fea28f8, 0x2a29fda29f9, 0x2abeab9ea2a, 0x2acdac8da2a, 0x2b257db27db, 0x2b2db27dbf2, 0x2b2db7db2cb, 0x2c247ec27ec, 0x2c2ec27ecf2, 0x2c2ec7ec2bc, 0x32437349734, 0x32537358735, 0x32d32c28d3d, 0x32e32b29e3e, 0x34373973b43, 0x343843684f3, 0x34384684354, 0x343e6843684, 0x35373873c53, 0x353953695f3, 0x35395695345, 0x353d6953695, 0x36843684c68, 0x36953695b69, 0x36bd36bd96b, 0x36ce36ce86c, 0x37d323dc23d, 0x37e323eb23e, 0x3a38fca38f8, 0x3a39fba39f9, 0x3adcad9ca3a, 0x3aebae8ba3a, 0x3d356bd36bd, 0x3d3bd36bdf3, 0x3d3bd6bd3ed, 0x3e346ce36ce, 0x3e3ce36cef3, 0x3e3ce6ce3de, 0x424624962a4, 0x434734973a4, 0x45b45e56b4b, 0x45d45c57d4d, 0x46249624e96, 0x47349734c97, 0x48b454be54b, 0x48d454dc54d, 0x49cb49cb79c, 0x49ed49ed69e, 0x4a6aef4efa6, 0x4a7acf4cfa7, 0x4abc94bc4b4, 0x4ade94de4d4, 0x4b439cb49cb, 0x4b4cb9cb4db, 0x4d429ed49ed, 0x4d4ed9ed4bd, 0x4fbefb7ef4f, 0x4fdcfd6cf4f, 0x525625862a5, 0x535735873a5, 0x54c54d46c5c, 0x54e54b47e5e, 0x56258625d86, 0x57358735b87, 0x58bc58bc78b, 0x58de58de68d, 0x59c545cd45c, 0x59e545eb45e, 0x5a6adf5dfa6, 0x5a7abf5bfa7, 0x5acb85cb5c5, 0x5aed85ed5e5, 0x5c538bc58bc, 0x5c5bc8bc5ec, 0x5e528de58de, 0x5e5de8de5ce, 0x5fcdfc7df5f, 0x5febfe6bf5f, 0x62b676be76b, 0x62c676cd76c, 0x67862562868, 0x67962462969, 0x67b67e74b6b, 0x67c67d75c6c, 0x68648348698, 0x69659359689, 0x6abeab5ea6a, 0x6acdac4da6a, 0x6b6db3db6cb, 0x6c6ec3ec6bc, 0x73d767dc67d, 0x73e767eb67e, 0x76873573878, 0x76973473979, 0x76d76c64d7d, 0x76e76b65e7e, 0x78748248798, 0x79759259789, 0x7adcad5ca7a, 0x7aebae4ba7a, 0x7d7bd2bd7ed, 0x7e7ce2ce7de, 0x84b898be98b, 0x84d898dc98d, 0x89b89e92b8b, 0x89d89c93d8d, 0x8b8cb5cb8db, 0x8d8ed5ed8bd, 0x8fbefb3ef8f, 0x8fdcfd2cf8f, 0x95c989cd89c, 0x95e989eb89e, 0x98c98d82c9c, 0x98e98b83e9e, 0x9c9bc4bc9ec, 0x9e9de4de9ce, 0x9fcdfc3df9f, 0x9febfe2bf9f, 0xaba27a297ab, 0xaba356a36ab, 0xaca27a287ac, 0xaca346a36ac, 0xada257a27ad, 0xada36a396ad, 0xaea247a27ae, 0xaea36a386ae, 0xbf49f479fbf, 0xbf85f835fbf, 0xcf58f578fcf, 0xcf94f934fcf, 0xdf49f469fdf, 0xdf85f825fdf, 0xef58f568fef, 0xef94f924fef, }; // clang-format on return map; } } // namespace tsa_internal } // namespace tket
tket/libs/tktokenswap/src/TableLookup/SwapSequenceTable.cpp/0
{ "file_path": "tket/libs/tktokenswap/src/TableLookup/SwapSequenceTable.cpp", "repo_id": "tket", "token_count": 66728 }
348
// 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 "SwapSequenceReductionTester.hpp" #include <catch2/catch_test_macros.hpp> #include <tktokenswap/SwapListSegmentOptimiser.hpp> #include <tktokenswap/VertexMapResizing.hpp> #include <tktokenswap/VertexMappingFunctions.hpp> #include <tktokenswap/VertexSwapResult.hpp> #include "NeighboursFromEdges.hpp" using std::vector; namespace tket { namespace tsa_internal { namespace tests { static void reduce_sequence( const vector<Swap>& swaps, const VertexMapping& vertex_mapping, NeighboursFromEdges& neighbours, SwapList& raw_swap_list, SwapListOptimiser& general_optimiser, const SwapSequenceReductionTester::Options& options) { REQUIRE(!swaps.empty()); VertexMapResizing map_resizing(neighbours); SwapListTableOptimiser table_optimiser; SwapListSegmentOptimiser& segment_optimiser = table_optimiser.get_segment_optimiser(); raw_swap_list.clear(); for (const auto& swap : swaps) { raw_swap_list.push_back(swap); } std::set<std::size_t> vertices_with_tokens; for (const auto& entry : vertex_mapping) { vertices_with_tokens.insert(entry.first); } if (options.optimise_initial_segment_only) { general_optimiser.optimise_pass_with_frontward_travel(raw_swap_list); if (!raw_swap_list.empty()) { table_optimiser.get_segment_optimiser().optimise_segment( raw_swap_list.front_id().value(), vertices_with_tokens, map_resizing, raw_swap_list); } return; } table_optimiser.optimise( vertices_with_tokens, map_resizing, raw_swap_list, general_optimiser); } static void check_solution( VertexMapping problem_vertex_mapping, const SwapList& raw_swap_list) { // Every vertex swap on a source->target mapping converts it to a new // source->target map, i.e. map[v] = (token currently at v). // So we BEGIN with every token equalling its target, // thus at the end every token must equal its vertex. for (auto id_opt = raw_swap_list.front_id(); id_opt;) { const auto id = id_opt.value(); id_opt = raw_swap_list.next(id); const auto& swap = raw_swap_list.at(id); const VertexSwapResult vswap_result(swap, problem_vertex_mapping); } REQUIRE(all_tokens_home(problem_vertex_mapping)); } static std::size_t get_reduced_swaps_size_with_checks( const vector<Swap>& swaps, const VertexMapping& problem_vertex_mapping, NeighboursFromEdges& neighbours_calculator, SwapListOptimiser& general_optimiser, const SwapSequenceReductionTester::Options& options) { SwapList raw_swap_list; reduce_sequence( swaps, problem_vertex_mapping, neighbours_calculator, raw_swap_list, general_optimiser, options); check_solution(problem_vertex_mapping, raw_swap_list); REQUIRE(raw_swap_list.size() <= swaps.size()); return raw_swap_list.size(); } std::size_t SwapSequenceReductionTester::get_checked_solution_size( const DecodedProblemData& problem_data, const SwapSequenceReductionTester::Options& options) { NeighboursFromEdges neighbours_calculator(problem_data.swaps); return get_reduced_swaps_size_with_checks( problem_data.swaps, problem_data.vertex_mapping, neighbours_calculator, m_general_optimiser, options); } // Reduces the sequence of swaps, checks it, and returns the size. std::size_t SwapSequenceReductionTester::get_checked_solution_size( const DecodedProblemData& problem_data, const DecodedArchitectureData& architecture_data, const SwapSequenceReductionTester::Options& options) { NeighboursFromEdges neighbours_calculator(architecture_data.edges); return get_reduced_swaps_size_with_checks( problem_data.swaps, problem_data.vertex_mapping, neighbours_calculator, m_general_optimiser, options); } SequenceReductionStats::SequenceReductionStats() : problems(0), reduced_problems(0), total_original_swaps(0), total_original_swaps_for_reduced_problems(0), total_reduced_swaps(0) {} void SequenceReductionStats::add_solution( std::size_t original_swaps, std::size_t reduced_swaps) { REQUIRE(reduced_swaps <= original_swaps); ++problems; if (reduced_swaps < original_swaps) { ++reduced_problems; total_original_swaps_for_reduced_problems += original_swaps; } total_reduced_swaps += reduced_swaps; total_original_swaps += original_swaps; } std::string SequenceReductionStats::str() const { std::stringstream ss; const std::size_t swaps_for_equal_probs = total_original_swaps - total_original_swaps_for_reduced_problems; const std::size_t reduced_swaps_for_reduced_probs = total_reduced_swaps - swaps_for_equal_probs; const std::size_t overall_decrease = total_original_swaps - total_reduced_swaps; ss << "[" << problems - reduced_problems << " equal probs (" << swaps_for_equal_probs << "); " << reduced_problems << " reduced probs (" << reduced_swaps_for_reduced_probs << " vs " << total_original_swaps_for_reduced_problems << ")]\n[Overall reduction " << total_reduced_swaps << " vs " << total_original_swaps << ": "; if (total_original_swaps == 0) { ss << "0%"; } else { ss << (100 * overall_decrease) / total_original_swaps << "%"; } ss << "]"; return ss.str(); } } // namespace tests } // namespace tsa_internal } // namespace tket
tket/libs/tktokenswap/test/src/TableLookup/SwapSequenceReductionTester.cpp/0
{ "file_path": "tket/libs/tktokenswap/test/src/TableLookup/SwapSequenceReductionTester.cpp", "repo_id": "tket", "token_count": 2148 }
349
// 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. #pragma once #include <algorithm> #include <limits> #include <map> #include <optional> #include <sstream> #include <stdexcept> #include <string> #include <utility> #include <vector> #include "SpecialExceptions.hpp" namespace tket { namespace WeightedSubgraphMonomorphism { // GCOVR_EXCL_START // A bug in test coverage? The following functions DEFINITELY are // used many times, but not according to test coverage... /** Sets the numeric variable to its maximum possible value. * This helps avoid mixing types accidentally, e.g. writing * x = std::numeric_limits<long>::max() where x is actually an int. * @param val the numeric variable, to be set to max() */ template <class T> void set_maximum(T& val) { val = std::numeric_limits<T>::max(); } /** Simply check if the variable does have its maximum possible value. * @param val the numeric variable * @return True if it equals its maximum possible value */ template <class T> bool is_maximum(const T& val) { return val == std::numeric_limits<T>::max(); } // GCOVR_EXCL_STOP /** Handy for testing; a string represention of a std container. * @param elems A container of elements. * @param max_elems_to_print The maximum number to print, before terminating * early. * @return a string representation of the elements. */ template <class Container> std::string str(const Container& elems, std::size_t max_elems_to_print = 10) { std::stringstream ss; if (elems.size() > 3) { ss << elems.size() << " elems: "; } ss << "[ "; std::size_t number_printed = 0; for (const auto& elem : elems) { ss << elem << " "; ++number_printed; if (number_printed == elems.size()) { break; } if (number_printed >= max_elems_to_print) { ss << "..."; break; } } ss << "]"; return ss.str(); } // GCOVR_EXCL_START // A bug in test coverage? /** Handy for testing. * @param elems An ordinary std::vector of comparable elements. * @return True if they are in increasing order, with all values distinct. */ template <class T> bool is_sorted_and_unique(const std::vector<T>& elems) { return std::is_sorted(elems.cbegin(), elems.cend()) && (std::adjacent_find(elems.cbegin(), elems.cend()) == elems.cend()); } // GCOVR_EXCL_STOP /** Checks if the map has this key. * @param map A std::map * @param key A key to check * @return The value in the map corresponding to the key if it exists, or null * optional object if the key does not exist. */ template <class Key, class Value> std::optional<Value> get_optional_value( const std::map<Key, Value>& map, const Key& key) { const auto citer = map.find(key); if (citer == map.cend()) { return {}; } return citer->second; } // GCOVR_EXCL_START // There MUST be a bug in test coverage, surely? // Below, "get_sum_or_throw" definitely calls "get_checked_sum" in all cases. // Yet the SAME coverage report (for the same file!) // reported the first as covered (including the actual lines calling // the second), // but the second as uncovered (every line!) /** For an unsigned integer type, returns x+y if the value is correct, * or null if overflow would occur (so the actual value of x+y does not fit in * the type). * @param x First number * @param y Second number * @return x+y, if the value fits in the unsigned integer type; otherwise null. */ template <typename UINT> std::optional<UINT> get_checked_sum(UINT x, UINT y) { if (x == 0) { return y; } if (y == 0) { return x; } const UINT sum = x + y; // x,y >= 1, and if n = x add y (the C add operation) // then n = x+y (mod M) (as ordinary integers), // with M being the max possible value. // If overflow didn't occur, then n=x+y is the correct value, // and so n > x (of course!) // // If overflow occurs, then // M <= x+y <= 2M (as ordinary integers). // So, if x+y = 2M then x=y=M, and then // n = 0 < x. // Otherwise, x+y < 2M, so that 0 <= x+y-M < M, // and thus n = x+y-M = x - (M-y) (as ordinary integers). // Clearly, now n <= x (and also n <= y). if (sum <= x) { return {}; } return sum; } /** For an unsigned integer type, returns x*y * if the value is small enough to fit inside a UINT. * Otherwise, returns null. * @param x First number * @param y Second number * @return x*y, if the value fits in the unsigned integer type; otherwise null. */ template <typename UINT> std::optional<UINT> get_checked_product(UINT x, UINT y) { switch (x) { case 0: return 0; case 1: return y; default: break; } switch (y) { case 0: return 0; case 1: return x; default: break; } if (y > std::numeric_limits<UINT>::max() / x) { // By definition of unsigned integer type division for x > 0, // M div x = n // (where div means the C++ integer division operation) // if and only if n <= M/x < n+1 (as real numbers). // Therefore nx <= M, (n+1)x > M (as real numbers), // so yx <= M (as real numbers) <==> y <= n. // // (OK, int division can be a lot slower than multiplication. // But I think it's unavoidable; we cannot just inspect // x MULT y directly, as for addition. // E.g., if x ~ sqrt(M), y = 1.5x, x even, then // xy = 1.5x^2 ~ 1.5 M will be converted to ~0.5 M, // which is far bigger than both x and y). return {}; } return x * y; } // GCOVR_EXCL_STOP /** Throws the special IntegerOverflow exception if the values are too big. * @param x First number * @param y Second number * @return x+y, if the value fits in the unsigned integer type; otherwise throws * an IntegerOverflow exception. */ template <typename UINT> UINT get_sum_or_throw(UINT x, UINT y) { const auto sum_opt = get_checked_sum(x, y); if (sum_opt) { return sum_opt.value(); } std::stringstream ss; ss << "(" << x << " + " << y << ")"; throw IntegerOverflow(ss.str()); } /** Throws the special IntegerOverflow exception if the values are too big. * @param x First number * @param y Second number * @return x*y, if the value fits in the unsigned integer type; otherwise throws * an IntegerOverflow exception. */ template <typename UINT> UINT get_product_or_throw(UINT x, UINT y) { const auto product_opt = get_checked_product(x, y); if (product_opt) { return product_opt.value(); } std::stringstream ss; ss << "(" << x << " * " << y << ")"; throw IntegerOverflow(ss.str()); } } // namespace WeightedSubgraphMonomorphism } // namespace tket
tket/libs/tkwsm/include/tkwsm/Common/GeneralUtils.hpp/0
{ "file_path": "tket/libs/tkwsm/include/tkwsm/Common/GeneralUtils.hpp", "repo_id": "tket", "token_count": 2464 }
350
// 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. #pragma once #include <algorithm> #include <boost/dynamic_bitset.hpp> #include <cstdint> #include <map> #include <set> #include <string> #include <vector> namespace tket { namespace WeightedSubgraphMonomorphism { typedef std::uint_fast32_t VertexWSM; typedef std::uint64_t WeightWSM; /** (v1,v2) with v1<v2. */ typedef std::pair<VertexWSM, VertexWSM> EdgeWSM; /** KEY: Edge (v1,v2) with v1<v2, * VALUE: the weight >= 0 of the edge v1-v2. */ typedef std::map<EdgeWSM, WeightWSM> GraphEdgeWeights; /** KEY: pattern vertex * VALUE: all possible target vertices it could map to. */ typedef std::map<VertexWSM, std::set<VertexWSM>> PossibleAssignments; /** A string representation of a graph with edge weights. */ std::string str(const GraphEdgeWeights& gdata); /** Simply return the maximum weight occurring in the data. */ WeightWSM get_max_weight(const GraphEdgeWeights& graph_data); /** Do a detailed check, including overflow checks, * that the assignments PV->TV are valid, and return the scalar product. */ WeightWSM get_checked_scalar_product( const GraphEdgeWeights& pdata, const GraphEdgeWeights& tdata, const std::vector<std::pair<VertexWSM, VertexWSM>>& solution); /** A string representation of a list of edges. */ std::string str(const std::vector<EdgeWSM>&); /** Ensures consistency. Checks that v1 != v2. * @param v1 First vertex. * @param v2 Second vertex. * @return An edge (a,b), with a<b always. */ EdgeWSM get_edge(VertexWSM v1, VertexWSM v2); struct GetVerticesOptions { // Do we allow (v1,v2) to have v1 >= v2? bool allow_edge_vertices_not_in_order = false; // Do we allow edges (v,v)? bool allow_loops = false; // Do we allow both (v1,v2) AND (v2,v1) to occur // (as long as they have the same weight)? bool allow_duplicate_edges = false; bool allow_zero_weights = true; }; /** Get the nonisolated vertices (i.e., vertices appearing in the edges). * @param edges_and_weights The graph (with edge weights, which are ignored). * @param options More details of what to allow or forbid in the data. * @return A list of all nonisolated vertices (i.e., vertices appearing in the * edges), unique and sorted. */ std::vector<VertexWSM> get_vertices( const GraphEdgeWeights& edges_and_weights, const GetVerticesOptions& options = {}); /** No checks on the edges and weights; simply counts how many distinct vertices * occur in the edges. */ unsigned get_number_of_vertices(const GraphEdgeWeights& edges_and_weights); /** For use in reducing a search node, or individual Domain(pv). */ enum class ReductionResult { SUCCESS, /** At least one new assignment PV->TV was created; * a special case needing different treatment to "SUCCESS". */ NEW_ASSIGNMENTS, /** The node is impossible; some domain has become empty. */ NOGOOD }; /** KEY: pattern vertex * VALUE: target vertex */ typedef std::map<VertexWSM, VertexWSM> Assignments; /** A string representation of some assignments. */ std::string str(const Assignments&); /** Mainly used for checking if a bitset, representing a domain, * has 0, 1 or more bits set to true; this is a bit faster than count(). */ struct BitsetInformation { bool empty; /** This will be nonnull if and only if the bitset has EXACTLY one bit set, * and then will contain the value. */ std::optional<VertexWSM> single_element; explicit BitsetInformation(const boost::dynamic_bitset<>& domain); }; } // namespace WeightedSubgraphMonomorphism } // namespace tket
tket/libs/tkwsm/include/tkwsm/GraphTheoretic/GeneralStructs.hpp/0
{ "file_path": "tket/libs/tkwsm/include/tkwsm/GraphTheoretic/GeneralStructs.hpp", "repo_id": "tket", "token_count": 1302 }
351
// 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. #pragma once #include <boost/dynamic_bitset.hpp> #include <optional> #include <string> #include "../GraphTheoretic/GeneralStructs.hpp" namespace tket { namespace WeightedSubgraphMonomorphism { struct NodesRawData; class NodesRawDataWrapper; /** This is passed to Reducer, Checker, Updater objects, * to obtain information about the domains in the current node only, * and alter them. */ class DomainsAccessor { public: /** The wrapped NodesRawData object will be directly altered. */ explicit DomainsAccessor(NodesRawDataWrapper& raw_data_wrapper); unsigned get_number_of_pattern_vertices() const; /** Every unassigned p-vertex (i.e., with size Domain(pv) > 1) in the * current node is included in here. * However, this may also include some assigned vertices. * @return A vector which definitely includes all pattern vertices which are * unassigned, in the current node. However, it may include other * pattern vertices. */ const std::vector<VertexWSM>& get_unassigned_pattern_vertices_superset() const; bool current_node_is_valid() const; /** This may be a reference to the SAME object returned by * get_unassigned_pattern_vertices_superset(), or it may be different. * The caller is free to overwrite it at the END (after processing). * A vector::swap is most efficient, of course. * @return A vector which can be directly overwritten at the END, in order to * fill out all the unassigned vertices in the current node. */ std::vector<VertexWSM>& get_unassigned_pattern_vertices_superset_to_overwrite(); /** Return Domain(pv) in the current node, i.e. the set of all target * vertices which pv could be mapped to, as we extend the current mapping. * @param pv A vertex in the pattern graph. * @return The domain of pv in the current search node. */ const boost::dynamic_bitset<>& get_domain(VertexWSM pv) const; /** The number of TV currently in Domain(PV). */ std::size_t get_domain_size(VertexWSM pv) const; /** Returns true if Domain(pv) is different in the current search node * and the previous node. */ bool domain_created_in_current_node(VertexWSM pv) const; /** The newly made assignments, just in the current node. * Note that this list might be cleared after they have been processed; * thus it need not be the complete list of ALL assignments which occurred * in this node. */ const std::vector<std::pair<VertexWSM, VertexWSM>>& get_new_assignments() const; /** Once a domain is fully reduced and all assignments processed, clear the * data; there is no use for it any more. */ void clear_new_assignments(); /** Returns the scalar product sum_e w(e).w(f(e)) over all p-edges e * in the which have actually been assigned, i.e. for which * both end vertices are assigned in the current node (although of course * they may have been assigned first in previous nodes). */ WeightWSM get_scalar_product() const; /** Simply overwrite the scalar product in the current node with * the new value; the caller is assumed to know how to calculate it * correctly (which requires, of course, carefully considering the new * assignments in the current node, and adding the values appropriately). * @param scalar_product The new scalar product value; simply overwrites the * existing one. * @return This object, for chaining. */ DomainsAccessor& set_scalar_product(WeightWSM scalar_product); /** Returns the sum of all pattern edge weights for those edges * which have been assigned so far (i.e., both end vertices * have been assigned). * @return The sum of weights of all assigned pattern edges. */ WeightWSM get_total_p_edge_weights() const; /** Simply overwrite the total sum of pattern edge weights in the current * node with the new value. The caller is responsible for doing this * calculation correctly. * @param value The new value; simply overwrites the existing one. * @return This object, for chaining. */ DomainsAccessor& set_total_p_edge_weights(WeightWSM value); /** Assuming that the caller has already processed the given number * of new assignments in this current node (without clearing the * new assignments list - which stores them in order of creation), * go through ALL remaining assignments and process them, by applying * alldiff propagation. (I.e., if PV->y, then y must be erased from EVERY * other domain in this node). * The caller must keep track of how many new_assignments are processed. * @param n_assignments_already_processed The number of assignments in the * current new assignments list which were previously processed by this * function in the current node. The caller must keep track of this * information. After returning, EITHER all will have been processed, OR a * nogood is found. * @return False if some domain becomes empty (so, we are at a nogood: an * invalid node, meaning that we must backtrack in the search. We return early * as soon as this occurs, since there's no point in continuing with an * invalid node). */ bool alldiff_reduce_current_node(std::size_t n_assignments_already_processed); struct IntersectionResult { ReductionResult reduction_result; // Only bother filling this in if it's NOT a nogood or new assignment. std::size_t new_domain_size; bool changed; }; /** Simply intersect Domain(PV) with the specified set of TV, represented * by a bitset. For speed, uses the "swap" function (similar to vector::swap * and set::swap - time O(1), no copies) - which thus alters domain_mask. * We should have an intersect function WITHOUT doing this - * the operator -= function should work. * We check for and update new assignments if necessary. * @param pattern_v The pattern vertex. * @param domain_mask A set of target vertices to intersect with the domain; * will be altered. * @return The result of changing the domain. */ IntersectionResult intersect_domain_with_swap( VertexWSM pattern_v, boost::dynamic_bitset<>& domain_mask); private: NodesRawData& m_raw_data; }; } // namespace WeightedSubgraphMonomorphism } // namespace tket
tket/libs/tkwsm/include/tkwsm/Searching/DomainsAccessor.hpp/0
{ "file_path": "tket/libs/tkwsm/include/tkwsm/Searching/DomainsAccessor.hpp", "repo_id": "tket", "token_count": 2003 }
352
// 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 "tkwsm/GraphTheoretic/DerivedGraphs.hpp" #include "tkwsm/GraphTheoretic/DerivedGraphsCalculator.hpp" namespace tket { namespace WeightedSubgraphMonomorphism { DerivedGraphs::DerivedGraphs( const NeighboursData& ndata, DerivedGraphsCalculator& calculator) : m_neighbours_data(ndata), m_calculator(calculator) {} DerivedGraphs::VertexData DerivedGraphs::get_data(VertexWSM v) { auto iter = m_data_for_vertices.find(v); if (iter != m_data_for_vertices.end()) { return iter->second; } auto& entry = m_data_for_vertices[v]; fill(v, entry); return entry; } static void fill_with_sorted_counts( DerivedGraphStructs::SortedCounts& counts, const DerivedGraphStructs::NeighboursAndCounts& neighbours_and_counts) { counts.reserve(neighbours_and_counts.size()); for (const auto& entry : neighbours_and_counts) { counts.push_back(entry.second); } std::sort(counts.begin(), counts.end()); } template <class T> static typename std::forward_list<T>::iterator get_new_iter( std::forward_list<T>& storage) { storage.emplace_front(); return storage.begin(); } void DerivedGraphs::fill(VertexWSM v, VertexData& vertex_data) { vertex_data.d2_neighbours = get_new_iter(m_storage); vertex_data.d3_neighbours = get_new_iter(m_storage); m_calculator.fill( m_neighbours_data, v, vertex_data.triangle_count, *vertex_data.d2_neighbours, *vertex_data.d3_neighbours); vertex_data.d2_sorted_counts_iter = get_new_iter(m_counts_storage); vertex_data.d3_sorted_counts_iter = get_new_iter(m_counts_storage); fill_with_sorted_counts( *vertex_data.d2_sorted_counts_iter, *vertex_data.d2_neighbours); fill_with_sorted_counts( *vertex_data.d3_sorted_counts_iter, *vertex_data.d3_neighbours); } } // namespace WeightedSubgraphMonomorphism } // namespace tket
tket/libs/tkwsm/src/GraphTheoretic/DerivedGraphs.cpp/0
{ "file_path": "tket/libs/tkwsm/src/GraphTheoretic/DerivedGraphs.cpp", "repo_id": "tket", "token_count": 899 }
353
// 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. #pragma once #include <string> #include "PlacementCostModelInterface.hpp" namespace tket { namespace WeightedSubgraphMonomorphism { namespace InitialPlacement { namespace tests { /** Just for testing; we want a reaonsably large graph where * sensible token swapping is easy to work out. * (And because it's a TREE, shortest paths are unique). * * Thus this gives a reasonable simplified model for the cost of applying * a sequence of gates, once we've got an initial qubit placement. * * However, this is only for very quick sanity tests; a full benchmark * should be carried out with many different graphs, * token swapping strategies, etc. (Even GIVEN an initial placement, * and GIVEN a sequence of gates to apply, there may be many * possible reorderings from parallel gates; * so there are probably many possible solutions, even for trees. * It is presumably impossible to find an OPTIMUM solution * in less than exponential time in general. Need to research this!) * * Represents, implicitly, a binary tree. The vertices are labelled * {1,2,3,...}. Let 1 be the root vertex, at level 0. * As we descend down, vertex v has left child 2v, right child 2v+1. * Thus, the trees look like: * * 1 * / \ * / \ * / \ * / \ * 2 3 * / \ / \ * 4 5 6 7 * / \ / \ / \ / \ * 8 9 10 11 12 13 14 15 * * ...etc. It's very easy to find the level of a vertex * from its binary representation. */ class WeightedBinaryTree : public PlacementCostModelInterface { public: /** * @param weights weights[i] is the edge weight from vertex i to its parent. * (Thus weights[0], weights[1] are "dummy" weights, as 0,1 have no parent). * @param number_of_primitive_gates_in_swap How many primitive 2-qubit gates * (with cost equal to the edge weight) does it take to make a single SWAP * gate, in our model? */ explicit WeightedBinaryTree( std::vector<WeightWSM> weights, unsigned number_of_primitive_gates_in_swap = 3); // Calculate the edges and weights in standard format. virtual GraphEdgeWeights get_graph_data() const override; // The vertices are 1,2,...,N. Returns N. // This is, of course, equal to the number of vertices. unsigned get_max_vertex_number() const; private: // Element[i] is the edge weight from vertex i to its parent // (with weight 0 for i=0,1, which are "dummy" values; vertices 0,1 have no // parent.) const std::vector<WeightWSM> m_weights; // For the path u -> v, e.g. [u, x, y, z, a, b, c, v], // it's convenient to build it up from both ends: // [u, x, y, ...] and [v, c, b, a, ...] until they meet in the middle. // This will be the tail, i.e. starting with the end vertex; // thus the order will later need to be reversed. // The weights will also be shifted; thus element[0], corresponding to v, // will be (v, weight(v--c)), rather than (v,0). This is more convenient // when reversing and concatenating to make the complete path. mutable Path m_path_work_vector; mutable Path m_tail_path_work_vector; // Choose a path between the VERTICES v1, v2, and fill m_path_work_vector. void fill_path(VertexWSM vertex1, VertexWSM vertex2) const; virtual const Path& get_path_to_use( VertexWSM vertex1, VertexWSM vertex2) const override; }; } // namespace tests } // namespace InitialPlacement } // namespace WeightedSubgraphMonomorphism } // namespace tket
tket/libs/tkwsm/test/src/InitPlacement/WeightedBinaryTree.hpp/0
{ "file_path": "tket/libs/tkwsm/test/src/InitPlacement/WeightedBinaryTree.hpp", "repo_id": "tket", "token_count": 1321 }
354
// 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 <catch2/catch_test_macros.hpp> #include <map> #include <random> #include <sstream> #include <string> #include <tkwsm/Common/GeneralUtils.hpp> #include <utility> #include "../TestUtils/CheckedSolution.hpp" #include "../TestUtils/ResumedSolutionChecker.hpp" #include "../TestUtils/TestSettings.hpp" namespace tket { namespace WeightedSubgraphMonomorphism { namespace { // Try to embed graphs from the first sequence // into graphs from the second sequence, // recording the result in a string (for easy copy/paste). struct EmbedGraphSequences { long long total_time_ms; // Simply use 0 for no embedding, 1 for an embedding, // * for timeout, and letters for errors. std::string result; EmbedGraphSequences( const std::vector<GraphEdgeWeights>& graph_sequence1, const std::vector<GraphEdgeWeights>& graph_sequence2, unsigned timeout_ms, const std::string& expected_result) : total_time_ms(0) { CheckedSolution::Statistics statistics( "unweighted problems; embedding graph sequences"); MainSolverParameters solver_params(timeout_ms); solver_params.terminate_with_first_full_solution = true; CheckedSolution::ProblemInformation info; std::stringstream ss; unsigned result_index = 0; ResumedSolutionChecker resumption_checker; for (unsigned index1 = 0; index1 < graph_sequence1.size(); ++index1) { const auto& pattern_graph = graph_sequence1[index1]; for (unsigned index2 = 0; index2 < graph_sequence2.size(); ++index2) { const auto& target_graph = graph_sequence2[index2]; const bool timeout_expected = result_index < expected_result.size() && expected_result.at(result_index) == '*'; if (result_index % 8 == 0) { TestSettings::get().os << "\n### RI=" << result_index << ": "; } ++result_index; if (timeout_expected) { // To save time, don't bother trying to solve // known hard problems. ss << "*"; continue; } const auto search_time_before = statistics.total_search_time_ms; const CheckedSolution checked_solution( pattern_graph, target_graph, info, solver_params, statistics); resumption_checker.check( checked_solution, pattern_graph, target_graph, solver_params); if (checked_solution.scalar_product == pattern_graph.size()) { ss << "1"; continue; } if (checked_solution.scalar_product == 0) { if (checked_solution.finished) { ss << "0"; } else { // Timed out. ss << "*"; } } else { // Error: wrong scalar product! ss << "X"; } } } result = ss.str(); if (!expected_result.empty()) { CHECK(expected_result.size() == result.size()); CHECK(result_index == result.size()); } total_time_ms = statistics.total_init_time_ms + statistics.total_search_time_ms; statistics.finish(); } }; } // namespace typedef std::mt19937_64 RNG_64; // Use 16 random bits as the sorting key, // to get approx uniform distribution of permutations. template <class T> static void reorder( RNG_64& rng, std::vector<std::pair<std::uint_fast16_t, T>>& data) { std::uint64_t bits = 0; for (auto& entry : data) { if (bits == 0) { bits = rng(); } entry.first = bits & 0xffff; bits >>= 16; } std::sort(data.begin(), data.end()); } // Add edges gradually to a graph, // to get a sequence of graphs each one of which embeds in the next, // but randomly relabelling the vertices to make it harder for // the solver. static std::vector<GraphEdgeWeights> get_increasing_graph_sequence( unsigned number_of_vertices, unsigned num_entries, RNG_64& rng) { std::vector<std::pair<std::uint_fast16_t, EdgeWSM>> edges_data; edges_data.reserve((number_of_vertices * (number_of_vertices - 1)) / 2); std::vector<std::pair<std::uint_fast16_t, unsigned>> new_labels( number_of_vertices); for (unsigned ii = 0; ii < number_of_vertices; ++ii) { new_labels[ii].second = ii; for (unsigned jj = ii + 1; jj < number_of_vertices; ++jj) { edges_data.emplace_back(); edges_data.back().second = get_edge(ii, jj); } } reorder(rng, edges_data); const unsigned num_edges_increment = edges_data.size() / (num_entries + 1); REQUIRE(num_edges_increment > 0); REQUIRE(num_edges_increment * num_entries < edges_data.size()); // Now create the increasing graphs. std::vector<GraphEdgeWeights> graph_data; for (unsigned multiplier = 1; multiplier <= num_entries; ++multiplier) { const unsigned num_edges = num_edges_increment * multiplier; reorder(rng, new_labels); // Now add the edges. graph_data.emplace_back(); for (unsigned ee = 0; ee < num_edges; ++ee) { const auto& edge = edges_data[ee].second; const auto new_edge = get_edge( new_labels[edge.first].second, new_labels[edge.second].second); // WeightWSM 1 for every edge. graph_data.back()[new_edge] = 1; } if (graph_data.size() >= num_entries) { break; } } return graph_data; } // A string like "111111110111..." records the results // of trying to embed graph P(i) into T(j). // The graphs come from increasing sequences, // so there should be a cutoff point dividing 0 and 1. static void check_monotonic_embedding_property( const std::string& str_result, unsigned n_target_graphs, bool same_sequence) { const unsigned n_pattern_graphs = str_result.size() / n_target_graphs; CHECK(n_pattern_graphs * n_target_graphs == str_result.size()); if (same_sequence) { CHECK(n_pattern_graphs == n_target_graphs); } unsigned index = 0; unsigned embed_count = 0; unsigned nonembed_count = 0; // The pattern graphs and target graphs are both increasing. // In each target graph block, it should START at 0 and switch over to 1. for (unsigned p_index = 0; p_index < n_pattern_graphs; ++p_index) { const auto previous_embed_count = embed_count; const auto previous_nonembed_count = nonembed_count; embed_count = 0; nonembed_count = 0; for (unsigned t_index = 0; t_index < n_target_graphs; ++t_index) { auto& symbol = str_result.at(index); ++index; if (symbol == '1') { ++embed_count; if (same_sequence) { // If it happens to be the same increasing sequence // in the source and target, clearly this must hold. CHECK(t_index >= p_index); } continue; } if (symbol == '0') { ++nonembed_count; CHECK(embed_count == 0); if (same_sequence) { CHECK(t_index < p_index); } continue; } } if (embed_count + nonembed_count == previous_embed_count + previous_nonembed_count && embed_count + nonembed_count == n_target_graphs) { // No timeouts. The number of embeddings must be DECREASING, // because the pattern graphs are getting bigger. CHECK(embed_count <= previous_embed_count); } } } static const std::vector<std::string>& get_expected_results_ref() { static const std::vector<std::string> expected_results{ "1111111101111111001111110001111100001111000001110000001100000001", "1111111111111111111111110111111100111111000111110001111100011111", "1111111111111111111111111111111101111111011111110011111100111111", "1111111111111111111111111111111111111111011111110011111100111111", "1111111111111111111111111111111111111111111111110111111101111111", "0000000100000000000000000000000000000000000000000000000000000000", "1111111101111111001111110001111100001111000001110000001100000001", "1111111101111111001111110000111100000111000000110000001100000001", "1111111101111111001111110001111100001111000011110000001100000011", "1111111111111111011111110011111100011111000111110000011100000011", "0000000000000000000000000000000000000000000000000000000000000000", "0011111100000000000000000000000000000000000000000000000000000000", "1111111101111111001111110001111100001111000001110000001100000001", "0111111100111111000111110000111100000111000000110000000100000001", "1111111101111111001111110001111100001111000001110000001100000001", "0000000000000000000000000000000000000000000000000000000000000000", "0000000000000000000000000000000000000000000000000000000000000000", "0011111100000000000000000000000000000000000000000000000000000000", "1111111101111111001111110001111100001111000001110000001100000001", "1111111100111111000011110000111100000111000000110000001100000001", "0000000000000000000000000000000000000000000000000000000000000000", "0000000000000000000000000000000000000000000000000000000000000000", "0000000000000000000000000000000000000000000000000000000000000000", "0000000000000000000000000000000000000000000000000000000000000000", "1111111101111111001111110001111100001111000001110000001100000001"}; return expected_results; } static std::vector<std::vector<GraphEdgeWeights>> get_list_of_increasing_graph_sequences() { std::vector<std::vector<GraphEdgeWeights>> list_of_increasing_graph_sequences; const unsigned num_entries = 8; unsigned number_of_vertices = 3; RNG_64 rng; for (int count = 0; count < 5; ++count) { number_of_vertices += 3; list_of_increasing_graph_sequences.emplace_back( get_increasing_graph_sequence(number_of_vertices, num_entries, rng)); } { // A crude check that the test data hasn't changed, // and is identical across platforms. CHECK(rng() == 0x3c5c9fe803f69af3); const auto& final_list = list_of_increasing_graph_sequences.back(); CHECK(final_list.size() == 8); const auto& final_graph = final_list.back(); CHECK(final_graph.size() == 136); // Check an edge in the middle... const auto& middle_graph = final_list[final_list.size() / 2]; CHECK(middle_graph.size() == 85); std::size_t counter = middle_graph.size() / 2; for (const auto& edge_weight_pair : middle_graph) { CHECK(edge_weight_pair.second == 1); if (counter != 0) { --counter; continue; } CHECK(edge_weight_pair.first.first == 5); CHECK(edge_weight_pair.first.second == 6); break; } } return list_of_increasing_graph_sequences; } static const std::vector<std::vector<GraphEdgeWeights>>& get_list_of_increasing_graph_sequences_ref() { static const auto list_of_increasing_graph_sequences = get_list_of_increasing_graph_sequences(); return list_of_increasing_graph_sequences; } static std::set<std::pair<unsigned, unsigned>> get_longer_ij_pair_tests() { return {{2, 3}, {2, 4}, {3, 3}, {3, 4}, {4, 4}}; } static void test(bool short_test) { const unsigned num_entries = 8; const unsigned timeout_ms = short_test ? 1000 : 10000; const auto& expected_results = get_expected_results_ref(); long long total_time_ms = 0; unsigned expected_str_index = 0; const auto& list_of_increasing_graph_sequences = get_list_of_increasing_graph_sequences_ref(); const std::string short_test_str = short_test ? "SHORT" : "LONG"; TestSettings::get().os << "\n\nRunning unweighted probs: " << short_test_str; const auto longer_test_pairs = get_longer_ij_pair_tests(); unsigned pair_count = 0; for (unsigned ii = 0; ii < list_of_increasing_graph_sequences.size(); ++ii) { for (unsigned jj = 0; jj < list_of_increasing_graph_sequences.size(); ++jj) { TestSettings::get().os << "\ni=" << ii << ", j=" << jj << " : "; const bool should_test = (longer_test_pairs.count(std::make_pair(ii, jj)) == 0) == short_test; if (!should_test) { TestSettings::get().os << "SKIPPED"; ++expected_str_index; continue; } const EmbedGraphSequences embedding_tester( list_of_increasing_graph_sequences[ii], list_of_increasing_graph_sequences[jj], timeout_ms, expected_results.at(expected_str_index)); CHECK(embedding_tester.result == expected_results.at(expected_str_index)); ++expected_str_index; ++pair_count; TestSettings::get().os << "\n@@@@@ (" << ii << "," << jj << ") took time " << embedding_tester.total_time_ms; total_time_ms += embedding_tester.total_time_ms; check_monotonic_embedding_property( embedding_tester.result, num_entries, ii == jj); } } CHECK(expected_str_index == expected_results.size()); TestSettings::get().os << "\n::::END: all unweighted probs for " << pair_count << " (i,j) pairs, " << short_test_str << " tests; " << total_time_ms << " ms.\n"; } SCENARIO("Increasing graph sequences: short tests") { test(true); } SCENARIO("Increasing graph sequences: long tests") { test(false); } } // namespace WeightedSubgraphMonomorphism } // namespace tket
tket/libs/tkwsm/test/src/SolvingProblems/test_UnweightedProblems.cpp/0
{ "file_path": "tket/libs/tkwsm/test/src/SolvingProblems/test_UnweightedProblems.cpp", "repo_id": "tket", "token_count": 5150 }
355
// 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 <array> #include <catch2/catch_test_macros.hpp> #include "SquareGridGeneration.hpp" namespace tket { namespace WeightedSubgraphMonomorphism { // Also test get_graph_edge_weights static WeightWSM get_total_weights(const SquareGrid& grid) { WeightWSM total = 0; for (auto ww : grid.horiz_weights) { REQUIRE(ww > 0); total += ww; } for (auto ww : grid.vert_weights) { REQUIRE(ww > 0); total += ww; } const auto gmap = grid.get_graph_edge_weights(); REQUIRE(gmap.size() == grid.horiz_weights.size() + grid.vert_weights.size()); WeightWSM other_total = 0; for (const auto& entry : gmap) { other_total += entry.second; } REQUIRE(total == other_total); return total; } SCENARIO("square grid rotate 4 times equals identity") { RNG rng; for (int ii = 0; ii < 5; ++ii) { SquareGrid grid; grid.width = 4; grid.height = 7; grid.fill_weights(rng); const auto original_copy = grid; const auto total_weight = get_total_weights(grid); for (int nn = 0; nn < 4; ++nn) { grid = grid.get_rotated_grid(); REQUIRE(total_weight == get_total_weights(grid)); } REQUIRE(grid.horiz_weights == original_copy.horiz_weights); REQUIRE(grid.vert_weights == original_copy.vert_weights); } } SCENARIO("square grid refl/rotate twice equals identity") { RNG rng; for (int ii = 0; ii < 5; ++ii) { SquareGrid grid; grid.width = 4; grid.height = 4; grid.fill_weights(rng); const auto original_copy = grid; const auto total_weight = get_total_weights(grid); for (int nn = 0; nn < 2; ++nn) { grid = grid.get_reflected_grid(); REQUIRE(total_weight == get_total_weights(grid)); grid = grid.get_rotated_grid(); REQUIRE(total_weight == get_total_weights(grid)); } REQUIRE(grid.horiz_weights == original_copy.horiz_weights); REQUIRE(grid.vert_weights == original_copy.vert_weights); } } // Width 3, height 2 vertical edge indices: // // +---+---+---+ // 1 3 5 7 // +---+---+---+ // 0 2 4 6 // +---+---+---+ // // Horizontal indices: // // +-6-+-7-+-8-+ // | | | | // +-3-+-4-+-5-+ // | | | | // +-0-+-1-+-2-+ SCENARIO("square grid reflection") { RNG rng; for (int ii = 0; ii < 5; ++ii) { SquareGrid grid; grid.width = 3; grid.height = 2; grid.fill_weights(rng); REQUIRE(grid.horiz_weights.size() == 9); REQUIRE(grid.vert_weights.size() == 8); const auto other_grid = grid.get_reflected_grid(); REQUIRE(other_grid.width == grid.width); REQUIRE(other_grid.height == grid.height); REQUIRE(other_grid.horiz_weights.size() == grid.horiz_weights.size()); REQUIRE(other_grid.vert_weights.size() == grid.vert_weights.size()); REQUIRE(get_total_weights(grid) == get_total_weights(other_grid)); // Which horiz edges are mapped into each other? const std::vector<std::pair<unsigned, unsigned>> horiz_equal_pairs{ {0, 2}, {1, 1}, {3, 5}, {4, 4}, {6, 8}, {7, 7}}; for (const auto& entry : horiz_equal_pairs) { REQUIRE( other_grid.horiz_weights.at(entry.first) == grid.horiz_weights.at(entry.second)); REQUIRE( other_grid.horiz_weights.at(entry.second) == grid.horiz_weights.at(entry.first)); } const std::vector<std::pair<unsigned, unsigned>> vert_equal_pairs{ {0, 6}, {2, 4}, {1, 7}, {3, 5}}; for (const auto& entry : vert_equal_pairs) { REQUIRE( other_grid.vert_weights.at(entry.first) == grid.vert_weights.at(entry.second)); REQUIRE( other_grid.vert_weights.at(entry.second) == grid.vert_weights.at(entry.first)); } } } // Width 2, height 4 vert/horiz indices: // // +8+9+ // 3 7 11 // +6+7+ // 2 6 10 // +4+5+ // 1 5 9 // +2+3+ // 0 4 8 // +0+1+ // // Width 4, height 2 indices: // // + 8 + 9 + 10+ 11+ // 1 3 5 7 9 // + 4 + 5 + 6 + 7 + // 0 2 4 6 8 // + 0 + 1 + 2 + 3 + // // ...and the original, rotated: // // + 11+ 10+ 9 + 8 + // 9 7 5 3 1 // + 7 + 6 + 5 + 4 + // 8 6 4 2 0 // + 3 + 2 + 1 + 0 + // SCENARIO("square grid rotation") { RNG rng; for (int ii = 0; ii < 5; ++ii) { SquareGrid grid; grid.width = 2; grid.height = 4; grid.fill_weights(rng); REQUIRE(grid.horiz_weights.size() == 10); REQUIRE(grid.vert_weights.size() == 12); const auto other_grid = grid.get_rotated_grid(); REQUIRE(other_grid.width == grid.height); REQUIRE(other_grid.height == grid.width); REQUIRE(other_grid.horiz_weights.size() == grid.vert_weights.size()); REQUIRE(other_grid.vert_weights.size() == grid.horiz_weights.size()); REQUIRE(get_total_weights(grid) == get_total_weights(other_grid)); // i: an original horiz edge index // Element[i]: the new vert edge index it becomes const std::vector<unsigned> horiz_to_vert_data{8, 9, 6, 7, 4, 5, 2, 3, 0, 1}; for (unsigned ii = 0; ii < horiz_to_vert_data.size(); ++ii) { REQUIRE( other_grid.vert_weights.at(horiz_to_vert_data[ii]) == grid.horiz_weights.at(ii)); } // element[i] is the new horiz edge index, for original vert edge index i const std::vector<unsigned> vert_to_horiz_data{3, 2, 1, 0, 7, 6, 5, 4, 11, 10, 9, 8}; for (unsigned ii = 0; ii < vert_to_horiz_data.size(); ++ii) { REQUIRE( other_grid.horiz_weights.at(vert_to_horiz_data[ii]) == grid.vert_weights.at(ii)); } } } // 1x1 square; next to reflected; rotated // // # b # # b # # B # // A B B A b a // # a # # a # # A # SCENARIO("square grid reflection, rotation on 1x1 square") { RNG rng; std::vector<unsigned> numbers; const auto add_numbers = [&numbers](const SquareGrid& gg) { numbers.push_back(gg.width); numbers.push_back(gg.height); numbers.push_back(gg.horiz_weights.size()); numbers.push_back(gg.vert_weights.size()); for (auto ww : gg.horiz_weights) { numbers.push_back(ww); } for (auto ww : gg.vert_weights) { numbers.push_back(ww); } numbers.push_back(0); }; for (int ii = 0; ii < 5; ++ii) { SquareGrid grid; grid.width = 1; grid.height = 1; grid.fill_weights(rng); add_numbers(grid); const auto reflected_grid = grid.get_reflected_grid(); add_numbers(reflected_grid); const auto rotated_grid = grid.get_rotated_grid(); add_numbers(rotated_grid); } REQUIRE( numbers == std::vector<unsigned>{ 1, 1, 2, 2, 8, 3, 7, 9, 0, 1, 1, 2, 2, 8, 3, 9, 7, 0, 1, 1, 2, 2, 7, 9, 3, 8, 0, 1, 1, 2, 2, 1, 4, 3, 1, 0, 1, 1, 2, 2, 1, 4, 1, 3, 0, 1, 1, 2, 2, 3, 1, 4, 1, 0, 1, 1, 2, 2, 5, 4, 3, 6, 0, 1, 1, 2, 2, 5, 4, 6, 3, 0, 1, 1, 2, 2, 3, 6, 4, 5, 0, 1, 1, 2, 2, 2, 5, 5, 8, 0, 1, 1, 2, 2, 2, 5, 8, 5, 0, 1, 1, 2, 2, 5, 8, 5, 2, 0, 1, 1, 2, 2, 5, 4, 7, 3, 0, 1, 1, 2, 2, 5, 4, 3, 7, 0, 1, 1, 2, 2, 7, 3, 4, 5, 0}); } SCENARIO("square grid: check gdata conversion") { RNG rng; SquareGrid grid; grid.width = 2; grid.height = 3; std::vector<WeightWSM> sorted_weights; std::vector<WeightWSM> sorted_weights_again; for (grid.width = 1; grid.width < 10; ++grid.width) { for (grid.height = 1; grid.height < 10; ++grid.height) { grid.fill_weights(rng); sorted_weights.clear(); for (auto ww : grid.horiz_weights) { sorted_weights.push_back(ww); } for (auto ww : grid.vert_weights) { sorted_weights.push_back(ww); } std::sort(sorted_weights.begin(), sorted_weights.end()); const auto gdata = grid.get_graph_edge_weights(); REQUIRE(gdata.size() == sorted_weights.size()); sorted_weights_again.clear(); for (const auto& entry : gdata) { sorted_weights_again.push_back(entry.second); } std::sort(sorted_weights_again.begin(), sorted_weights_again.end()); REQUIRE(sorted_weights == sorted_weights_again); } } } SCENARIO( "square grid subgraph_isomorphism_min_scalar_product picks out reversed " "cycles") { SquareGrid cycle; cycle.width = 1; cycle.height = 1; // "random" increasing weights. const std::array<unsigned, 4> cycle_weights{1, 3, 7, 20}; cycle.horiz_weights = {cycle_weights[0], cycle_weights[2]}; cycle.vert_weights = {cycle_weights[3], cycle_weights[1]}; // To get the minimum scalar product, the orders must be opposite. unsigned min_sc_prod = 0; for (unsigned ii = 0; ii < cycle_weights.size(); ++ii) { min_sc_prod += cycle_weights[ii] * cycle_weights[cycle_weights.size() - 1 - ii]; } SquareGrid big_grid; for (big_grid.width = 1; big_grid.width < 5; ++big_grid.width) { for (big_grid.height = 1; big_grid.height < 5; ++big_grid.height) { big_grid.resize_weight_vectors(); for (unsigned dx = 0; dx < big_grid.width; ++dx) { for (unsigned dy = 0; dy < big_grid.height; ++dy) { // Make a copy of 1,2,3,4 within the edges, // starting at point (dx,dy). unsigned value = 9999; for (auto& ww : big_grid.horiz_weights) { ww = value--; } for (auto& ww : big_grid.vert_weights) { ww = value--; } const unsigned horiz_start = dy * big_grid.width + dx; big_grid.horiz_weights[horiz_start] = cycle_weights[0]; big_grid.horiz_weights[horiz_start + big_grid.width] = cycle_weights[2]; const unsigned vert_start = dx * big_grid.height + dy; big_grid.vert_weights[vert_start] = cycle_weights[3]; big_grid.vert_weights[vert_start + big_grid.height] = cycle_weights[1]; const auto sc_prod = cycle.get_subgraph_isomorphism_min_scalar_product(big_grid); REQUIRE(sc_prod == min_sc_prod); } } } } } } // namespace WeightedSubgraphMonomorphism } // namespace tket
tket/libs/tkwsm/test/src/TestUtils/test_SquareGridGeneration.cpp/0
{ "file_path": "tket/libs/tkwsm/test/src/TestUtils/test_SquareGridGeneration.cpp", "repo_id": "tket", "token_count": 4846 }
356
self: super: { pybind11_json = super.stdenv.mkDerivation { name = "pybind11_json"; src = super.fetchFromGitHub { owner = "pybind"; repo = "pybind11_json"; rev = "0.2.14"; sha256 = "sha256-6L675DsfafzRv0mRR3b0eUFFjUpll3jCPoBAAffk7U0="; }; nativeBuildInputs = [ super.cmake ]; buildInputs = [ super.python3Packages.pybind11 super.nlohmann_json ]; }; qwasm = super.python3.pkgs.buildPythonPackage { name = "qwasm"; src = super.fetchFromGitHub { owner = "CQCL"; repo = "qwasm"; rev = "35ebe1e2551449d97b9948a600f8d2e4d7474df6"; sha256 = "sha256:g/QA5CpAR3exRDgVQMnXGIH8bEGtwGFBjjSblbdXRkU="; }; }; lark = super.python3.pkgs.buildPythonPackage { pname = "lark"; version = "1.1.9"; format = "pyproject"; src = super.fetchFromGitHub { owner = "lark-parser"; repo = "lark"; rev = "refs/tags/1.1.9"; hash = "sha256:pWLKjELy10VNumpBHjBYCO2TltKsZx1GhQcGMHsYJNk="; }; nativeBuildInputs = with super.python3Packages; [ setuptools ]; doCheck = false; }; sympy' = super.python3.pkgs.buildPythonPackage rec{ # version bump - nixpkgs' version is 1.12 at the time of writing pname = "sympy"; version = "1.13.0"; format = "setuptools"; src = super.python3Packages.fetchPypi { inherit pname version; sha256 = "sha256:O2r49NAIuaGmpCaLM1uYSyODXybR1gsFJuvHHUiiX1c="; }; nativeCheckInputs = [ super.glibcLocales ]; propagatedBuildInputs = [ super.python3Packages.mpmath ]; # tests take ~1h doCheck = false; pythonImportsCheck = [ "sympy" ]; preCheck = '' export LANG="en_US.UTF-8" ''; }; }
tket/nix-support/third-party-python-packages.nix/0
{ "file_path": "tket/nix-support/third-party-python-packages.nix", "repo_id": "tket", "token_count": 824 }
357
// 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. #pragma once #include <pybind11/pybind11.h> #include <vector> #include "tket/Circuit/Circuit.hpp" #include "typecast.hpp" namespace py = pybind11; namespace tket { template <typename ID> static Circuit *add_gate_method_sequence( Circuit *circ, const Op_ptr &op, const py::tket_custom::SequenceVec<ID> &args_seq, const py::kwargs &kwargs) { std::vector<ID> args = args_seq; return add_gate_method(circ, op, args, kwargs); } template <typename ID> static Circuit *add_gate_method( Circuit *circ, const Op_ptr &op, const std::vector<ID> &args, const py::kwargs &kwargs) { if (op->get_desc().is_meta()) { throw CircuitInvalidity("Cannot add metaop to a circuit."); } if (op->get_desc().is_barrier()) { throw CircuitInvalidity( "Please use `add_barrier` to add a " "barrier to a circuit."); } static const std::set<std::string> allowed_kwargs = { "opgroup", "condition", "condition_bits", "condition_value"}; for (const auto kwarg : kwargs) { const std::string kwargstr = py::cast<std::string>(kwarg.first); if (!allowed_kwargs.contains(kwargstr)) { std::stringstream msg; msg << "Unsupported keyword argument '" << kwargstr << "'"; throw CircuitInvalidity(msg.str()); } } std::optional<std::string> opgroup; if (kwargs.contains("opgroup")) { opgroup = py::cast<std::string>(kwargs["opgroup"]); } bool condition_given = kwargs.contains("condition"); bool condition_bits_given = kwargs.contains("condition_bits"); bool condition_value_given = kwargs.contains("condition_value"); if (condition_given && condition_bits_given) { throw CircuitInvalidity("Both `condition` and `condition_bits` specified"); } if (condition_value_given && !condition_bits_given) { throw CircuitInvalidity( "`condition_value` specified without `condition_bits`"); } if (condition_given) { py::module condition = py::module::import("pytket.circuit.add_condition"); py::object add_condition = condition.attr("_add_condition"); auto conditions = add_condition(circ, kwargs["condition"]).cast<std::pair<Bit, bool>>(); unit_vector_t new_args = {conditions.first}; unsigned n_new_args = new_args.size(); Op_ptr cond = std::make_shared<Conditional>(op, n_new_args, int(conditions.second)); op_signature_t sig = op->get_signature(); for (unsigned i = 0; i < args.size(); ++i) { switch (sig.at(i)) { case EdgeType::Quantum: { new_args.push_back(Qubit(args[i])); break; } case EdgeType::WASM: { new_args.push_back(WasmState(args[i])); break; } case EdgeType::Classical: case EdgeType::Boolean: { new_args.push_back(Bit(args[i])); break; } default: { TKET_ASSERT(!"add_gate_method found invalid edge type in signature"); } } } circ->add_op(cond, new_args, opgroup); } else if (condition_bits_given) { std::vector<ID> new_args = py::cast<std::vector<ID>>(kwargs["condition_bits"]); unsigned n_new_args = new_args.size(); unsigned value = condition_value_given ? py::cast<unsigned>(kwargs["condition_value"]) : (1u << n_new_args) - 1; Op_ptr cond = std::make_shared<Conditional>(op, n_new_args, value); new_args.insert(new_args.end(), args.begin(), args.end()); circ->add_op(cond, new_args, opgroup); } else circ->add_op(op, args, opgroup); return circ; } } // namespace tket
tket/pytket/binders/include/add_gate.hpp/0
{ "file_path": "tket/pytket/binders/include/add_gate.hpp", "repo_id": "tket", "token_count": 1632 }
358
// 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 <pybind11/eigen.h> #include <pybind11/pybind11.h> #include <pybind11/stl.h> #include <pybind11/stl_bind.h> #include "binder_utils.hpp" #include "tket/Characterisation/FrameRandomisation.hpp" #include "tket/Clifford/UnitaryTableau.hpp" #include "tket/Converters/Converters.hpp" namespace py = pybind11; namespace tket { SpCxPauliTensor apply_clifford_basis_change_tensor( const SpCxPauliTensor &in_pauli, const Circuit &circ) { SpPauliStabiliser in_string(in_pauli.string); UnitaryRevTableau tab = circuit_to_unitary_rev_tableau(circ); SpCxPauliTensor new_operator = tab.get_row_product(in_string); new_operator.coeff *= in_pauli.coeff; return new_operator; } SpPauliString apply_clifford_basis_change_string( const SpPauliString &in_pauli, const Circuit &circ) { UnitaryRevTableau tab = circuit_to_unitary_rev_tableau(circ); SpPauliStabiliser new_operator = tab.get_row_product(SpPauliStabiliser(in_pauli)); return SpPauliString(new_operator.string); } PYBIND11_MODULE(tailoring, m) { m.doc() = "The tailoring module provides access to noise tailoring tools."; py::class_<FrameRandomisation>( m, "FrameRandomisation", "The base FrameRandomisation class. FrameRandomisation finds " "subcircuits (cycles) of a given circuit comprised of gates with " "OpType only from a specified set of OpType, and wires gates into " "the boundary (frame) of these cycles. Input frame gates are " "sampled from another set of OpType, and output frame gates " "deduced such that the circuit unitary doesn't change, achieved by " "computing the action of cycle gates on frame gates.") .def( py::init([](const OpTypeSet &_cycle_types, const OpTypeSet &_frame_types, const std::map<OpType, std::map<py::tuple, py::tuple>> &cycle_frame_actions) { std::map<OpType, std::map<OpTypeVector, OpTypeVector>> real_cycle_frame_actions; for (const auto &actions : cycle_frame_actions) { std::map<OpTypeVector, OpTypeVector> otv_map; for (const auto &tups : actions.second) { otv_map[tups.first.cast<OpTypeVector>()] = tups.second.cast<OpTypeVector>(); } real_cycle_frame_actions[actions.first] = otv_map; } return FrameRandomisation( _cycle_types, _frame_types, real_cycle_frame_actions); }), "Constructor for FrameRandomisation." "\n\n:param cycletypes: " "A set of OpType corresponding to the gates cycles found are " "comprised of" "\n:param frametypes: A set of OpType " "corresponding to the gates Frames are sampled from" "\n:param conjugates: A map from cycle OpType, to a map " "between Frame OptypeVector giving the required change to " "output frame OpType to preserve Unitary from given input " "frame OpType.") .def( "get_all_circuits", &FrameRandomisation::get_all_circuits, "For given circuit, finds all Cycles, finds all frames for " "each Cycle, and returns every combination of frame and cycle " "in a vector of Circuit.\n\n:param circuit: The circuit to " "find frames for.\n" ":return: list of " CLSOBJS(Circuit), py::arg("circuit")) .def( "sample_circuits", &FrameRandomisation::sample_randomisation_circuits, "Returns a number of instances equal to sample of frame " "randomisation for the given circuit. Samples individual " "frame gates uniformly.\n\n:param " "circuit: The circuit to perform frame randomisation with " "Pauli gates on\n:param samples: the number of frame " "randomised circuits to return.\n" ":return: list of " CLSOBJS(Circuit), py::arg("circuit"), py::arg("samples")) .def("__repr__", &FrameRandomisation::to_string); py::class_<PauliFrameRandomisation>( m, "PauliFrameRandomisation", "The PauliFrameRandomisation class. PauliFrameRandomisation finds " "subcircuits (cycles) of a given circuit comprised of gates with " "OpType::H, OpType::CX and OpType::S, and wires gates " "into " "the boundary (frame) of these cycles. Input frame gates are " "sampled from another set of OpType comprised of the Pauli gates, " "and output frame gates " "deduced such that the circuit unitary doesn't change, achieved by " "computing the action of cycle gates on frame gates.") .def(py::init<>(), "Constructor for PauliFrameRandomisation.") .def( "get_all_circuits", &PauliFrameRandomisation::get_all_circuits, "For given circuit, finds all Cycles, finds all frames for " "each Cycle, and returns every combination of frame and cycle " "in a vector of Circuit.\n\n:param circuit: The circuit to " "find frames for.\n" ":return: list of " CLSOBJS(Circuit), py::arg("circuit")) .def( "sample_circuits", &PauliFrameRandomisation::sample_randomisation_circuits, "Returns a number of instances equal to sample of frame " "randomisation for the given circuit. Samples individual " "frame gates uniformly from the Pauli gates.\n\n:param " "circuit: The circuit to perform frame randomisation with " "Pauli gates on\n:param samples: the number of frame " "randomised circuits to return.\n" ":return: list of " CLSOBJS(Circuit), py::arg("circuit"), py::arg("samples")) .def("__repr__", &PauliFrameRandomisation::to_string); py::class_<UniversalFrameRandomisation>( m, "UniversalFrameRandomisation", "The UniversalFrameRandomisation class. " "UniversalFrameRandomisation finds " "subcircuits (cycles) of a given circuit comprised of gates with " "OpType::H, OpType::CX, and OpType::Rz, and wires gates " "into " "the boundary (frame) of these cycles. Input frame gates are " "sampled from another set of OpType comprised of the Pauli gates, " "and output frame gates " "deduced such that the circuit unitary doesn't change, achieved by " "computing the action of cycle gates on frame gates. Some gates " "with OpType::Rz may be substituted for their dagger to achieve " "this.") .def(py::init<>(), "Constructor for UniversalFrameRandomisation.") .def( "get_all_circuits", &UniversalFrameRandomisation::get_all_circuits, "For given circuit, finds all Cycles, finds all frames for " "each Cycle, and returns every combination of frame and cycle " "in a vector of Circuit.\n\n:param circuit: The circuit to " "find frames for.\n" ":return: list of " CLSOBJS(Circuit), py::arg("circuit")) .def( "sample_circuits", &UniversalFrameRandomisation::sample_randomisation_circuits, "Returns a number of instances equal to sample of frame " "randomisation for the given circuit. Samples individual " "frame gates uniformly from the Pauli gates.\n\n:param " "circuit: The circuit to perform frame randomisation with " "Pauli gates on\n:param samples: the number of frame " "randomised circuits to return.\n" ":return: list of " CLSOBJS(Circuit), py::arg("circuit"), py::arg("samples")) .def("__repr__", &UniversalFrameRandomisation::to_string); m.def( "apply_clifford_basis_change", &apply_clifford_basis_change_string, "Given Pauli operator P and Clifford circuit C, " "returns C_dagger.P.C in multiplication order. This ignores any -1 " "phase that could be introduced. " "\n\n:param pauli: Pauli operator being transformed. " "\n:param circuit: Clifford circuit acting on Pauli operator. " "\n:return: :py:class:`QubitPauliString` for new operator", py::arg("pauli"), py::arg("circuit")); m.def( "apply_clifford_basis_change_tensor", &apply_clifford_basis_change_tensor, "Given Pauli operator P and Clifford circuit C, " "returns C_dagger.P.C in multiplication order" "\n\n:param pauli: Pauli operator being transformed." "\n:param circuit: Clifford circuit acting on Pauli operator. " "\n:return: :py:class:`QubitPauliTensor` for new operator", py::arg("pauli"), py::arg("circuit")); } } // namespace tket
tket/pytket/binders/tailoring.cpp/0
{ "file_path": "tket/pytket/binders/tailoring.cpp", "repo_id": "tket", "token_count": 3617 }
359
pytket.circuit.Circuit ====================== :py:class:`Circuit` objects provide an abstraction of quantum circuits. They consist of a set of qubits/quantum wires and a collection of operations applied to them in a given order. These wires have open inputs and outputs, rather than assuming any fixed input state. See the `pytket User Manual <https://tket.quantinuum.com/user-manual/manual_circuit.html>`_ for a step-by-step tutorial on constructing circuits. See also the notebook tutorials on `circuit generation <https://tket.quantinuum.com/examples/circuit_generation_example.html>`_ and `circuit analysis <https://tket.quantinuum.com/examples/circuit_analysis_example.html>`_. Many of the :py:class:`Circuit` methods described below append a gate or box to the end of the circuit. Where ``kwargs`` are indicated in these methods, the following keyword arguments are supported: - ``opgroup`` (:py:class:`str`): name of the associated operation group, if any - ``condition`` (:py:class:`Bit`, :py:class:`BitLogicExp` or :py:class:`Predicate`): classical condition for applying operation - ``condition_bits`` (list of :py:class:`Bit`): classical bits on which to condition operation - ``condition_value`` (:py:class:`int`): required value of condition bits (little-endian), defaulting to all-1s if not specified (Thus there are two ways to express classical conditions: either using a general ``condition``, or using the pair ``condition_bits`` and ``condition_value`` to condition on a specified set of bit values.) .. Sphinx doesn't seem to offer much control over how the methods and properties are ordered in the docs We list the methods and properties manually (for now) to ensure that the most important methods (e.g. Circuit.add_gate) are closer to the top of the page. Some less important methods like Circuit.YYPhase and Circuit.add_multiplexed_tensored_u2 are near the bottom. Since the Circuit class is so big we use the check_circuit_class_docs.py script to check that we haven't missed anything. .. currentmodule:: pytket.circuit.Circuit .. autoclass:: pytket.circuit.Circuit .. automethod:: __init__ .. automethod:: __iter__ .. automethod:: __rshift__ .. automethod:: add_gate .. automethod:: append .. automethod:: add_circuit .. automethod:: add_qubit .. automethod:: add_bit .. automethod:: add_phase .. autoproperty:: name .. autoproperty:: n_qubits .. autoproperty:: n_bits .. autoproperty:: phase .. autoproperty:: qubits .. autoproperty:: bits .. autoproperty:: n_gates .. autoproperty:: is_symbolic .. automethod:: add_q_register .. automethod:: get_q_register .. automethod:: add_c_register .. automethod:: get_c_register .. autoproperty:: q_registers .. autoproperty:: c_registers .. automethod:: rename_units .. automethod:: add_blank_wires .. automethod:: remove_blank_wires .. automethod:: flatten_registers .. autoproperty:: qubit_readout .. autoproperty:: bit_readout .. autoproperty:: opgroups .. autoproperty:: is_simple .. autoproperty:: qubit_to_bit_map .. automethod:: commands_of_type .. automethod:: ops_of_type .. automethod:: n_gates_of_type .. automethod:: n_1qb_gates .. automethod:: n_2qb_gates .. automethod:: n_nqb_gates .. automethod:: free_symbols .. automethod:: symbol_substitution .. automethod:: substitute_named .. automethod:: depth .. automethod:: depth_2q .. automethod:: depth_by_type .. automethod:: get_commands .. automethod:: add_barrier .. automethod:: add_conditional_barrier .. automethod:: add_wasm .. automethod:: add_wasm_to_reg .. automethod:: from_dict .. automethod:: to_dict .. automethod:: get_statevector .. automethod:: get_unitary .. automethod:: get_unitary_times_other .. automethod:: dagger .. automethod:: transpose .. automethod:: copy .. automethod:: get_resources .. automethod:: add_c_and .. automethod:: add_c_not .. automethod:: add_c_or .. automethod:: add_c_xor .. automethod:: add_c_range_predicate .. automethod:: add_c_and_to_registers .. automethod:: add_c_or_to_registers .. automethod:: add_c_xor_to_registers .. automethod:: add_c_not_to_registers .. automethod:: add_c_copybits .. automethod:: add_c_copyreg .. automethod:: add_c_setreg .. automethod:: add_c_setbits .. automethod:: add_c_transform .. automethod:: add_c_modifier .. automethod:: add_c_predicate .. automethod:: add_classicalexpbox_bit .. automethod:: add_classicalexpbox_register .. automethod:: qubit_create .. automethod:: qubit_create_all .. automethod:: qubit_discard .. automethod:: qubit_discard_all .. automethod:: qubit_is_created .. automethod:: qubit_is_discarded .. autoproperty:: created_qubits .. autoproperty:: discarded_qubits .. autoproperty:: valid_connectivity .. automethod:: replace_SWAPs .. automethod:: replace_implicit_wire_swaps .. automethod:: implicit_qubit_permutation .. automethod:: to_latex_file Convenience methods for appending gates --------------------------------------- .. Note:: For adding gates to a circuit the :py:meth:`Circuit.add_gate` method is sufficient to append any :py:class:`OpType` to a :py:class:`Circuit`. Some gates can only be added with :py:meth:`Circuit.add_gate`. For other more commonly used operations these can be added to a :py:class:`Circuit` directly using the convenience methods below. .. automethod:: H .. automethod:: X .. automethod:: Y .. automethod:: Z .. automethod:: S .. automethod:: Sdg .. automethod:: SX .. automethod:: SXdg .. automethod:: T .. automethod:: Tdg .. automethod:: V .. automethod:: Vdg .. automethod:: Rx .. automethod:: Ry .. automethod:: Rz .. automethod:: PhasedX .. automethod:: TK1 .. automethod:: TK2 .. automethod:: U1 .. automethod:: U2 .. automethod:: U3 .. automethod:: CX .. automethod:: CY .. automethod:: CZ .. automethod:: CS .. automethod:: CSdg .. automethod:: CV .. automethod:: CVdg .. automethod:: CSX .. automethod:: CSXdg .. automethod:: CH .. automethod:: ECR .. automethod:: CRx .. automethod:: CRy .. automethod:: CRz .. automethod:: CU1 .. automethod:: CU3 .. automethod:: Measure .. automethod:: measure_all .. automethod:: measure_register .. automethod:: Reset .. automethod:: Phase .. automethod:: SWAP .. automethod:: CCX .. automethod:: CSWAP .. automethod:: ESWAP .. automethod:: ISWAP .. automethod:: ISWAPMax .. automethod:: PhasedISWAP .. automethod:: FSim .. automethod:: Sycamore .. automethod:: XXPhase .. automethod:: XXPhase3 .. automethod:: YYPhase .. automethod:: ZZPhase .. automethod:: ZZMax .. automethod:: AAMS .. automethod:: GPI .. automethod:: GPI2 Methods for appending circuit boxes ----------------------------------- .. Note:: For adding boxes to a circuit the :py:meth:`Circuit.add_gate` method is sufficient to append any :py:class:`OpType` to a :py:class:`Circuit`. .. jupyter-input:: from pytket.circuit import Circuit, CircBox sub_circ = Circuit(2).CX(0, 1).Rz(0.25, 1).CX(0, 1) box = CircBox(sub_circ) bigger_circ = Circuit(3) # Equivalent to bigger_circ.add_circbox(box, [0, 1, 2]) bigger_circ.add_gate(box, [0, 1, 2]) .. automethod:: add_circbox .. automethod:: add_circbox_regwise .. automethod:: add_circbox_with_regmap .. automethod:: add_unitary1qbox .. automethod:: add_unitary2qbox .. automethod:: add_unitary3qbox .. automethod:: add_expbox .. automethod:: add_pauliexpbox .. automethod:: add_pauliexppairbox .. automethod:: add_pauliexpcommutingsetbox .. automethod:: add_termsequencebox .. automethod:: add_phasepolybox .. automethod:: add_toffolibox .. automethod:: add_dummybox .. automethod:: add_qcontrolbox .. automethod:: add_custom_gate .. automethod:: add_assertion .. automethod:: add_multiplexor .. automethod:: add_multiplexedrotation .. automethod:: add_multiplexedu2 .. automethod:: add_multiplexed_tensored_u2 .. automethod:: add_state_preparation_box .. automethod:: add_diagonal_box .. automethod:: add_conjugation_box
tket/pytket/docs/circuit_class.rst/0
{ "file_path": "tket/pytket/docs/circuit_class.rst", "repo_id": "tket", "token_count": 3107 }
360
pytket.placement ================================== In order for the constraints of a :py:class:`Backend` to be solved we must first assign device qubits to device-independent (or program) qubits. This module contains three placement methods to perform such an assignment. For more on qubit placement (and routing in general) see the `qubit mapping and routing <https://tket.quantinuum.com/examples/mapping_example.html>`_ tutorial and the corresponding entry in the `user manual <https://tket.quantinuum.com/user-manual/manual_compiler.html#placement>`_. .. automodule:: pytket._tket.placement :members: :special-members: __init__
tket/pytket/docs/placement.rst/0
{ "file_path": "tket/pytket/docs/placement.rst", "repo_id": "tket", "token_count": 184 }
361
from __future__ import annotations import pytket.circuit.logic_exp import typing __all__ = ['Bit', 'BitRegister', 'Node', 'Qubit', 'QubitRegister', 'UnitID', 'UnitType'] class Bit(UnitID): """ A handle to a bit """ @staticmethod def from_list(arg0: list) -> Bit: """ Construct Bit instance from JSON serializable list representation of the Bit. """ def __and__(self: typing.Union[pytket.circuit.logic_exp.LogicExp, pytket._tket.unit_id.Bit, int], other: typing.Union[pytket.circuit.logic_exp.LogicExp, pytket._tket.unit_id.Bit, int]) -> pytket.circuit.logic_exp.BitLogicExp: ... def __copy__(self) -> Bit: ... def __deepcopy__(self, arg0: dict) -> Bit: ... def __eq__(self, arg0: typing.Any) -> bool: ... def __getstate__(self) -> tuple: ... def __hash__(self) -> int: ... @typing.overload def __init__(self, index: int) -> None: """ Constructs an id for some index in the default classical register :param index: The index in the register """ @typing.overload def __init__(self, name: str) -> None: """ Constructs a named id (i.e. corresponding to a singleton register) :param name: The readable name for the id """ @typing.overload def __init__(self, name: str, index: int) -> None: """ Constructs an indexed id (i.e. corresponding to an element in a linear register) :param name: The readable name for the register :param index: The numerical index """ @typing.overload def __init__(self, name: str, row: int, col: int) -> None: """ Constructs a doubly-indexed id (i.e. corresponding to an element in a grid register) :param name: The readable name for the register :param row: The row index :param col: The column index """ @typing.overload def __init__(self, name: str, index: typing.Sequence[int]) -> None: """ Constructs an id with an arbitrary-dimensional index :param name: The readable name for the register :param index: The index vector """ def __or__(self: typing.Union[pytket.circuit.logic_exp.LogicExp, pytket._tket.unit_id.Bit, int], other: typing.Union[pytket.circuit.logic_exp.LogicExp, pytket._tket.unit_id.Bit, int]) -> pytket.circuit.logic_exp.BitLogicExp: ... def __rand__(self: typing.Union[pytket.circuit.logic_exp.LogicExp, pytket._tket.unit_id.Bit, int], other: typing.Union[pytket.circuit.logic_exp.LogicExp, pytket._tket.unit_id.Bit, int]) -> pytket.circuit.logic_exp.BitLogicExp: ... def __ror__(self: typing.Union[pytket.circuit.logic_exp.LogicExp, pytket._tket.unit_id.Bit, int], other: typing.Union[pytket.circuit.logic_exp.LogicExp, pytket._tket.unit_id.Bit, int]) -> pytket.circuit.logic_exp.BitLogicExp: ... def __rxor__(self: typing.Union[pytket.circuit.logic_exp.LogicExp, pytket._tket.unit_id.Bit, int], other: typing.Union[pytket.circuit.logic_exp.LogicExp, pytket._tket.unit_id.Bit, int]) -> pytket.circuit.logic_exp.BitLogicExp: ... def __setstate__(self, arg0: tuple) -> None: ... def __xor__(self: typing.Union[pytket.circuit.logic_exp.LogicExp, pytket._tket.unit_id.Bit, int], other: typing.Union[pytket.circuit.logic_exp.LogicExp, pytket._tket.unit_id.Bit, int]) -> pytket.circuit.logic_exp.BitLogicExp: ... def to_list(self) -> list: """ Return a JSON serializable list representation of the Bit. :return: list containing register name and index """ class BitRegister: """ Linear register of UnitID types. """ def __add__(self: typing.Union[pytket.circuit.logic_exp.LogicExp, pytket._tket.unit_id.BitRegister, int], other: typing.Union[pytket.circuit.logic_exp.LogicExp, pytket._tket.unit_id.BitRegister, int]) -> pytket.circuit.logic_exp.RegLogicExp: ... def __and__(self: typing.Union[pytket.circuit.logic_exp.LogicExp, pytket._tket.unit_id.BitRegister, int], other: typing.Union[pytket.circuit.logic_exp.LogicExp, pytket._tket.unit_id.BitRegister, int]) -> pytket.circuit.logic_exp.RegLogicExp: ... def __contains__(self, arg0: Bit) -> bool: ... def __copy__(self) -> BitRegister: ... def __deepcopy__(self, arg0: dict) -> BitRegister: ... def __eq__(self, arg0: typing.Any) -> bool: ... def __floordiv__(self: typing.Union[pytket.circuit.logic_exp.LogicExp, pytket._tket.unit_id.BitRegister, int], other: typing.Union[pytket.circuit.logic_exp.LogicExp, pytket._tket.unit_id.BitRegister, int]) -> pytket.circuit.logic_exp.RegLogicExp: ... def __getitem__(self, arg0: int) -> Bit: ... def __hash__(self) -> int: ... def __init__(self, name: str, size: int) -> None: """ Construct a new BitRegister. :param name: Name of the register. :param size: Size of register. """ def __iter__(self) -> BitRegister: ... def __len__(self) -> int: ... def __lshift__(self: typing.Union[pytket.circuit.logic_exp.LogicExp, pytket._tket.unit_id.BitRegister, int], other: typing.Union[pytket.circuit.logic_exp.LogicExp, pytket._tket.unit_id.BitRegister, int]) -> pytket.circuit.logic_exp.RegLogicExp: ... def __lt__(self, arg0: BitRegister) -> bool: ... def __mul__(self: typing.Union[pytket.circuit.logic_exp.LogicExp, pytket._tket.unit_id.BitRegister, int], other: typing.Union[pytket.circuit.logic_exp.LogicExp, pytket._tket.unit_id.BitRegister, int]) -> pytket.circuit.logic_exp.RegLogicExp: ... def __next__(self) -> Bit: ... def __or__(self: typing.Union[pytket.circuit.logic_exp.LogicExp, pytket._tket.unit_id.BitRegister, int], other: typing.Union[pytket.circuit.logic_exp.LogicExp, pytket._tket.unit_id.BitRegister, int]) -> pytket.circuit.logic_exp.RegLogicExp: ... def __pow__(self: typing.Union[pytket.circuit.logic_exp.LogicExp, pytket._tket.unit_id.BitRegister, int], other: typing.Union[pytket.circuit.logic_exp.LogicExp, pytket._tket.unit_id.BitRegister, int]) -> pytket.circuit.logic_exp.RegLogicExp: ... def __rand__(self: typing.Union[pytket.circuit.logic_exp.LogicExp, pytket._tket.unit_id.BitRegister, int], other: typing.Union[pytket.circuit.logic_exp.LogicExp, pytket._tket.unit_id.BitRegister, int]) -> pytket.circuit.logic_exp.RegLogicExp: ... def __repr__(self) -> str: ... def __ror__(self: typing.Union[pytket.circuit.logic_exp.LogicExp, pytket._tket.unit_id.BitRegister, int], other: typing.Union[pytket.circuit.logic_exp.LogicExp, pytket._tket.unit_id.BitRegister, int]) -> pytket.circuit.logic_exp.RegLogicExp: ... def __rshift__(self: typing.Union[pytket.circuit.logic_exp.LogicExp, pytket._tket.unit_id.BitRegister, int], other: typing.Union[pytket.circuit.logic_exp.LogicExp, pytket._tket.unit_id.BitRegister, int]) -> pytket.circuit.logic_exp.RegLogicExp: ... def __rxor__(self: typing.Union[pytket.circuit.logic_exp.LogicExp, pytket._tket.unit_id.BitRegister, int], other: typing.Union[pytket.circuit.logic_exp.LogicExp, pytket._tket.unit_id.BitRegister, int]) -> pytket.circuit.logic_exp.RegLogicExp: ... def __str__(self) -> str: ... def __sub__(self: typing.Union[pytket.circuit.logic_exp.LogicExp, pytket._tket.unit_id.BitRegister, int], other: typing.Union[pytket.circuit.logic_exp.LogicExp, pytket._tket.unit_id.BitRegister, int]) -> pytket.circuit.logic_exp.RegLogicExp: ... def __xor__(self: typing.Union[pytket.circuit.logic_exp.LogicExp, pytket._tket.unit_id.BitRegister, int], other: typing.Union[pytket.circuit.logic_exp.LogicExp, pytket._tket.unit_id.BitRegister, int]) -> pytket.circuit.logic_exp.RegLogicExp: ... def to_list(self) -> list[Bit]: ... @property def _current(self) -> int: """ Internal property for iteration. """ @_current.setter def _current(self, arg1: int) -> None: ... @property def name(self) -> str: """ Name of register. """ @name.setter def name(self, arg1: str) -> None: ... @property def size(self) -> int: """ Size of register. """ @size.setter def size(self, arg1: int) -> None: ... class Node(Qubit): """ A handle to a device node """ @staticmethod def from_list(arg0: list) -> Node: """ Construct Node instance from JSON serializable list representation of the Node. """ def __copy__(self) -> Node: ... def __deepcopy__(self, arg0: dict) -> Node: ... @typing.overload def __init__(self, index: int) -> None: """ Constructs an id for some index in the default physical register :param index: The index in the register """ @typing.overload def __init__(self, name: str, index: int) -> None: """ Constructs an indexed id (i.e. corresponding to an element in a linear register) :param name: The readable name for the register :param index: The numerical index """ @typing.overload def __init__(self, name: str, row: int, col: int) -> None: """ Constructs a doubly-indexed id (i.e. corresponding to an element in a grid register) :param name: The readable name for the register :param row: The row index :param col: The column index """ @typing.overload def __init__(self, name: str, row: int, col: int, layer: int) -> None: """ Constructs a triply-indexed id (i.e. corresponding to an element in a 3D grid register) :param name: The readable name for the register :param row: The row index :param col: The column index :param layer: The layer index """ @typing.overload def __init__(self, name: str, index: typing.Sequence[int]) -> None: """ Constructs an id with an arbitrary-dimensional index :param name: The readable name for the register :param index: The index vector """ def to_list(self) -> list: """ :return: a JSON serializable list representation of the Node """ class Qubit(UnitID): """ A handle to a qubit """ @staticmethod def from_list(arg0: list) -> Qubit: """ Construct Qubit instance from JSON serializable list representation of the Qubit. """ def __copy__(self) -> Qubit: ... def __deepcopy__(self, arg0: dict) -> Qubit: ... def __getstate__(self) -> tuple: ... @typing.overload def __init__(self, index: int) -> None: """ Constructs an id for some index in the default qubit register :param index: The index in the register """ @typing.overload def __init__(self, name: str) -> None: """ Constructs a named id (i.e. corresponding to a singleton register) :param name: The readable name for the id """ @typing.overload def __init__(self, name: str, index: int) -> None: """ Constructs an indexed id (i.e. corresponding to an element in a linear register) :param name: The readable name for the register :param index: The numerical index """ @typing.overload def __init__(self, name: str, row: int, col: int) -> None: """ Constructs a doubly-indexed id (i.e. corresponding to an element in a grid register) :param name: The readable name for the register :param row: The row index :param col: The column index """ @typing.overload def __init__(self, name: str, index: typing.Sequence[int]) -> None: """ Constructs an id with an arbitrary-dimensional index :param name: The readable name for the register :param index: The index vector """ def __setstate__(self, arg0: tuple) -> None: ... def to_list(self) -> list: """ :return: a JSON serializable list representation of the Qubit """ class QubitRegister: """ Linear register of UnitID types. """ def __contains__(self, arg0: Qubit) -> bool: ... def __copy__(self) -> QubitRegister: ... def __deepcopy__(self, arg0: dict) -> QubitRegister: ... def __eq__(self, arg0: typing.Any) -> bool: ... def __getitem__(self, arg0: int) -> Qubit: ... def __hash__(self) -> int: ... def __init__(self, name: str, size: int) -> None: """ Construct a new QubitRegister. :param name: Name of the register. :param size: Size of register. """ def __iter__(self) -> QubitRegister: ... def __len__(self) -> int: ... def __lt__(self, arg0: QubitRegister) -> bool: ... def __next__(self) -> Qubit: ... def __repr__(self) -> str: ... def __str__(self) -> str: ... def to_list(self) -> list[Qubit]: ... @property def _current(self) -> int: """ Internal property for iteration. """ @_current.setter def _current(self, arg1: int) -> None: ... @property def name(self) -> str: """ Name of register. """ @name.setter def name(self, arg1: str) -> None: ... @property def size(self) -> int: """ Size of register. """ @size.setter def size(self, arg1: int) -> None: ... class UnitID: """ A handle to a computational unit (e.g. qubit, bit) """ def __copy__(self) -> UnitID: ... def __deepcopy__(self, arg0: dict) -> UnitID: ... def __eq__(self, arg0: typing.Any) -> bool: ... def __hash__(self) -> int: ... def __init__(self) -> None: ... def __lt__(self, arg0: UnitID) -> bool: ... def __repr__(self) -> str: ... @property def index(self) -> list[int]: """ Index vector describing position in the register. The length of this vector is the dimension of the register """ @property def reg_name(self) -> str: """ Readable name of register """ @property def type(self) -> UnitType: """ Type of unit, either ``UnitType.qubit`` or ``UnitType.bit`` """ class UnitType: """ Enum for data types of units in circuits (e.g. Qubits vs Bits). Members: qubit : A single Qubit bit : A single classical Bit """ __members__: typing.ClassVar[dict[str, UnitType]] # value = {'qubit': <UnitType.qubit: 0>, 'bit': <UnitType.bit: 1>} bit: typing.ClassVar[UnitType] # value = <UnitType.bit: 1> qubit: typing.ClassVar[UnitType] # value = <UnitType.qubit: 0> def __eq__(self, other: typing.Any) -> bool: ... def __getstate__(self) -> int: ... def __hash__(self) -> int: ... def __index__(self) -> int: ... def __init__(self, value: int) -> None: ... def __int__(self) -> int: ... def __ne__(self, other: typing.Any) -> bool: ... def __repr__(self) -> str: ... def __setstate__(self, state: int) -> None: ... def __str__(self) -> str: ... @property def name(self) -> str: ... @property def value(self) -> int: ... _DEBUG_ONE_REG_PREFIX: str = 'tk_DEBUG_ONE_REG' _DEBUG_ZERO_REG_PREFIX: str = 'tk_DEBUG_ZERO_REG' _TEMP_BIT_NAME: str = 'tk_SCRATCH_BIT' _TEMP_BIT_REG_BASE: str = 'tk_SCRATCH_BITREG' _TEMP_REG_SIZE: int = 64
tket/pytket/pytket/_tket/unit_id.pyi/0
{ "file_path": "tket/pytket/pytket/_tket/unit_id.pyi", "repo_id": "tket", "token_count": 7168 }
362
{% macro show_circuit_page(display_options, circuit_json, uid, min_width, min_height) %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> {% include "html/head_imports.html" %} </head> <body> {% if not jupyter %} <div style=" position:absolute; top:0;bottom:0;left:0;right:0; margin:auto;resize:both;display:block;overflow:hidden; width:min({{ min_width }}, 100%); height:min({{ min_height }},100%); max-width:100%; max-height:100%;"> {% endif %} <div id="circuit-display-vue-container-{{uid}}" class="pytket-circuit-display-container"> <div style="display: none"> <div id="circuit-json-to-display">{{ circuit_json }}</div> </div> <circuit-display-container :circuit-element-str="'#circuit-json-to-display'" :init-render-options="initRenderOptions" ></circuit-display-container> </div> <script type="application/javascript"> const circuitRendererUid = "{{ uid }}"; const displayOptions = JSON.parse('{{display_options}}'); {% include_raw "js/main.js" %} </script> {% if not jupyter %} </div> {% endif %} </body> </html> {% endmacro %} {% if jupyter %} <div style="resize: vertical; overflow: auto; height: {{ min_height }}; display: block"> <iframe srcdoc="{{ show_circuit_page(display_options, circuit_json, uid)|escape }}" width="100%" height="100%" style="border: none; outline: none; overflow: auto"></iframe> </div> {% else %} {{ show_circuit_page(display_options, circuit_json, uid, min_width, min_height) }} {% endif %}
tket/pytket/pytket/circuit/display/static/circuit.html/0
{ "file_path": "tket/pytket/pytket/circuit/display/static/circuit.html", "repo_id": "tket", "token_count": 698 }
363
# 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. import itertools from functools import lru_cache from math import ceil, log2 from collections import OrderedDict from typing import Dict, Iterable, List, Tuple, Counter, cast, Optional, Callable, Union import numpy as np from pytket.circuit import Circuit, Qubit, Bit, Node, CircBox, OpType from pytket.backends import Backend from pytket.passes import DecomposeBoxes, FlattenRegisters from pytket.backends.backendresult import BackendResult from pytket.utils.outcomearray import OutcomeArray from pytket.utils.results import CountsDict, StateTuple ParallelMeasures = List[Dict[Qubit, Bit]] def compress_counts( counts: Dict[StateTuple, float], tol: float = 1e-6, round_to_int: bool = False ) -> CountsDict: """Filter counts to remove states that have a count value (which can be a floating-point number) below a tolerance, and optionally round to an integer. :param counts: Input counts :type counts: Dict[StateTuple, float] :param tol: Value below which counts are pruned. Defaults to 1e-6. :type tol: float, optional :param round_to_int: Whether to round each count to an integer. Defaults to False. :type round_to_int: bool, optional :return: Filtered counts :rtype: CountsDict """ valprocess: Callable[[float], Union[int, float]] = lambda x: ( int(round(x)) if round_to_int else x ) processed_pairs = ( (key, valprocess(val)) for key, val in counts.items() if val > tol ) return {key: val for key, val in processed_pairs if val > 0} @lru_cache(maxsize=128) def binary_to_int(bintuple: Tuple[int]) -> int: """Convert a binary tuple to corresponding integer, with most significant bit as the first element of tuple. :param bintuple: Binary tuple :type bintuple: Tuple[int] :return: Integer :rtype: int """ integer = 0 for index, bitset in enumerate(reversed(bintuple)): if bitset: integer |= 1 << index return integer @lru_cache(maxsize=128) def int_to_binary(val: int, dim: int) -> Tuple[int, ...]: """Convert an integer to corresponding binary tuple, with most significant bit as the first element of tuple. :param val: input integer :type val: int :param dim: Bit width :type dim: int :return: Binary tuple of width dim :rtype: Tuple[int, ...] """ return tuple(map(int, format(val, "0{}b".format(dim)))) ######################################### ### _compute_dot and helper functions ### ### ### With thanks to ### https://math.stackexchange.com/a/3423910 ### and especially ### https://gist.github.com/ahwillia/f65bc70cb30206d4eadec857b98c4065 ### on which this code is based. def _unfold(tens: np.ndarray, mode: int, dims: List[int]) -> np.ndarray: """Unfolds tensor into matrix. :param tens: Tensor with shape equivalent to dimensions :type tens: np.ndarray :param mode: Specifies axis move to front of matrix in unfolding of tensor :type mode: int :param dims: Gives shape of tensor passed :type dims: List[int] :return: Matrix with shape (dims[mode], prod(dims[/mode])) :rtype: np.ndarray """ if mode == 0: return tens.reshape(dims[0], -1) else: return np.moveaxis(tens, mode, 0).reshape(dims[mode], -1) def _refold(vec: np.ndarray, mode: int, dims: List[int]) -> np.ndarray: """Refolds vector into tensor. :param vec: Tensor with length equivalent to the product of dimensions given in dims :type vec: np.ndarray :param mode: Axis tensor was unfolded along :type mode: int :param dims: Shape of tensor :type dims: List[int] :return: Tensor folded from vector with shape equivalent to given dimensions :rtype: np.ndarray """ if mode == 0: return vec.reshape(dims) else: # Reshape and then move dims[mode] back to its # appropriate spot (undoing the `unfold` operation). tens = vec.reshape([dims[mode]] + [d for m, d in enumerate(dims) if m != mode]) return np.moveaxis(tens, 0, mode) def _compute_dot(submatrices: Iterable[np.ndarray], vector: np.ndarray) -> np.ndarray: """Multiplies the kronecker product of the given submatrices with given vector. :param submatrices: Submatrices multiplied :type submatrices: Iterable[np.ndarray] :param vector: Vector multplied :type vector: np.ndarray :return: Kronecker product of arguments :rtype: np.ndarray """ dims = [A.shape[0] for A in submatrices] vt = vector.reshape(dims) for i, A in enumerate(submatrices): vt = _refold(A @ _unfold(vt, i, dims), i, dims) return vt.ravel() def _bayesian_iteration( submatrices: Iterable[np.ndarray], measurements: np.ndarray, t: np.ndarray, epsilon: float, ) -> np.ndarray: """Transforms T corresponds to a Bayesian iteration, used to modfiy measurements. :param submatrices: submatrices to be inverted and applied to measurements. :type submatrices: Iterable[np.ndarray] :param measurements: Probability distribution over set of states to be amended. :type measurements: np.ndarray :param t: Some transform to act on measurements. :type t: np.ndarray :param epsilon: A stabilization parameter to define an affine transformation for application to submatrices, eliminating zero probabilities. :type epsilon: float :return: Transformed distribution vector. :rtype: np.ndarray """ # Transform t according to the Bayesian iteration # The parameter epsilon is a stabilization parameter which defines an affine # transformation to apply to the submatrices to eliminate zero probabilities. This # transformation preserves the property that all columns sum to 1 if epsilon == 0: # avoid copying if we don't need to As = submatrices else: As = [ epsilon / submatrix.shape[0] + (1 - epsilon) * submatrix for submatrix in submatrices ] z = _compute_dot(As, t) if np.isclose(z, 0).any(): raise ZeroDivisionError return cast( np.ndarray, t * _compute_dot([A.transpose() for A in As], measurements / z) ) def _bayesian_iterative_correct( submatrices: Iterable[np.ndarray], measurements: np.ndarray, tol: float = 1e-5, max_it: Optional[int] = None, ) -> np.ndarray: """Finds new states to represent application of inversion of submatrices on measurements. Converges when update states within tol range of previously tested states. :param submatrices: Matrices comprising the pure noise characterisation. :type submatrices: Iterable[np.ndarray] :param input_vector: Vector corresponding to some counts distribution. :type input_vector: np.ndarray :param tol: tolerance of closeness of found results :type tol: float :param max_it: Maximum number of inversions attempted to correct results. :type max_it: int """ # based on method found in https://arxiv.org/abs/1910.00129 vector_size = measurements.size # uniform initial true_states = np.full(vector_size, 1 / vector_size) prev_true = true_states.copy() converged = False count = 0 epsilon: float = 0 # stabilization parameter, adjusted dynamically while not converged: if max_it: if count >= max_it: break count += 1 try: true_states = _bayesian_iteration( submatrices, measurements, true_states, epsilon ) converged = np.allclose(true_states, prev_true, atol=tol) prev_true = true_states.copy() except ZeroDivisionError: # Shift the stabilization parameter up a bit (always < 0.5). epsilon = 0.99 * epsilon + 0.01 * 0.5 return true_states def reduce_matrix(indices_to_remove: List[int], matrix: np.ndarray) -> np.ndarray: """Removes indices from indices_to_remove from binary associated to indexing of matrix, producing a new transition matrix. To do so, it assigns all transition probabilities as the given state in the remaining indices binary, with the removed binary in state 0. This is an assumption on the noise made because it is likely that unmeasured qubits will be in that state. :param indices_to_remove: Binary index of state matrix is mapping to be removed. :type indices_to_remove: List[int] :param matrix: Transition matrix where indices correspond to some binary state. :type matrix: np.ndarray :return: Transition matrix with removed entries. :rtype: np.ndarray """ new_n_qubits = int(log2(matrix.shape[0])) - len(indices_to_remove) if new_n_qubits == 0: return np.array([]) bin_map = dict() mat_dim = 1 << new_n_qubits for index in range(mat_dim): # get current binary bina = list(int_to_binary(index, new_n_qubits)) # add 0's to fetch old binary to set values from for i in sorted(indices_to_remove): bina.insert(i, 0) # get index of values bin_map[index] = binary_to_int(tuple(bina)) new_mat = np.zeros((mat_dim,) * 2, dtype=float) for i in range(len(new_mat)): old_row_index = bin_map[i] for j in range(len(new_mat)): old_col_index = bin_map[j] new_mat[i, j] = matrix[old_row_index, old_col_index] return new_mat def reduce_matrices( entries_to_remove: List[Tuple[int, int]], matrices: List[np.ndarray] ) -> List[np.ndarray]: """Removes some dimensions from some matrices. :param entries_to_remove: Via indexing, details dimensions to be removed. :type entries_to_remove: List[Tuple[int, int]] :param matrices: All matrices to have dimensions removed. :type matrices: List[np.ndarray] :return: Matrices with some dimensions removed. :rtype: List[np.ndarray] """ organise: Dict[int, List] = dict({k: [] for k in range(len(matrices))}) for unused in entries_to_remove: # unused[0] is index in matrices # unused[1] is qubit index in matrix organise[unused[0]].append(unused[1]) output_matrices = [reduce_matrix(organise[m], matrices[m]) for m in organise] normalised_mats = [ mat / np.sum(mat, axis=0) for mat in [x for x in output_matrices if len(x) != 0] ] return normalised_mats class SpamCorrecter: """A class for generating "state preparation and measurement" (SPAM) calibration experiments for ``pytket`` backends, and correcting counts generated from them. Supports saving calibrated state to a dictionary format, and restoring from the dictionary. """ def __init__( self, qubit_subsets: List[List[Node]], backend: Optional[Backend] = None ): """Construct a new `SpamCorrecter`. :param qubit_subsets: A list of lists of correlated Nodes of an `Architecture`. Qubits within the same list are assumed to only have SPAM errors correlated with each other. Thus to allow SPAM errors between all qubits you should provide a single list. :type qubit_subsets: List[List[Node]] :param backend: Backend on which the experiments are intended to be run (optional). If provided, the qubits in `qubit_subsets` must be nodes in the backend's associated `Architecture`. If not provided, it is assumed that the experiment will be run on an `Architecture`with the nodes in `qubit_subsets`, and furthermore that the intended architecture natively supports X gates. :raises ValueError: There are repeats in the `qubit_subsets` specification. """ self.correlations = qubit_subsets self.all_qbs = [qb for subset in qubit_subsets for qb in subset] def to_tuple(inp: list[Node]) -> tuple: return tuple(inp) self.subsets_matrix_map = OrderedDict.fromkeys( sorted(map(to_tuple, self.correlations), key=len, reverse=True) ) # ordered from largest to smallest via OrderedDict & sorted self.subset_dimensions = [len(subset) for subset in self.subsets_matrix_map] if len(self.all_qbs) != len(set(self.all_qbs)): raise ValueError("Qubit subsets are not mutually disjoint.") xcirc = Circuit(1).X(0) if backend is not None: if backend.backend_info is None: raise ValueError("No architecture associated with backend.") nodes = backend.backend_info.nodes if not all(node in nodes for node in self.all_qbs): raise ValueError("Nodes do not all belong to architecture.") backend.default_compilation_pass().apply(xcirc) FlattenRegisters().apply(xcirc) self.xbox = CircBox(xcirc) def calibration_circuits(self) -> List[Circuit]: """Generate calibration circuits according to the specified correlations. :return: A list of calibration circuits to be run on the machine. The circuits should be processed without compilation. Results from these circuits must be given back to this class (via the `calculate_matrices` method) in the same order. :rtype: List[Circuit] """ major_state_dimensions = self.subset_dimensions[0] n_circuits = 1 << major_state_dimensions # output self.prepared_circuits = [] self.state_infos = [] # set up base circuit for appending xbox to base_circuit = Circuit() c_reg = [] for index, qb in enumerate(self.all_qbs): base_circuit.add_qubit(qb) c_bit = Bit(index) c_reg.append(c_bit) base_circuit.add_bit(c_bit) # generate state circuits for given correlations for major_state_index in range(n_circuits): state_circuit = base_circuit.copy() # get bit string corresponding to basis state of biggest subset of qubits major_state = int_to_binary(major_state_index, major_state_dimensions) new_state_dicts = {} # parallelise circuits, run uncorrelated subsets # characterisation in parallel for dim, qubits in zip(self.subset_dimensions, self.subsets_matrix_map): # add state to prepared states new_state_dicts[qubits] = major_state[:dim] # find only qubits that are expected to be in 1 state, # add xbox to given qubits for flipped_qb in itertools.compress(qubits, major_state[:dim]): state_circuit.add_circbox(self.xbox, [flipped_qb]) # Decompose boxes, add barriers to preserve circuit, add measures DecomposeBoxes().apply(state_circuit) for qb, cb in zip(self.all_qbs, c_reg): state_circuit.Measure(qb, cb) # add to returned types self.prepared_circuits.append(state_circuit) self.state_infos.append((new_state_dicts, state_circuit.qubit_to_bit_map)) return self.prepared_circuits def calculate_matrices(self, results_list: List[BackendResult]) -> None: """Calculate the calibration matrices from the results of running calibration circuits. :param results_list: List of results from Backend. Must be in the same order as the corresponding circuits generated by `calibration_circuits`. :type counts_list: List[BackendResult] :raises RuntimeError: Calibration circuits have not been generated yet. """ if not self.state_infos: raise RuntimeError( "Ensure calibration states/circuits have been calculated first." ) counter = 0 self.node_index_dict: Dict[Node, Tuple[int, int]] = dict() for qbs, dim in zip(self.subsets_matrix_map, self.subset_dimensions): # for a subset with n qubits, create a 2^n by 2^n matrix self.subsets_matrix_map[qbs] = np.zeros((1 << dim,) * 2, dtype=float) for i in range(len(qbs)): qb = qbs[i] self.node_index_dict[qb] = (counter, i) counter += 1 for result, state_info in zip(results_list, self.state_infos): state_dict = state_info[0] qb_bit_map = state_info[1] for qb_sub in self.subsets_matrix_map: # bits of counts to consider bits = [qb_bit_map[q] for q in qb_sub] counts_dict = result.get_counts(cbits=bits) for measured_state, count in counts_dict.items(): # intended state prepared_state_index = binary_to_int(state_dict[qb_sub]) # produced state measured_state_index = binary_to_int(measured_state) # update characterisation matrix M = self.subsets_matrix_map[qb_sub] assert type(M) is np.ndarray M[measured_state_index, prepared_state_index] += count # normalise everything self.characterisation_matrices = [ mat / np.sum(cast(np.ndarray, mat), axis=0) for mat in self.subsets_matrix_map.values() ] def get_parallel_measure(self, circuit: Circuit) -> ParallelMeasures: """For a given circuit, produces and returns a ParallelMeasures object required for correcting counts results. :param circuit: Circuit with some Measure operations. :type circuit: Circuit :return: A list of dictionaries mapping Qubit to Bit where each separate dictionary details some set of Measurement operations run in parallel. :rtype: ParallelMeasures """ parallel_measure = [circuit.qubit_to_bit_map] # implies mid-circuit measurements, or that at least missing # bits need to be checked for Measure operation if len(parallel_measure[0]) != len(circuit.bits): used_bits = set(parallel_measure[0].values()) for mc in circuit.commands_of_type(OpType.Measure): bit = mc.bits[0] if bit not in used_bits: # mid-circuit measure, add as a separate parallel measure parallel_measure.append({mc.qubits[0]: bit}) return parallel_measure def correct_counts( self, result: BackendResult, parallel_measures: ParallelMeasures, method: str = "bayesian", options: Optional[Dict] = None, ) -> BackendResult: """Modifies count distribution for result, such that the inversion of the pure noise map represented by characterisation matrices is applied to it. :param result: BackendResult object to be negated by pure noise object. :type result: BackendResult :param parallel_measures: Used to permute corresponding BackendResult object so counts order matches noise characterisation and to amend characterisation matrices to correct the right bits. SpamCorrecter.get_parallel_measure returns the required object for a given circuit. :type parallel_measures: ParallelMeasures :raises ValueError: Measured qubit in result not characterised. :return: A new result object with counts modified to reflect SPAM correction. :rtype: BackendResult """ # the correction process assumes that when passed a list of matrices # and a distribution to correct, that the j rows of matrix i # corrects for the i, i+1,...i+j states in the passed distribution # given information of which bits are measured on which qubits from # parallel_measures, the following first produces matrices such that # this condition is true char_bits_order = [] correction_matrices = [] for mapping in parallel_measures: # reduce_matrices removes given qubits corresponding entries from # characterisation matrices unused_qbs = set(self.all_qbs.copy()) for q in mapping: # no q duplicates as mapping is dict from qubit to bit if q not in unused_qbs: raise ValueError( "Measured qubit {} is not characterised by " "SpamCorrecter".format(q) ) unused_qbs.remove(q) # type:ignore[arg-type] char_bits_order.append(mapping[q]) correction_matrices.extend( reduce_matrices( [self.node_index_dict[q] for q in unused_qbs], self.characterisation_matrices, ) ) # get counts object for returning later counts = result.get_counts(cbits=char_bits_order) in_vec = np.zeros(1 << len(char_bits_order), dtype=float) # turn from counts to probability distribution for state, count in counts.items(): in_vec[binary_to_int(state)] = count Ncounts = np.sum(in_vec) in_vec_norm = in_vec / Ncounts # with counts and characterisation matrices orders matching, # correct distribution if method == "invert": try: subinverts = [ np.linalg.inv(submatrix) for submatrix in correction_matrices ] except np.linalg.LinAlgError: raise ValueError( "Unable to invert calibration matrix: please re-run " "calibration experiments or use an alternative correction method." ) # assumes that order of rows in flattened subinverts equals # order of bits in input vector outvec = _compute_dot(subinverts, in_vec_norm) # The entries of v will always sum to 1, but they may not all # be in the range [0,1]. In order to make them genuine # probabilities (and thus generate meaningful counts), # we adjust them by setting all negative values to 0 and scaling # the remainder. outvec[outvec < 0] = 0 outvec /= sum(outvec) elif method == "bayesian": if options is None: options = {} tol_val = options.get("tol", 1 / Ncounts) maxit = options.get("maxiter", None) outvec = _bayesian_iterative_correct( correction_matrices, in_vec_norm, tol=tol_val, max_it=maxit ) else: valid_methods = ("invert", "bayesian") raise ValueError("Method must be one of: ", *valid_methods) outvec *= Ncounts # counter object with binary from distribution corrected_counts = { int_to_binary(index, len(char_bits_order)): Bcount for index, Bcount in enumerate(outvec) } counter = Counter( { OutcomeArray.from_readouts([key]): ceil(val) for key, val in corrected_counts.items() } ) # produce and return BackendResult object return BackendResult(counts=counter, c_bits=char_bits_order) def to_dict(self) -> Dict: """Get calibration information as a dictionary. :return: Dictionary output :rtype: Dict """ correlations = [] for subset in self.correlations: correlations.append([(uid.reg_name, uid.index) for uid in subset]) node_index_hashable = [ ((uid.reg_name, uid.index), self.node_index_dict[uid]) for uid in self.node_index_dict ] char_matrices = [m.tolist() for m in self.characterisation_matrices] self_dict = { "correlations": correlations, "node_index_dict": node_index_hashable, "characterisation_matrices": char_matrices, } return self_dict @classmethod def from_dict(class_obj, d: Dict) -> "SpamCorrecter": """Build a `SpamCorrecter` instance from a dictionary in the format returned by `to_dict`. :return: Dictionary of calibration information. :rtype: SpamCorrecter """ new_inst = class_obj( [ [Node(*pair)] for subset_tuple in d["correlations"] for pair in subset_tuple ] ) new_inst.node_index_dict = dict( [ (Node(*pair[0]), (int(pair[1][0]), int(pair[1][1]))) for pair in d["node_index_dict"] ] ) new_inst.characterisation_matrices = [ np.array(m) for m in d["characterisation_matrices"] ] return new_inst
tket/pytket/pytket/utils/spam.py/0
{ "file_path": "tket/pytket/pytket/utils/spam.py", "repo_id": "tket", "token_count": 10526 }
364
# 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. import numpy as np import pytest from pytket.circuit import ( ProjectorAssertionBox, StabiliserAssertionBox, Circuit, Qubit, ) from pytket.passes import ( DecomposeBoxes, ) from pytket.pauli import PauliStabiliser, Pauli from simulator import TketSimShotBackend # type: ignore def test_assertion_init() -> None: circ = Circuit(5) P = np.asarray( [ [0.5, 0, 0, 0.5], [0, 0, 0, 0], [0, 0, 0, 0], [0.5, 0, 0, 0.5], ] ) p_box = ProjectorAssertionBox(P) circ.add_assertion(p_box, [0, 1], name="|bell>") circ.add_assertion(p_box, [Qubit(0), Qubit(1)], name="|bell> 2") # Projector that requires a ancilla P = np.asarray( [ [1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 0], ] ) p_box = ProjectorAssertionBox(P) with pytest.raises(RuntimeError) as errorinfo: circ.add_assertion(p_box, [0, 1]) assert "ancilla" in str(errorinfo.value) circ.add_assertion(p_box, [0, 1], ancilla=2) stabilisers = StabiliserAssertionBox( [ PauliStabiliser([Pauli.X, Pauli.X], 1), PauliStabiliser([Pauli.Y, Pauli.Y], -1), ] ) stabilisers_2 = StabiliserAssertionBox(["XX", "-YY"]) assert stabilisers.get_stabilisers() == stabilisers_2.get_stabilisers() circ.add_assertion(stabilisers, [0, 1], 2, name="|stab1>") circ.add_assertion(stabilisers_2, [0, 1], 2, name="|stab2>") circ.add_assertion(stabilisers_2, [Qubit(0), Qubit(1)], Qubit(2), name="|stab3>") # Test the circuit can be decomposed assert DecomposeBoxes().apply(circ) def test_assertion() -> None: # P =|00><00| tensor I + |111><111| P = np.zeros((8, 8), dtype=np.complex128) P[0, 0] = 1 P[1, 1] = 1 P[7, 7] = 1 p_box = ProjectorAssertionBox(P) circ = Circuit(6) circ.X(0) circ.H(2) circ.X(1) circ.X(3) circ.add_assertion(p_box, [4, 5, 1], name="|001>") circ.add_assertion(p_box, [0, 1, 3], name="|111>") circ.add_assertion(p_box, [1, 3, 4], name="|110>") b = TketSimShotBackend(ignore_measures=True) circ_compiled = b.get_compiled_circuit(circ) h = b.process_circuit(circ_compiled, n_shots=5) r = b.get_result(h) # TketSimShotBackend produces incorrect results with OpType::Measure # so we can't check if the assertions are successful assert "|001>" in r.get_debug_info() assert "|111>" in r.get_debug_info() assert "|110>" in r.get_debug_info() # TketSimShotBackend doesn't support RESET hence we can't # process circuits with stabiliser assertions and some # of the projector based assertions if __name__ == "__main__": test_assertion_init() test_assertion()
tket/pytket/tests/assertion_test.py/0
{ "file_path": "tket/pytket/tests/assertion_test.py", "repo_id": "tket", "token_count": 1494 }
365
# 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. import json import pytest from referencing import Registry from referencing.jsonschema import DRAFT7 from jsonschema import Draft7Validator, ValidationError # type: ignore from pathlib import Path from typing import Any, Dict, List from sympy import Expr from pytket.circuit import Node, Circuit, Qubit, OpType from pytket.predicates import Predicate from pytket.architecture import Architecture from pytket.placement import Placement, GraphPlacement import pytket.circuit_library as _library from pytket.passes import ( BasePass, SequencePass, RemoveRedundancies, RepeatUntilSatisfiedPass, CommuteThroughMultis, RepeatWithMetricPass, RebaseCustom, CXMappingPass, FullMappingPass, DefaultMappingPass, AASRouting, SquashCustom, ) from pytket.mapping import ( LexiLabellingMethod, LexiRouteRoutingMethod, MultiGateReorderRoutingMethod, BoxDecompositionRoutingMethod, ) from pytket.circuit.named_types import ParamType def standard_pass_dict(content: Dict[str, Any]) -> Dict[str, Any]: return {"StandardPass": content, "pass_class": "StandardPass"} def sequence_pass_dict(content: List[Dict[str, Any]]) -> Dict[str, Any]: return {"SequencePass": {"sequence": content}, "pass_class": "SequencePass"} def repeat_pass_dict(content: Dict[str, Any]) -> Dict[str, Any]: return {"RepeatPass": {"body": content}, "pass_class": "RepeatPass"} def repeat_until_satisfied_pass_dict( content: Dict[str, Any], pred: Dict[str, Any] ) -> Dict[str, Any]: return { "RepeatUntilSatisfiedPass": {"body": content, "predicate": pred}, "pass_class": "RepeatUntilSatisfiedPass", } def nonparam_pass_dict(name: str) -> Dict[str, Any]: return standard_pass_dict({"name": name}) def nonparam_predicate_dict(name: str) -> Dict[str, Any]: return {"type": name} example_routing_config = [ {"name": "LexiLabellingMethod"}, {"depth": 100, "name": "LexiRouteRoutingMethod"}, ] _arch = Architecture( [ (Node(0), Node(1)), (Node(1), Node(2)), (Node(2), Node(3)), (Node(3), Node(4)), (Node(4), Node(5)), ] ) example_architecture = _arch.to_dict() example_placement = Placement(_arch).to_dict() example_qmap = [ [Qubit(0).to_list(), Qubit(1).to_list()], [Qubit(1).to_list(), Qubit(0).to_list()], ] example_2q_circuit = Circuit(2).CX(0, 1).to_dict() example_1q_circuit = Circuit(1).X(0).to_dict() PARAM_PREDICATES: dict[str, dict[str, Any]] = { "GateSetPredicate": { "type": "GateSetPredicate", "allowed_types": ["CX", "Rx", "Rz"], }, "PlacementPredicate": { "type": "PlacementPredicate", "node_set": [Node(0).to_list(), Node(1).to_list()], }, "ConnectivityPredicate": { "type": "ConnectivityPredicate", "architecture": example_architecture, }, "DirectednessPredicate": { "type": "DirectednessPredicate", "architecture": example_architecture, }, "MaxNQubitsPredicate": {"type": "MaxNQubitsPredicate", "n_qubits": 10}, } NONPARAM_PREDICATES = [ "NoClassicalControlPredicate", "NoFastFeedforwardPredicate", "NoClassicalBitsPredicate", "NoWireSwapsPredicate", "MaxTwoQubitGatesPredicate", "CliffordCircuitPredicate", "DefaultRegisterPredicate", "NoBarriersPredicate", "CommutableMeasuresPredicate", "NoMidMeasurePredicate", "NoSymbolsPredicate", "GlobalPhasedXPredicate", "NormalisedTK2Predicate", ] PREDICATES = {name: nonparam_predicate_dict(name) for name in NONPARAM_PREDICATES} PREDICATES.update(PARAM_PREDICATES) # Parametrized passes that satisfy pass.from_dict(d).to_dict()==d TWO_WAY_PARAM_PASSES = { "KAKDecomposition": standard_pass_dict( { "name": "KAKDecomposition", "allow_swaps": True, "fidelity": 0.99, "target_2qb_gate": "CX", } ), "ThreeQubitSquash": standard_pass_dict( { "name": "ThreeQubitSquash", "allow_swaps": True, } ), "FullPeepholeOptimise": standard_pass_dict( { "name": "FullPeepholeOptimise", "allow_swaps": True, "target_2qb_gate": "CX", } ), "PeepholeOptimise2Q": standard_pass_dict( { "name": "PeepholeOptimise2Q", "allow_swaps": True, } ), "ComposePhasePolyBoxes": standard_pass_dict( { "name": "ComposePhasePolyBoxes", "min_size": 10, } ), "DecomposeBoxes": standard_pass_dict( { "name": "DecomposeBoxes", "excluded_types": ["QControlBox"], "excluded_opgroups": ["opgroup1"], } ), "EulerAngleReduction": standard_pass_dict( { "name": "EulerAngleReduction", "euler_p": "Rx", "euler_q": "Rz", "euler_strict": True, } ), "RoutingPass": standard_pass_dict( { "name": "RoutingPass", "architecture": example_architecture, "routing_config": example_routing_config, } ), "PlacementPass": standard_pass_dict( { "name": "PlacementPass", "placement": example_placement, } ), "NaivePlacementPass": standard_pass_dict( { "name": "NaivePlacementPass", "architecture": example_architecture, } ), "RenameQubitsPass": standard_pass_dict( { "name": "RenameQubitsPass", "qubit_map": example_qmap, } ), "CliffordSimp": standard_pass_dict( { "name": "CliffordSimp", "allow_swaps": True, } ), "DecomposeSwapsToCXs": standard_pass_dict( { "name": "DecomposeSwapsToCXs", "architecture": example_architecture, "directed": True, } ), "DecomposeSwapsToCircuit": standard_pass_dict( { "name": "DecomposeSwapsToCircuit", "swap_replacement": example_2q_circuit, } ), "OptimisePhaseGadgets": standard_pass_dict( { "name": "OptimisePhaseGadgets", "cx_config": "Snake", } ), "OptimisePairwiseGadgets": standard_pass_dict( { "name": "OptimisePairwiseGadgets", "cx_config": "Snake", } ), "PauliExponentials": standard_pass_dict( { "name": "PauliExponentials", "pauli_synth_strat": "Sets", "cx_config": "Snake", } ), "GuidedPauliSimp": standard_pass_dict( { "name": "GuidedPauliSimp", "pauli_synth_strat": "Sets", "cx_config": "Snake", } ), "SimplifyInitial": standard_pass_dict( { "name": "SimplifyInitial", "allow_classical": True, "create_all_qubits": True, } ), "SimplifyInitial with x_circuit set": standard_pass_dict( { "name": "SimplifyInitial", "allow_classical": True, "create_all_qubits": True, "x_circuit": example_1q_circuit, } ), "DelayMeasures": standard_pass_dict( { "name": "DelayMeasures", "allow_partial": False, } ), "RoundAngles": standard_pass_dict( {"name": "RoundAngles", "n": 6, "only_zeros": False} ), "GreedyPauliSimp": standard_pass_dict( {"name": "GreedyPauliSimp", "discount_rate": 0.4, "depth_weight": 0.5} ), # lists must be sorted by OpType value "AutoSquash": standard_pass_dict( {"name": "AutoSquash", "basis_singleqs": ["Rz", "TK1"]} ), "AutoRebase": standard_pass_dict( {"name": "AutoRebase", "basis_allowed": ["H", "TK1", "CX"], "allow_swaps": True} ), } # non-parametrized passes that satisfy pass.from_dict(d).to_dict()==d TWO_WAY_NONPARAM_PASSES = [ "CommuteThroughMultis", "DecomposeArbitrarilyControlledGates", "DecomposeMultiQubitsCX", "DecomposeSingleQubitsTK1", "RebaseTket", "RebaseUFR", "RemoveRedundancies", "SynthesiseTK", "SynthesiseTket", "SynthesiseUMD", "SquashTK1", "SquashRzPhasedX", "FlattenRegisters", "ZZPhaseToRz", "RemoveDiscarded", "SimplifyMeasured", "RemoveBarriers", "DecomposeBridges", "CnXPairwiseDecomposition", "RemoveImplicitQubitPermutation", ] TWO_WAY_PASSES = {name: nonparam_pass_dict(name) for name in TWO_WAY_NONPARAM_PASSES} TWO_WAY_PASSES.update(TWO_WAY_PARAM_PASSES) CUSTOM_TWO_WAY_PASSES = { "Simple SequencePass": sequence_pass_dict( [ TWO_WAY_PASSES["ThreeQubitSquash"], TWO_WAY_PASSES["NaivePlacementPass"], ] ), "Simple RepeatPass": repeat_pass_dict(TWO_WAY_PASSES["DecomposeBoxes"]), "Simple RepeatUntilSatisfiedPass": repeat_until_satisfied_pass_dict( TWO_WAY_PASSES["DecomposeBoxes"], PREDICATES["NoBarriersPredicate"] ), } TWO_WAY_PASSES.update(CUSTOM_TWO_WAY_PASSES) # Passes that don't satisfy pass.from_dict(d).to_dict()==d ONE_WAY_PASSES = { "FullMappingPass": standard_pass_dict( { "name": "FullMappingPass", "architecture": example_architecture, "placement": example_placement, "routing_config": example_routing_config, } ), "DefaultMappingPass": standard_pass_dict( { "name": "DefaultMappingPass", "architecture": example_architecture, "delay_measures": True, } ), "CXMappingPass": standard_pass_dict( { "name": "CXMappingPass", "architecture": example_architecture, "placement": example_placement, "routing_config": example_routing_config, "directed": True, "delay_measures": True, } ), "PauliSimp": standard_pass_dict( { "name": "PauliSimp", "pauli_synth_strat": "Sets", "cx_config": "Snake", } ), "PauliSquash": standard_pass_dict( { "name": "PauliSquash", "pauli_synth_strat": "Sets", "cx_config": "Snake", } ), "ContextSimp": standard_pass_dict( { "name": "ContextSimp", "allow_classical": True, "x_circuit": example_1q_circuit, } ), "DecomposeTK2": standard_pass_dict( { "name": "DecomposeTK2", "fidelities": { "CX": None, "ZZMax": 1.0, }, "allow_swaps": True, } ), } # Load the json schemas for testing # https://stackoverflow.com/a/61632081 curr_file_path = Path(__file__).resolve().parent schema_dir = curr_file_path.parent.parent / "schemas" with open(schema_dir / "compiler_pass_v1.json", "r") as f: pass_schema = json.load(f) with open(schema_dir / "circuit_v1.json", "r") as f: circ_schema = json.load(f) with open(schema_dir / "architecture_v1.json", "r") as f: arch_schema = json.load(f) with open(schema_dir / "placement_v1.json", "r") as f: plact_schema = json.load(f) with open(schema_dir / "predicate_v1.json", "r") as f: pred_schema = json.load(f) schema_store = [ (pass_schema["$id"], DRAFT7.create_resource(pass_schema)), (circ_schema["$id"], DRAFT7.create_resource(circ_schema)), (arch_schema["$id"], DRAFT7.create_resource(arch_schema)), (plact_schema["$id"], DRAFT7.create_resource(plact_schema)), (pred_schema["$id"], DRAFT7.create_resource(pred_schema)), ] registry: Registry = Registry().with_resources(schema_store) pass_validator = Draft7Validator(pass_schema, registry=registry) predicate_validator = Draft7Validator(pred_schema, registry=registry) def check_pass_serialisation( serialised_pass: Dict[str, Any], check_roundtrip: bool = True ) -> None: # Check the JSON is valid pass_validator.validate(serialised_pass) # Check the JSON can be deserialised tk_pass = BasePass.from_dict(serialised_pass) # Check the newly construct pass produces valid JSON new_serialised_pass = tk_pass.to_dict() pass_validator.validate(new_serialised_pass) # Optionally check for roundtrip if check_roundtrip: assert new_serialised_pass == serialised_pass def check_predicate_serialisation(serialised_predicate: Dict[str, Any]) -> None: # Check the JSON is valid predicate_validator.validate(serialised_predicate) # Check the JSON can be deserialised tk_predicate = Predicate.from_dict(serialised_predicate) # Check the newly construct predicate produces valid JSON new_serialised_predicate = tk_predicate.to_dict() predicate_validator.validate(new_serialised_predicate) # Check for roundtrip assert new_serialised_predicate == serialised_predicate def test_passes_roundtrip_serialisation() -> None: for k, p in TWO_WAY_PASSES.items(): try: check_pass_serialisation(p) except ValidationError as e: print(p) raise ValueError(f"Pass {k} failed serialisation test.") from e def test_passes_onw_way_serialisation() -> None: for k, p in ONE_WAY_PASSES.items(): try: check_pass_serialisation(p, check_roundtrip=False) except ValidationError as e: raise ValueError(f"Pass {k} failed serialisation test.") from e def test_predicate_serialisation() -> None: for k, p in PREDICATES.items(): try: check_predicate_serialisation(p) except ValidationError as e: raise ValueError(f"Predicate {k} failed serialisation test.") from e def test_invalid_pass_deserialisation() -> None: # Unknown pass p = standard_pass_dict( { "name": "UnknownPass", "architecture": example_architecture, } ) with pytest.raises(ValidationError) as e: check_pass_serialisation(p) err_msg = "'UnknownPass' is not one of" assert err_msg in str(e.value) # Wrong enum value p = standard_pass_dict( { "name": "PauliSimp", "pauli_synth_strat": "Wrong Strat", "cx_config": "Snake", } ) with pytest.raises(ValidationError) as e: check_pass_serialisation(p) err_msg = "'Wrong Strat' is not one of" assert err_msg in str(e.value) # Missing property p = standard_pass_dict( { "name": "PauliSimp", "cx_config": "Snake", } ) with pytest.raises(ValidationError) as e: check_pass_serialisation(p) err_msg = "'pauli_synth_strat' is a required property" assert err_msg in str(e.value) # Unsupported property p = standard_pass_dict( { "name": "PauliSimp", "pauli_synth_strat": "Sets", "cx_config": "Snake", "architecture": example_architecture, } ) with pytest.raises(ValidationError) as e: check_pass_serialisation(p) err_msg = "too many properties" assert err_msg in str(e.value) def test_invalid_predicate_deserialisation() -> None: # Unknown predicate p = { "type": "MyPredicate", "architecture": example_architecture, } with pytest.raises(ValidationError) as e: check_predicate_serialisation(p) err_msg = "'MyPredicate' is not one of" assert err_msg in str(e.value) # Missing property p = { "type": "ConnectivityPredicate", } with pytest.raises(ValidationError) as e: check_predicate_serialisation(p) err_msg = "'architecture' is a required property" assert err_msg in str(e.value) # Unsupported property p = { "type": "ConnectivityPredicate", "architecture": example_architecture, "allowed_types": ["CX", "Rx", "Rz"], } with pytest.raises(ValidationError) as e: check_predicate_serialisation(p) err_msg = "too many properties" assert err_msg in str(e.value) def check_arc_dict(arc: Architecture, d: dict) -> bool: links = [ {"link": [n1.to_list(), n2.to_list()], "weight": 1} for n1, n2 in arc.coupling ] if d["links"] != links: return False else: nodes = [Node(n[0], n[1]) for n in d["nodes"]] return set(nodes) == set(arc.nodes) def test_pass_deserialisation_only() -> None: # SquashCustom def sq(a: ParamType, b: ParamType, c: ParamType) -> Circuit: circ = Circuit(1) if c != 0: circ.Rz(c, 0) if b != 0: circ.Rx(b, 0) if a != 0: circ.Rz(a, 0) return circ squash_pass = SquashCustom({OpType.Rz, OpType.Rx, OpType.Ry}, sq) assert squash_pass.to_dict()["StandardPass"]["name"] == "SquashCustom" assert set(squash_pass.to_dict()["StandardPass"]["basis_singleqs"]) == { "Rz", "Rx", "Ry", } # RebaseCustom cx = Circuit(2) cx.CX(0, 1) pz_rebase = RebaseCustom( {OpType.CX, OpType.PhasedX, OpType.Rz}, cx, _library.TK1_to_TK1 ) assert pz_rebase.to_dict()["StandardPass"]["name"] == "RebaseCustom" assert set(pz_rebase.to_dict()["StandardPass"]["basis_allowed"]) == { "CX", "PhasedX", "Rz", } assert cx.to_dict() == pz_rebase.to_dict()["StandardPass"]["basis_cx_replacement"] def tk2_rep(a: ParamType, b: ParamType, c: ParamType) -> Circuit: return Circuit(2).ZZPhase(c, 0, 1).YYPhase(b, 0, 1).XXPhase(a, 0, 1) def tk1_rep(a: ParamType, b: ParamType, c: ParamType) -> Circuit: return Circuit(1).Rz(c, 0).Rx(b, 0).Rz(a, 0) # RebaseCustomViaTK2 rebase = RebaseCustom( {OpType.XXPhase, OpType.YYPhase, OpType.ZZPhase, OpType.Rx, OpType.Rz}, tk2_rep, tk1_rep, ) assert rebase.to_dict()["StandardPass"]["name"] == "RebaseCustomViaTK2" assert set(rebase.to_dict()["StandardPass"]["basis_allowed"]) == { "XXPhase", "YYPhase", "ZZPhase", "Rx", "Rz", } # FullMappingPass arc = Architecture([(0, 2), (1, 3), (2, 3), (2, 4)]) placer = GraphPlacement(arc) fm_pass = FullMappingPass( arc, placer, config=[ LexiLabellingMethod(), LexiRouteRoutingMethod(), MultiGateReorderRoutingMethod(), BoxDecompositionRoutingMethod(), ], ) assert fm_pass.to_dict()["pass_class"] == "SequencePass" assert isinstance(fm_pass, SequencePass) p_pass = fm_pass.get_sequence()[0] r_pass = fm_pass.get_sequence()[1] np_pass = fm_pass.get_sequence()[2] assert np_pass.to_dict()["StandardPass"]["name"] == "NaivePlacementPass" assert r_pass.to_dict()["StandardPass"]["name"] == "RoutingPass" assert p_pass.to_dict()["StandardPass"]["name"] == "PlacementPass" assert check_arc_dict(arc, r_pass.to_dict()["StandardPass"]["architecture"]) assert p_pass.to_dict()["StandardPass"]["placement"]["type"] == "GraphPlacement" assert r_pass.to_dict()["StandardPass"]["routing_config"] == [ {"name": "LexiLabellingMethod"}, { "name": "LexiRouteRoutingMethod", "depth": 10, }, { "name": "MultiGateReorderRoutingMethod", "depth": 10, "size": 10, }, {"name": "BoxDecompositionRoutingMethod"}, ] assert r_pass.to_dict()["StandardPass"]["routing_config"][3] == { "name": "BoxDecompositionRoutingMethod" } # DefaultMappingPass dm_pass = DefaultMappingPass(arc) assert dm_pass.to_dict()["pass_class"] == "SequencePass" assert isinstance(dm_pass, SequencePass) dm_pass_0 = dm_pass.get_sequence()[0] assert isinstance(dm_pass_0, SequencePass) p_pass = dm_pass_0.get_sequence()[0] r_pass = dm_pass_0.get_sequence()[1] np_pass = dm_pass_0.get_sequence()[2] d_pass = dm_pass.get_sequence()[1] assert d_pass.to_dict()["StandardPass"]["name"] == "DelayMeasures" assert d_pass.to_dict()["StandardPass"]["allow_partial"] == False assert p_pass.to_dict()["StandardPass"]["name"] == "PlacementPass" assert np_pass.to_dict()["StandardPass"]["name"] == "NaivePlacementPass" assert r_pass.to_dict()["StandardPass"]["name"] == "RoutingPass" assert check_arc_dict(arc, r_pass.to_dict()["StandardPass"]["architecture"]) assert p_pass.to_dict()["StandardPass"]["placement"]["type"] == "GraphPlacement" # DefaultMappingPass with delay_measures=False dm_pass = DefaultMappingPass(arc, False) assert dm_pass.to_dict()["pass_class"] == "SequencePass" assert isinstance(dm_pass, SequencePass) assert len(dm_pass.get_sequence()) == 3 p_pass = dm_pass.get_sequence()[0] r_pass = dm_pass.get_sequence()[1] np_pass = dm_pass.get_sequence()[2] assert p_pass.to_dict()["StandardPass"]["name"] == "PlacementPass" assert r_pass.to_dict()["StandardPass"]["name"] == "RoutingPass" assert np_pass.to_dict()["StandardPass"]["name"] == "NaivePlacementPass" assert check_arc_dict(arc, r_pass.to_dict()["StandardPass"]["architecture"]) assert p_pass.to_dict()["StandardPass"]["placement"]["type"] == "GraphPlacement" # AASRouting aas_pass = AASRouting(arc, lookahead=2) assert aas_pass.to_dict()["pass_class"] == "SequencePass" assert isinstance(aas_pass, SequencePass) comppba_plac_pass = aas_pass.get_sequence()[0] assert isinstance(comppba_plac_pass, SequencePass) aasrou_pass = aas_pass.get_sequence()[1] assert aasrou_pass.to_dict()["StandardPass"]["name"] == "AASRoutingPass" assert check_arc_dict(arc, aasrou_pass.to_dict()["StandardPass"]["architecture"]) assert ( comppba_plac_pass.get_sequence()[0].to_dict()["StandardPass"]["name"] == "ComposePhasePolyBoxes" ) assert ( comppba_plac_pass.get_sequence()[1].to_dict()["StandardPass"]["name"] == "PlacementPass" ) # CXMappingPass cxm_pass = CXMappingPass(arc, placer, directed_cx=True, delay_measures=True) assert cxm_pass.to_dict()["pass_class"] == "SequencePass" assert isinstance(cxm_pass, SequencePass) p0 = cxm_pass.get_sequence()[0] p1 = cxm_pass.get_sequence()[1] assert p0.to_dict()["pass_class"] == "SequencePass" assert p1.to_dict()["StandardPass"]["name"] == "DecomposeSwapsToCXs" assert p1.to_dict()["StandardPass"]["directed"] == True assert isinstance(p0, SequencePass) p00 = p0.get_sequence()[0] p01 = p0.get_sequence()[1] assert p00.to_dict()["pass_class"] == "SequencePass" assert p01.to_dict()["StandardPass"]["name"] == "RebaseCustom" assert p01.to_dict()["StandardPass"]["basis_cx_replacement"] == cx.to_dict() assert isinstance(p00, SequencePass) p000 = p00.get_sequence()[0] p001 = p00.get_sequence()[1] assert p000.to_dict()["pass_class"] == "SequencePass" assert p001.to_dict()["StandardPass"]["name"] == "DelayMeasures" assert p001.to_dict()["StandardPass"]["allow_partial"] == False assert isinstance(p000, SequencePass) p0000 = p000.get_sequence()[0] p0001 = p000.get_sequence()[1] assert p0000.to_dict()["StandardPass"]["name"] == "RebaseCustom" assert p0001.to_dict()["pass_class"] == "SequencePass" assert isinstance(p0001, SequencePass) p00010 = p0001.get_sequence()[0] p00011 = p0001.get_sequence()[1] assert p00010.to_dict()["StandardPass"]["name"] == "PlacementPass" assert p00011.to_dict()["StandardPass"]["name"] == "RoutingPass" assert check_arc_dict(arc, p00011.to_dict()["StandardPass"]["architecture"]) # RepeatWithMetricPass def number_of_CX(circ: Circuit) -> int: return circ.n_gates_of_type(OpType.CX) rp = RepeatWithMetricPass( SequencePass([CommuteThroughMultis(), RemoveRedundancies()]), number_of_CX ) assert rp.to_dict()["pass_class"] == "RepeatWithMetricPass" rp_pass = rp.get_pass() assert isinstance(rp_pass, SequencePass) sps = rp_pass.get_sequence() assert sps[0].to_dict()["StandardPass"]["name"] == "CommuteThroughMultis" assert sps[1].to_dict()["StandardPass"]["name"] == "RemoveRedundancies" cx = Circuit(2) cx.CX(0, 1) cx.CX(1, 0) assert number_of_CX(cx) == rp.get_metric()(cx) # RepeatUntilSatisfiedPass def no_CX(circ: Circuit) -> bool: return circ.n_gates_of_type(OpType.CX) == 0 rps = RepeatUntilSatisfiedPass( SequencePass([CommuteThroughMultis(), RemoveRedundancies()]), no_CX ) assert rps.to_dict()["pass_class"] == "RepeatUntilSatisfiedPass" rps_pass = rps.get_pass() assert isinstance(rps_pass, SequencePass) sps = rps_pass.get_sequence() assert sps[0].to_dict()["StandardPass"]["name"] == "CommuteThroughMultis" assert sps[1].to_dict()["StandardPass"]["name"] == "RemoveRedundancies" assert rps.get_predicate().__repr__() == "UserDefinedPredicate" assert ( rps.to_dict()["RepeatUntilSatisfiedPass"]["predicate"]["type"] == "UserDefinedPredicate" )
tket/pytket/tests/passes_serialisation_test.py/0
{ "file_path": "tket/pytket/tests/passes_serialisation_test.py", "repo_id": "tket", "token_count": 11772 }
366
OPENQASM 2.0; include "qelib1.inc"; qreg q[3]; rz(1.5*pi) q[4];
tket/pytket/tests/qasm_test_files/test2.qasm/0
{ "file_path": "tket/pytket/tests/qasm_test_files/test2.qasm", "repo_id": "tket", "token_count": 40 }
367
Inputs: 0:Qbit, 1:Qbit, 2:Qbit, 3:Qbit, 4:Cbit, 5:Cbit QGate["not"](0) with controls=[+1] with nocontrol QGate["X"](0) with controls=[+1,-2] with nocontrol QGate["Y"](0) with controls=[+3] QGate["X"](1) with controls=[+0,-2,+3] QGate["H"](2) QGate["iX"](0) QGate["Z"](3) QGate["Z"](2) with controls=[-0] QGate["H"](2) with controls=[+1] QGate["S"](2) QGate["S"]*(1) QGate["T"](1) QGate["T"]*(0) QRot["exp(-i%Z)",0.5](2) QRot["R(2pi/%)",3](2) QGate["omega"](1) QGate["E"](0) QGate["V"](1) QGate["E"]*(2) QGate["multinot"](0,1) with controls=[+2,-3] QGate["swap"](1,2) with nocontrol QGate["swap"](2,3) with controls=[+0] QGate["W"](1,2) QGate["V"]*(1) Outputs: 0:Qbit, 1:Qbit, 2:Qbit, 3:Qbit, 4:Cbit, 5:Cbit
tket/pytket/tests/quipper_test_files/test2.quip/0
{ "file_path": "tket/pytket/tests/quipper_test_files/test2.quip", "repo_id": "tket", "token_count": 385 }
368
Inputs: 0:Qbit QRot["exp(-i%Z)",0.5](0) Outputs: 0:Qbit
tket/pytket/tests/quipper_test_files/test4-6.quip/0
{ "file_path": "tket/pytket/tests/quipper_test_files/test4-6.quip", "repo_id": "tket", "token_count": 32 }
369
void init() {} typedef struct _twoints { unsigned x; unsigned y; } twoints; twoints divmod(unsigned x, unsigned y) { unsigned q, r; if (y == 0) { q = 0; r = 0; } else { q = x / y; r = x % y; } twoints result = {q, r}; return result; }
tket/pytket/tests/wasm-generation/wasmfromcpp/multivalue.c/0
{ "file_path": "tket/pytket/tests/wasm-generation/wasmfromcpp/multivalue.c", "repo_id": "tket", "token_count": 158 }
370
{ "$schema": "http://json-schema.org/draft-07/schema#", "$id": "http://cambridgequantum.com/schemas/tket/compiler_pass_v1.json", "type": "object", "description": "Serialization of a pytket compiler pass v1", "properties": { "pass_class": { "enum": [ "StandardPass", "SequencePass", "RepeatPass", "RepeatWithMetricPass", "RepeatUntilSatisfiedPass" ], "description": "The subclass of \"BasePass\" implemented, defining whether this is an elementary pass or some recursive combination of passes." }, "StandardPass": { "$ref": "#/definitions/StandardPass" }, "SequencePass": { "$ref": "#/definitions/SequencePass" }, "RepeatPass": { "$ref": "#/definitions/RepeatPass" }, "RepeatWithMetricPass": { "$ref": "#/definitions/RepeatWithMetricPass" }, "RepeatUntilSatisfiedPass": { "$ref": "#/definitions/RepeatUntilSatisfiedPass" } }, "required": [ "pass_class" ], "allOf": [ { "if": { "properties": { "pass_class": { "const": "StandardPass" } } }, "then": { "required": [ "StandardPass" ] } }, { "if": { "properties": { "pass_class": { "const": "SequencePass" } } }, "then": { "required": [ "SequencePass" ] } }, { "if": { "properties": { "pass_class": { "const": "RepeatPass" } } }, "then": { "required": [ "RepeatPass" ] } }, { "if": { "properties": { "pass_class": { "const": "RepeatWithMetricPass" } } }, "then": { "required": [ "RepeatWithMetricPass" ] } }, { "if": { "properties": { "pass_class": { "const": "RepeatUntilSatisfiedPass" } } }, "then": { "required": [ "RepeatUntilSatisfiedPass" ] } } ], "definitions": { "StandardPass": { "type": "object", "description": "Additional content to describe an elementary compiler pass.", "properties": { "name": { "type": "string", "enum": [ "RebaseCustom", "RebaseCustomViaTK2", "AutoRebase", "CommuteThroughMultis", "DecomposeArbitrarilyControlledGates", "DecomposeBoxes", "DecomposeMultiQubitsCX", "DecomposeSingleQubitsTK1", "PeepholeOptimise2Q", "RebaseTket", "RebaseUFR", "RemoveRedundancies", "SynthesiseTK", "SynthesiseTket", "SynthesiseOQC", "SynthesiseUMD", "SquashTK1", "SquashRzPhasedX", "AutoSquash", "FlattenRegisters", "DelayMeasures", "ZZPhaseToRz", "RemoveDiscarded", "SimplifyMeasured", "RemoveBarriers", "DecomposeBridges", "KAKDecomposition", "ThreeQubitSquash", "FullPeepholeOptimise", "ComposePhasePolyBoxes", "EulerAngleReduction", "RoutingPass", "PlacementPass", "NaivePlacementPass", "RenameQubitsPass", "CliffordSimp", "DecomposeSwapsToCXs", "DecomposeSwapsToCircuit", "OptimisePhaseGadgets", "OptimisePairwiseGadgets", "PauliSimp", "PauliExponentials", "GuidedPauliSimp", "SimplifyInitial", "FullMappingPass", "DefaultMappingPass", "CXMappingPass", "PauliSquash", "ContextSimp", "DecomposeTK2", "CnXPairwiseDecomposition", "RemoveImplicitQubitPermutation", "RoundAngles", "GreedyPauliSimp" ], "description": "The name of the compiler pass. Matches the name of the pytket method used to generate it. List all the passes as enum." }, "basis_allowed": { "type": "array", "items": { "type": "string" }, "description": "OpTypes of supported gates. Used in \"RebaseCustom\" and \"AutoRebase\"." }, "basis_singleqs": { "type": "array", "items": { "type": "string" }, "description": "OpTypes of supported single qubit gates. Used in \"SquashCustom\" and \"AutoSquash\"" }, "basis_cx_replacement": { "$ref": "circuit_v1.json#", "description": "A circuit implementing a CX gate in a target gate set. Used in \"RebaseCustom\"." }, "basis_tk1_replacement": { "type": "string", "description": "A method for generating optimised single-qubit unitary circuits in a target gate set. This string should be interpreted by Python \"dill\" into a function. Used in \"RebaseCustom\" and \"SquashCustom\"." }, "always_squash_symbols": { "type": "boolean", "description": "Whether to always squash symbolic gates regardless of the complexity blow-up. Used in \"SquashCustom\"." }, "euler_p": { "type": "string", "description": "The choice of P rotation for \"EulerAngleReduction\" for P-Q-P and Q-P-Q triples.", "enum": [ "Rx", "Ry", "Rz" ] }, "euler_q": { "type": "string", "description": "The choice of Q rotation for \"EulerAngleReduction\" for P-Q-P and Q-P-Q triples.", "enum": [ "Rx", "Ry", "Rz" ] }, "euler_strict": { "type": "boolean", "description": "False allows context-dependent reduction to just P-Q or Q-P by commuting the third rotation through the subsequent gate. Used in \"EulerAngleReduction\"." }, "allow_swaps": { "type": "boolean", "description": "Permit Clifford simplifications that introduce implicit swaps. Used in \"CliffordSimp\"." }, "qubit_map": { "type": "array", "description": "Map for renaming qubits in \"RenameQubitsPass\".", "items": { "type": "array", "items": [ { "$ref": "circuit_v1.json#/definitions/unitid" }, { "$ref": "circuit_v1.json#/definitions/unitid" } ] } }, "placement": { "$ref": "placement_v1.json#" }, "architecture": { "$ref": "architecture_v1.json#" }, "directed": { "type": "boolean", "description": "Whether to consider directedness of the architecture for CXs in \"DecomposeSwapsToCXs\"." }, "swap_replacement": { "$ref": "circuit_v1.json#" }, "fidelity": { "type": "number", "definition": "If <1, \"KAKDecomposition\" may not preserve semantics in order to optimise for the given CX fidelity.", "minimum": 0, "maximum": 1 }, "cx_config": { "type": "string", "enum": [ "Snake", "Tree", "Star" ], "definition": "A preference of CX configuration for building parities. Used in \"OptimisePhaseGadgets\", \"PauliSimp\", \"GuidedPauliSimp\", and \"PauliSquash\"." }, "pauli_synth_strat": { "type": "string", "enum": [ "Individual", "Pairwise", "Sets" ], "definition": "Whether to synthesise Pauli gadget sequences as individual rotations, pairwise, or in sets of commuting operations. Used in \"PauliSimp\", \"GuidedPauliSimp\", and \"PauliSquash\"." }, "allow_classical": { "type": "boolean", "description": "Whether to allow measurements on known states to be removed during \"SimplifyInitial\" and \"ContextSimp\"." }, "create_all_qubits": { "type": "boolean", "description": "Whether to automatically annotate all qubits as initialised to the zero state for \"SimplifyInitial\"." }, "x_circuit": { "$ref": "circuit_v1.json#" }, "delay_measures": { "type": "boolean", "description": "Whether to include a \"DelayMeasures\" pass in a \"CXMappingPass\"." }, "allow_partial": { "type": "boolean", "description": "Whether to allow partial delays in \"DelayMeasures\" when the circuit has non-commutable operations after the measure." }, "target_2qb_gate": { "type": "string", "enum": [ "CX", "TK2" ] }, "min_size": { "type": "integer", "description": "Minimal number of CX gates in each phase in \"ComposePhasePolyBoxes\"." }, "routing_config": { "$ref": "#/definitions/routing_config" }, "fidelities": { "type": "object", "description": "Gate fidelities in \"DecomposeTK2\".", "properties": { "CX": { "type": ["number", "null"], "minimum": 0, "maximum": 1 }, "ZZMax": { "type": ["number", "null"], "minimum": 0, "maximum": 1 } } }, "n": { "type": "integer", "description": "Level of precision applied in \"RoundAngles\"." }, "only_zeros": { "type": "boolean", "description": "Whether to restrict \"RoundAngles\" to rounding to zero." }, "excluded_types": { "type": "array", "items": { "type": "string" }, "description": "OpTypes excluded in \"DecomposeBoxes\"" }, "excluded_opgroups": { "type": "array", "items": { "type": "string" }, "description": "opgroups excluded in \"DecomposeBoxes\"" }, "discount_rate": { "type": "number", "definition": "parameter controlling cost discount in \"GreedyPauliSimp\"" }, "depth_weight": { "type": "number", "definition": "parameter controlling the degree of depth optimisation in \"GreedyPauliSimp\"" } }, "required": [ "name" ], "allOf": [ { "if": { "properties": { "name": { "const": "RebaseCustom" } } }, "then": { "required": [ "basis_allowed", "basis_cx_replacement", "basis_tk1_replacement" ], "maxProperties": 4 } }, { "if": { "properties": { "name": { "const": "AutoRebase" } } }, "then": { "required": [ "basis_allowed", "allow_swaps" ], "maxProperties": 3 } }, { "if": { "properties": { "name": { "const": "SquashCustom" } } }, "then": { "required": [ "basis_singleqs", "basis_tk1_replacement", "always_squash_symbols" ], "maxProperties": 4 } }, { "if": { "properties": { "name": { "const": "AutoSquash" } } }, "then": { "required": [ "basis_singleqs" ], "maxProperties": 2 } }, { "if": { "properties": { "name": { "const": "EulerAngleReduction" } } }, "then": { "required": [ "euler_p", "euler_q", "euler_strict" ], "maxProperties": 4 } }, { "if": { "properties": { "name": { "const": "KAKDecomposition" } } }, "then": { "required": [ "fidelity", "allow_swaps", "target_2qb_gate" ], "maxProperties": 4 } }, { "if": { "properties": { "name": { "const": "FullPeepholeOptimise" } } }, "then": { "required": [ "allow_swaps", "target_2qb_gate" ], "maxProperties": 3 } }, { "if": { "properties": { "name": { "const": "PeepholeOptimise2Q" } } }, "then": { "required": [ "allow_swaps" ], "maxProperties": 2 } }, { "if": { "properties": { "name": { "const": "ComposePhasePolyBoxes" } } }, "then": { "required": [ "min_size" ], "maxProperties": 2 } }, { "if": { "properties": { "name": { "const": "CliffordSimp" } } }, "then": { "required": [ "allow_swaps" ], "maxProperties": 2 } }, { "if": { "properties": { "name": { "const": "ThreeQubitSquash" } } }, "then": { "required": [ "allow_swaps" ], "maxProperties": 2 } }, { "if": { "properties": { "name": { "const": "OptimisePhaseGadgets" } } }, "then": { "required": [ "cx_config" ], "maxProperties": 2 } }, { "if": { "properties": { "name": { "const": "PauliSimp" } } }, "then": { "required": [ "pauli_synth_strat", "cx_config" ], "maxProperties": 3 } }, { "if": { "properties": { "name": { "const": "PauliExponentials" } } }, "then": { "required": [ "pauli_synth_strat", "cx_config" ], "maxProperties": 3 } }, { "if": { "properties": { "name": { "const": "GuidedPauliSimp" } } }, "then": { "required": [ "pauli_synth_strat", "cx_config" ], "maxProperties": 3 } }, { "if": { "properties": { "name": { "const": "SimplifyInitial" } } }, "then": { "required": [ "allow_classical", "create_all_qubits" ], "$comment": "TODO We need to make sure that the optional parameter must be x_circuit", "maxProperties": 4 } }, { "if": { "properties": { "name": { "const": "FlattenRelabelRegistersPass" } } }, "then": { "required": [ "label" ], "maxProperties": 2 } }, { "if": { "properties": { "name": { "const": "RenameQubitsPass" } } }, "then": { "required": [ "qubit_map" ], "maxProperties": 2 } }, { "if": { "properties": { "name": { "const": "PlacementPass" } } }, "then": { "required": [ "placement" ], "maxProperties": 2 } }, { "if": { "properties": { "name": { "const": "NaivePlacementPass" } } }, "then": { "required": [ "architecture" ], "maxProperties": 2 } }, { "if": { "properties": { "name": { "const": "CustomRoutingPass" } } }, "then": { "required": [ "architecture", "routing_config" ], "maxProperties": 3 } }, { "if": { "properties": { "name": { "const": "RoutingPass" } } }, "then": { "required": [ "architecture", "routing_config" ], "maxProperties": 3 } }, { "if": { "properties": { "name": { "const": "DecomposeSwapsToCXs" } } }, "then": { "required": [ "architecture", "directed" ], "maxProperties": 3 } }, { "if": { "properties": { "name": { "const": "DecomposeSwapsToCircuit" } } }, "then": { "required": [ "swap_replacement" ], "maxProperties": 2 } }, { "if": { "properties": { "name": { "const": "FullMappingPass" } } }, "then": { "required": [ "architecture", "placement", "routing_config" ], "maxProperties": 4 } }, { "if": { "properties": { "name": { "const": "DefaultMappingPass" } } }, "then": { "required": [ "architecture", "delay_measures" ], "maxProperties": 3 } }, { "if": { "properties": { "name": { "const": "CXMappingPass" } } }, "then": { "required": [ "architecture", "placement", "routing_config", "directed", "delay_measures" ], "maxProperties": 6 } }, { "if": { "properties": { "name": { "const": "PauliSquash" } } }, "then": { "required": [ "pauli_synth_strat", "cx_config" ], "maxProperties": 3 } }, { "if": { "properties": { "name": { "const": "ContextSimp" } } }, "then": { "required": [ "allow_classical", "x_circuit" ], "maxProperties": 3 } }, { "if": { "properties": { "name": { "const": "DelayMeasures" } } }, "then": { "required": [ "allow_partial" ], "maxProperties": 2 } }, { "if": { "properties": { "name": { "const": "RoundAngles" } } }, "then": { "required": [ "n", "only_zeros" ], "maxProperties": 3 } }, { "if": { "properties": { "name": { "const": "DecomposeBoxes" } } }, "then": { "required": [ "excluded_types", "excluded_opgroups" ], "maxProperties": 3 } }, { "if": { "properties": { "name": { "const": "GreedyPauliSimp" } } }, "then": { "required": [ "discount_rate", "depth_weight" ], "maxProperties": 3 } }, { "if": { "properties": { "name": { "$comment": "List all non-parametrized passes", "enum": [ "CommuteThroughMultis", "DecomposeArbitrarilyControlledGates", "DecomposeMultiQubitsCX", "DecomposeSingleQubitsTK1", "RebaseTket", "RebaseUFR", "RemoveRedundancies", "SynthesiseTK", "SynthesiseTket", "SynthesiseOQC", "SynthesiseUMD", "SquashTK1", "SquashRzPhasedX", "FlattenRegisters", "ZZPhaseToRz", "RemoveDiscarded", "SimplifyMeasured", "RemoveBarriers", "DecomposeBridges" ] } } }, "then": { "maxProperties": 1 } } ], "additionalProperties": false }, "SequencePass": { "type": "object", "description": "Additional content to describe a compiler pass that executes as a sequence of passes in order.", "properties": { "sequence": { "type": "array", "items": { "$ref": "#" }, "description": "The passes to be executed in order." } }, "required": [ "sequence" ], "additionalProperties": false }, "RepeatPass": { "type": "object", "description": "Additional content to describe a compiler pass that iterates another to a fixpoint.", "properties": { "body": { "$ref": "#", "description": "The body of the loop, to be iterated until no further change." } }, "required": [ "body" ], "additionalProperties": false }, "RepeatWithMetricPass": { "type": "object", "description": "Additional content to describe a compiler pass that iterates another whilst some metric decreases.", "properties": { "body": { "$ref": "#", "description": "The body of the loop." }, "metric": { "type": "string", "description": "The metric that conditions the loop, stored as a dill string of the python function." } }, "required": [ "body", "metric" ], "additionalProperties": false }, "RepeatUntilSatisfiedPass": { "type": "object", "description": "Additional content to describe a compiler pass that iterates another until some predicate is satisfied.", "properties": { "body": { "$ref": "#", "description": "The body of the loop." }, "predicate": { "$ref": "predicate_v1.json#", "description": "The predicate that conditions the loop. The loop is terminated when this predicate returns True." } }, "required": [ "body", "predicate" ], "additionalProperties": false }, "routingmethod": { "type": "object", "description": "A method used during circuit mapping.", "properties": { "name": { "type": "string", "description": "Name of method." } } }, "routing_config": { "type": "array", "description": "A configuration for routing defined by an array of RoutingMethod.", "items": { "$ref": "#/definitions/routingmethod" } } } }
tket/schemas/compiler_pass_v1.json/0
{ "file_path": "tket/schemas/compiler_pass_v1.json", "repo_id": "tket", "token_count": 15529 }
371
// 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. #pragma once #include <tktokenswap/DistancesInterface.hpp> #include <tktokenswap/SwapFunctions.hpp> #include "ArchitectureMapping.hpp" namespace tket { /** Directly get distances from an architecture object, * but evaluated lazily. */ class DistancesFromArchitecture : public DistancesInterface { public: /** The ArchitectureMapping object already handles the Node <-> vertex size_t * conversion. * @param arch_mapping Object containing a reference to an Architecture, * which has decided upon Node <-> vertex size_t conversions. */ explicit DistancesFromArchitecture(const ArchitectureMapping& arch_mapping); /** Get the distance from v1 to v2. Throws if distinct vertices return * distance 0, which probably means a disconnected graph. * @param vertex1 First vertex * @param vertex2 Second vertex * @return distance from v1 to v2 within the Architecture graph, throwing if * they are disconnected (so the distance is +infinity). */ virtual std::size_t operator()( std::size_t vertex1, std::size_t vertex2) override; /** May save computation time later; by some method, the caller * has determined a path from v1 to v2, and hence all along the path * we know the distance between any two points. * However, avoids quadratic time blowup by discarding some information * for long paths. * @param path A sequence [v0,v1, v2, ..., vn] of vertices, KNOWN to be a * shortest path from v0 to vn. The caller must not call this without being * SURE that it really is a shortest path, or incorrect results may occur. */ virtual void register_shortest_path( const std::vector<std::size_t>& path) override; /** The caller has determined that v1, v2 are adjacent, and therefore * the distance from v1 to v2 equals one. Store this. * @param vertex1 First vertex * @param vertex2 Second vertex */ virtual void register_edge(std::size_t vertex1, std::size_t vertex2) override; private: /** Reference to the original object passed into the constructor; * the caller must ensure that it remains valid and unchanged. */ const ArchitectureMapping& m_arch_mapping; /** The key is the vertex pair (v1, v2), but always sorted with v1<v2 * to use half the space. */ std::map<Swap, std::size_t> m_cached_distances; /** The main register_shortest_path wraps around this; we want to avoid * quadratic timings growth by cutting off long paths. * This stores the quadratic number of distances between all vertex pairs * within the given subpath. * @param path A sequence [v0,v1, v2, ..., vn] of vertices, * KNOWN to be a shortest path from v0 to vn. * @param begin The first index in path to use. * @param end Like end(), an index one past the last index in path to use. */ void register_shortest_path_with_limits( const std::vector<std::size_t>& path, std::size_t begin, std::size_t end); }; } // namespace tket
tket/tket/include/tket/Architecture/DistancesFromArchitecture.hpp/0
{ "file_path": "tket/tket/include/tket/Architecture/DistancesFromArchitecture.hpp", "repo_id": "tket", "token_count": 1086 }
372
// 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. #pragma once #include <cstddef> #include <list> #include <optional> #include <set> #include <string> #include <unordered_map> #include <unordered_set> #include <utility> #include <vector> #include "tket/OpType/EdgeType.hpp" #include "tket/Ops/Op.hpp" #include "tket/Utils/GraphHeaders.hpp" namespace tket { /** Description of a node in a circuit, representing some operation */ struct VertexProperties { Op_ptr op; /**< operation */ std::optional<std::string> opgroup; /**< operation group identfier */ VertexProperties( Op_ptr op = 0, std::optional<std::string> opgroup = std::nullopt) : op(op), opgroup(opgroup) {} }; /** A specific entry or exit port of a vertex */ typedef unsigned port_t; /** Whether a vertex port is out-going (source) or in-coming (target) */ enum class PortType { Source, Target }; /** Description of an edge in a circuit, representing a directional wire */ struct EdgeProperties { EdgeType type; /**< type of wire */ std::pair<port_t, port_t> ports; }; /** Graph representing a circuit, with operations as nodes. */ typedef boost::adjacency_list< // OutEdgeList boost::listS, // VertexList (use listS because we want to be able to remove vertices // without invalidating iterators) boost::listS, // we want access to incoming and outgoing edges boost::bidirectionalS, // indexing needed for algorithms such as topological sort boost::property<boost::vertex_index_t, std::size_t, VertexProperties>, EdgeProperties> DAG; typedef boost::graph_traits<DAG>::vertex_descriptor Vertex; typedef boost::graph_traits<DAG>::vertex_iterator V_iterator; typedef std::unordered_set<Vertex> VertexSet; typedef std::vector<Vertex> VertexVec; typedef std::list<Vertex> VertexList; typedef std::unordered_map<Vertex, std::size_t> IndexMap; typedef boost::adj_list_vertex_property_map< DAG, std::size_t, std::size_t&, boost::vertex_index_t> VIndex; /** * A vertex with an index. * * This can be used instead of a plain @ref Vertex in associative containers * where control over the order of iteration is required. */ typedef std::pair<std::size_t, Vertex> IVertex; typedef boost::graph_traits<DAG>::edge_descriptor Edge; typedef boost::graph_traits<DAG>::edge_iterator E_iterator; typedef DAG::in_edge_iterator E_in_iterator; typedef DAG::out_edge_iterator E_out_iterator; typedef std::set<Edge> EdgeSet; typedef std::vector<Edge> EdgeVec; typedef std::list<Edge> EdgeList; typedef std::pair<Vertex, port_t> VertPort; } // namespace tket
tket/tket/include/tket/Circuit/DAGDefs.hpp/0
{ "file_path": "tket/tket/include/tket/Circuit/DAGDefs.hpp", "repo_id": "tket", "token_count": 1074 }
373
// 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. #pragma once #include "tket/Circuit/Boxes.hpp" #include "tket/Circuit/CircUtils.hpp" #include "tket/Circuit/Circuit.hpp" #include "tket/Utils/HelperFunctions.hpp" #include "tket/Utils/Json.hpp" #include "tket/Utils/MatrixAnalysis.hpp" namespace tket { /** * PhasePolynomial is just a sequence of parities: that is, terms of the form * \f$ e^{\alpha \bigotimes Z} \f$, where Z is a Pauli Z. This is capable of * representing a restricted set of circuits made up of CNOTs and Rzs: * specifically, circuits where the output qubits have the same state as the * inputs, modulo (local) phases. The vectors are always assumed to be the same * size as the qubit count. */ typedef std::map<std::vector<bool>, Expr> PhasePolynomial; typedef std::pair<std::vector<bool>, Expr> phase_term_t; /* arXiv:1712.01859 : heuristic for synthesis of phase polynomial into a CNOT-dihedral circuit (ie CNOT + Rz). Architecture-blind. */ Circuit gray_synth( unsigned n_qubits, const std::list<phase_term_t> &parities, const MatrixXb &linear_transformation); /** * A PhasePolyBox is capable of representing arbitrary Circuits made up of CNOT * and RZ, as a PhasePolynomial plus a boolean matrix representing an additional * linear transformation. */ class PhasePolyBox : public Box { public: explicit PhasePolyBox(const Circuit &circ); explicit PhasePolyBox( unsigned n_qubits, const boost::bimap<Qubit, unsigned> &qubit_indices, const PhasePolynomial &phase_polynomial, const MatrixXb &linear_transformation); PhasePolyBox() : Box(OpType::PhasePolyBox) {} /** * Copy constructor */ PhasePolyBox(const PhasePolyBox &other); ~PhasePolyBox() override {} Op_ptr symbol_substitution( const SymEngine::map_basic_basic &sub_map) const override; SymSet free_symbols() const override; bool is_equal(const Op &op_other) const override { const PhasePolyBox &other = dynamic_cast<const PhasePolyBox &>(op_other); return ( this->n_qubits_ == other.n_qubits_ && this->phase_polynomial_ == other.phase_polynomial_ && this->linear_transformation_ == other.linear_transformation_ && this->qubit_indices_ == other.qubit_indices_); } const PhasePolynomial &get_phase_polynomial() const { return phase_polynomial_; } const MatrixXb &get_linear_transformation() const { return linear_transformation_; } const boost::bimap<Qubit, unsigned> &get_qubit_indices() const { return qubit_indices_; } unsigned get_n_qubits() const { return n_qubits_; } static Op_ptr from_json(const nlohmann::json &j); Circuit generate_circuit_with_original_placement() const; static nlohmann::json to_json(const Op_ptr &op); protected: // automatically uses GraySynth // (https://arxiv.org/pdf/1712.01859.pdf) // other circuit generation methods (for architectures) to come! void generate_circuit() const override; private: unsigned n_qubits_; boost::bimap<Qubit, unsigned> qubit_indices_; PhasePolynomial phase_polynomial_; MatrixXb linear_transformation_; }; /** * this class realises the conversion all sub circuits of a given circuits which * contains only CX+Rz to a PhasePolyBox. The circuit should contain only * CX, Rz, H, measure, reset, collape, barrier. */ class CircToPhasePolyConversion { public: /** * converts all sub circuits of a given circuits which contains only * CX+Rz to a PhasePolyBox. * @throw not implemented for unsupported gates * @param circ circuit to be converted * @param min_size value for the minimal number of CX in each box, groups with * less than min_size CX gates are not converted to a PhasePolyBox, default * value is 0 */ explicit CircToPhasePolyConversion( const Circuit &circ, unsigned min_size = 0); void convert(); Circuit get_circuit() const; private: enum class QubitType { pre, in, post }; void add_phase_poly_box(); unsigned nq_; unsigned nb_; unsigned min_size_; unsigned box_size_; std::map<Qubit, unsigned> qubit_indices_; std::map<Bit, unsigned> bit_indices_; std::vector<QubitType> qubit_types_; qubit_vector_t all_qu_; Circuit input_circ_; Circuit box_circ_; Circuit post_circ_; Circuit circ_; Circuit empty_circ_; }; } // namespace tket
tket/tket/include/tket/Converters/PhasePoly.hpp/0
{ "file_path": "tket/tket/include/tket/Converters/PhasePoly.hpp", "repo_id": "tket", "token_count": 1610 }
374
// 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. #pragma once #include <boost/graph/biconnected_components.hpp> #include <set> #include "tket/Graphs/ArticulationPoints_impl.hpp" /** * Computation of Articulation Points (APs) on undirected graphs * * This problem is of interest as we can use APs to maintain connectivity * requirements in Architectures and QubitGraphs. The BGL already provides an * implementation of this, but it does not quite satisfy our needs -- only a * loser definition of connectivity matters to us. The following will give more * details. * * Articulation Points (APs) are vertices in a graph that cannot be removed * without breaking the graph connectivity. * This concept is closely linked to biconnected components, i.e. connected * subgraphs in which removing any vertex will not affect the subgraph * connectivity. * * For a given graph G, we can then define a map `belong_to_comp` that * maps any vertex to the set of biconnected components it belongs to. Note that * any vertex v will belong to at least one biconnected component (which in the * worst case will contain a single vertex). It is a well-known graph * theoretical result that APs can equivalently be characterised as the vertices * that belong to more than one biconnected component. APs (and biconnected * components) can be efficiently computed in linear time O(V + E). * * For our needs, we replace the connectivity requirements in the definition of * APs to only consider subgraph connectivity: given a subgraph, we say that the * graph is subgraph-connected iff any two vertices of the subgraph are * connected in the graph G. I.e. instead of "vanilla" APs, we are only * interested in APs that break subgraph connectivity when removed: we call them * subgraph APs. Remark that i) the subgraph APs are necessarily contained in * the set of all APs of the graph, as our connectivity requirements are * strictly weaker. ii) the subgraph APs will not be elements of the subgraph in * general * * BGL implementation: * https://www.boost.org/doc/libs/1_75_0/libs/graph/doc/biconnected_components.html */ /** These functions only work for the UndirectedConnGraph graph type (typedef in * `ArticulationPoints_impl.hpp`) i.e. undirected graphs of DirectedGraph * objects They are not defined for BGL graphs in general * * The reason for this is that we need the vertices to have a UnitID property * to identify vertices from the main graph and the subgraph */ /** * Implementation specific details (in particular the class * detail::BicomponentGraph is in the file `ArticulationPoints_impl.hpp` */ namespace tket::graphs { /** Given a graph and a subgraph, returns the subgraph APs, as defined * in the introduction above */ template <typename T> std::set<T> get_subgraph_aps( const UndirectedConnGraph<T>& graph, const UndirectedConnGraph<T>& subgraph); // template explicit instations, with implementations in cpp file extern template std::set<UnitID> get_subgraph_aps( const UndirectedConnGraph<UnitID>& graph, const UndirectedConnGraph<UnitID>& subgraph); extern template std::set<Node> get_subgraph_aps( const UndirectedConnGraph<Node>& graph, const UndirectedConnGraph<Node>& subgraph); } // namespace tket::graphs
tket/tket/include/tket/Graphs/ArticulationPoints.hpp/0
{ "file_path": "tket/tket/include/tket/Graphs/ArticulationPoints.hpp", "repo_id": "tket", "token_count": 1074 }
375
// 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. #pragma once #include "tket/Mapping/LexiRoute.hpp" #include "tket/Mapping/RoutingMethod.hpp" namespace tket { class LexiRouteRoutingMethod : public RoutingMethod { public: /** * Checking and Routing methods redefined using LexiRoute. Only circuit depth, * corresponding to lookahead, is a required parameter. * * @param _max_depth Number of layers of gates checked inr outed subcircuit. */ LexiRouteRoutingMethod(unsigned _max_depth = 100); /** * @param mapping_frontier Contains boundary of routed/unrouted circuit for * modifying * @param architecture Architecture providing physical constraints * * @return True if modification made, map between relabelled Qubit, always * empty. * */ std::pair<bool, unit_map_t> routing_method( MappingFrontier_ptr& mapping_frontier, const ArchitecturePtr& architecture) const override; /** * @return Max depth used in lookahead */ unsigned get_max_depth() const; nlohmann::json serialize() const override; static LexiRouteRoutingMethod deserialize(const nlohmann::json& j); private: unsigned max_depth_; }; JSON_DECL(LexiRouteRoutingMethod); } // namespace tket
tket/tket/include/tket/Mapping/LexiRouteRoutingMethod.hpp/0
{ "file_path": "tket/tket/include/tket/Mapping/LexiRouteRoutingMethod.hpp", "repo_id": "tket", "token_count": 535 }
376
// 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. #pragma once #include <string> #include <typeindex> #include "tket/Architecture/Architecture.hpp" #include "tket/Transformations/Transform.hpp" namespace tket { class Predicate; typedef std::shared_ptr<Predicate> PredicatePtr; JSON_DECL(PredicatePtr) class IncorrectPredicate : public std::logic_error { public: explicit IncorrectPredicate(const std::string& exception_string) : std::logic_error(exception_string) {} }; class UnsatisfiedPredicate : public std::logic_error { public: explicit UnsatisfiedPredicate(const std::string& pred_name) : std::logic_error( "Predicate requirements are not satisfied: " + pred_name) {} }; class PredicateNotSerializable : public std::logic_error { public: explicit PredicateNotSerializable(const std::string& pred_name) : std::logic_error("Predicate not serializable: " + pred_name) {} }; const std::string& predicate_name(std::type_index idx); ///////////////////// // PREDICATE CLASSES// ///////////////////// // abstract interface class class Predicate { public: virtual bool verify(const Circuit& circ) const = 0; // implication currently only works between predicates of the same subclass virtual bool implies(const Predicate& other) const = 0; virtual PredicatePtr meet(const Predicate& other) const = 0; virtual std::string to_string() const = 0; virtual ~Predicate() {}; // satisfy compiler }; // all Predicate subclasses must inherit from `Predicate` /** * Asserts that all operations are in the specified set of types. * * Note that the following are always permitted and do not need to be included * in the permitted set: * - "meta" operations (inputs, outputs, barriers); * - OpType::Phase gates (which have no input or output wires). * * Classically conditioned operations are permitted provided that the * conditional operation is of a permitted type. */ class GateSetPredicate : public Predicate { public: explicit GateSetPredicate(const OpTypeSet& allowed_types) : allowed_types_(allowed_types) {} bool verify(const Circuit& circ) const override; bool implies(const Predicate& other) const override; PredicatePtr meet(const Predicate& other) const override; std::string to_string() const override; const OpTypeSet& get_allowed_types() const { return allowed_types_; } private: const OpTypeSet allowed_types_; }; /** * Asserts that there are no conditional gates in the circuit. */ class NoClassicalControlPredicate : public Predicate { public: bool verify(const Circuit& circ) const override; bool implies(const Predicate& other) const override; PredicatePtr meet(const Predicate& other) const override; std::string to_string() const override; }; class NoFastFeedforwardPredicate : public Predicate { // verifies Circuit has no classical bits which are written from quantum gates // and then read in later in the Circuit public: bool verify(const Circuit& circ) const override; bool implies(const Predicate& other) const override; PredicatePtr meet(const Predicate& other) const override; std::string to_string() const override; }; class NoClassicalBitsPredicate : public Predicate { // this verifies that the Circuit uses no classical bits // (read or write -- so no measures and no classical controls) public: bool verify(const Circuit& circ) const override; bool implies(const Predicate& other) const override; PredicatePtr meet(const Predicate& other) const override; std::string to_string() const override; }; class NoWireSwapsPredicate : public Predicate { /** * Verifies that you can follow the paths of each qubit/bit in the circuit * and finish on the same qubit/bit you started with */ public: bool verify(const Circuit& circ) const override; bool implies(const Predicate& other) const override; PredicatePtr meet(const Predicate& other) const override; std::string to_string() const override; }; class MaxTwoQubitGatesPredicate : public Predicate { // this verifies that the Circuit uses no gates with greater than 2 qubits // Barriers are ignored public: bool verify(const Circuit& circ) const override; bool implies(const Predicate& other) const override; PredicatePtr meet(const Predicate& other) const override; std::string to_string() const override; }; class PlacementPredicate : public Predicate { public: explicit PlacementPredicate(const Architecture& arch) : nodes_(arch.nodes()) {} explicit PlacementPredicate(const node_set_t& nodes) : nodes_(nodes) {} bool verify(const Circuit& circ) const override; bool implies(const Predicate& other) const override; PredicatePtr meet(const Predicate& other) const override; std::string to_string() const override; const node_set_t& get_nodes() const { return nodes_; } private: const node_set_t nodes_; }; class ConnectivityPredicate : public Predicate { public: explicit ConnectivityPredicate(const Architecture& arch) : arch_(arch) {} bool verify(const Circuit& circ) const override; bool implies(const Predicate& other) const override; PredicatePtr meet(const Predicate& other) const override; std::string to_string() const override; const Architecture& get_arch() const { return arch_; } private: const Architecture arch_; }; class DirectednessPredicate : public Predicate { public: explicit DirectednessPredicate(const Architecture& arch) : arch_(arch) {} bool verify(const Circuit& circ) const override; bool implies(const Predicate& other) const override; PredicatePtr meet(const Predicate& other) const override; std::string to_string() const override; const Architecture& get_arch() const { return arch_; } private: const Architecture arch_; }; class CliffordCircuitPredicate : public Predicate { public: bool verify(const Circuit& circ) const override; bool implies(const Predicate& other) const override; PredicatePtr meet(const Predicate& other) const override; std::string to_string() const override; }; class UserDefinedPredicate : public Predicate { public: explicit UserDefinedPredicate(const std::function<bool(const Circuit&)>& func) : func_(func) {} bool verify(const Circuit& circ) const override; bool implies(const Predicate&) const override; PredicatePtr meet(const Predicate&) const override; std::string to_string() const override; private: const std::function<bool(const Circuit&)> func_; }; class DefaultRegisterPredicate : public Predicate { public: bool verify(const Circuit& circ) const override; bool implies(const Predicate& other) const override; PredicatePtr meet(const Predicate& other) const override; std::string to_string() const override; }; class MaxNQubitsPredicate : public Predicate { public: explicit MaxNQubitsPredicate(unsigned n_qubits) : n_qubits_(n_qubits) {} bool verify(const Circuit& circ) const override; bool implies(const Predicate& other) const override; PredicatePtr meet(const Predicate& other) const override; std::string to_string() const override; unsigned get_n_qubits() const { return n_qubits_; } private: const unsigned n_qubits_; }; /** * Asserts that the circuit only contains N classical registers or less */ class MaxNClRegPredicate : public Predicate { public: explicit MaxNClRegPredicate(unsigned _n_cl_reg) : n_cl_reg_(_n_cl_reg) {} bool verify(const Circuit& circ) const override; bool implies(const Predicate& other) const override; PredicatePtr meet(const Predicate& other) const override; std::string to_string() const override; unsigned get_n_cl_reg() const { return n_cl_reg_; } private: const unsigned n_cl_reg_; }; /** * Asserts that the circuit contains no \ref OpType::Barrier */ class NoBarriersPredicate : public Predicate { public: bool verify(const Circuit& circ) const override; bool implies(const Predicate& other) const override; PredicatePtr meet(const Predicate& other) const override; std::string to_string() const override; }; /** * Asserts that any internal measurements can be commuted to the end of the * circuit */ class CommutableMeasuresPredicate : public Predicate { public: bool verify(const Circuit& circ) const override; bool implies(const Predicate& other) const override; PredicatePtr meet(const Predicate& other) const override; std::string to_string() const override; }; /** * Asserts that any measurements occur at the end of the circuit */ class NoMidMeasurePredicate : public Predicate { public: bool verify(const Circuit& circ) const override; bool implies(const Predicate& other) const override; PredicatePtr meet(const Predicate& other) const override; std::string to_string() const override; }; /** * Asserts that no gates in the circuit have symbolic parameters */ class NoSymbolsPredicate : public Predicate { public: bool verify(const Circuit& circ) const override; bool implies(const Predicate& other) const override; PredicatePtr meet(const Predicate& other) const override; std::string to_string() const override; }; /** * Asserts that all NPhasedX gates act on all qubits * In the future, it might be useful to have a generic GlobalGatePredicate * for other global gates, or flag some gates as global */ class GlobalPhasedXPredicate : public Predicate { public: bool verify(const Circuit& circ) const override; bool implies(const Predicate& other) const override; PredicatePtr meet(const Predicate& other) const override; std::string to_string() const override; }; /** * Asserts that all TK2 gates are normalised * * A gate TK2(a, b, c) is considered normalised if * * - If all expressions are non symbolic, then it must hold * `0.5 โ‰ฅ a โ‰ฅ b โ‰ฅ |c|`. * - In the ordering (a, b, c), any symbolic expression must appear before * non-symbolic ones. The remaining non-symbolic expressions must still be * ordered in non-increasing order and must be in the interval [0, 1/2], * with the exception of the last one that may be in [-1/2, 1/2]. */ class NormalisedTK2Predicate : public Predicate { public: bool verify(const Circuit& circ) const override; bool implies(const Predicate& other) const override; PredicatePtr meet(const Predicate& other) const override; std::string to_string() const override; }; } // namespace tket
tket/tket/include/tket/Predicates/Predicates.hpp/0
{ "file_path": "tket/tket/include/tket/Predicates/Predicates.hpp", "repo_id": "tket", "token_count": 3090 }
377
// 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. #pragma once #include "Transform.hpp" namespace tket { namespace Transforms { // decomposes multiq gates not in the gate set to CXs, then replaces CXs with // the replacement (if CX is not allowed) then converts singleq gates no in // the gate set to U3 and replaces them using provided function Expects: any // gates Produces: gates in allowed_gates Transform rebase_factory( const OpTypeSet& allowed_gates, const Circuit& cx_replacement, const std::function<Circuit(const Expr&, const Expr&, const Expr&)>& tk1_replacement); Transform rebase_factory_via_tk2( const OpTypeSet& allowed_gates, const std::function<Circuit(const Expr&, const Expr&, const Expr&)>& tk1_replacement, const std::function<Circuit(const Expr&, const Expr&, const Expr&)>& tk2_replacement); // Multiqs: CX // Singleqs: TK1 Transform rebase_tket(); // Multiqs: CZ // Singleqs: PhasedX, Rz Transform rebase_cirq(); // Multiqs: CZ // Singleqs: Rx, Rz Transform rebase_quil(); // Multiqs: SWAP, CX, CZ // Singleqs: H, X, Z, S, T, Rx, Rz Transform rebase_pyzx(); // Multiqs: SWAP, CRz, CX, CZ // Singleqs: H, X, Y, Z, S, T, V, Rx, Ry, Rz Transform rebase_projectq(); // Used for UniversalFrameRandomisation // Multiqs: CX // Singleqs: Rz, H Transform rebase_UFR(); // Multiqs: ZZMax // Singleqs: Rz, PhasedX Transform rebase_HQS(); // Multiqs: TK2 // Singleqs: TK1 Transform rebase_TK(); // Multiqs: XXPhase // Singleqs: Rz, PhasedX Transform rebase_UMD(); // Multiqs: AAMS // Singleqs: GPI, GPI2 Transform rebase_ionq(); } // namespace Transforms } // namespace tket
tket/tket/include/tket/Transformations/Rebase.hpp/0
{ "file_path": "tket/tket/include/tket/Transformations/Rebase.hpp", "repo_id": "tket", "token_count": 770 }
378
// 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. #pragma once #include "tket/Utils/Constants.hpp" #include "tket/Utils/EigenConfig.hpp" #include "tket/Utils/Expression.hpp" #include "tket/Utils/Json.hpp" #include "tket/Utils/UnitID.hpp" namespace tket { /** Symbols for the Pauli operators (and identity) */ enum Pauli { I, X, Y, Z }; NLOHMANN_JSON_SERIALIZE_ENUM( Pauli, { {Pauli::I, "I"}, {Pauli::X, "X"}, {Pauli::Y, "Y"}, {Pauli::Z, "Z"}, }); /** * Whenever a decomposition choice of Pauli gadgets is presented, * users may use either Snake (a.k.a. cascade, ladder), Tree (i.e. CX * balanced tree) or Star (i.e. CXs target a common qubit). */ enum class CXConfigType { Snake, Tree, Star, MultiQGate }; NLOHMANN_JSON_SERIALIZE_ENUM( CXConfigType, {{CXConfigType::Snake, "Snake"}, {CXConfigType::Tree, "Tree"}, {CXConfigType::Star, "Star"}, {CXConfigType::MultiQGate, "MultiQGate"}}); typedef Eigen::SparseMatrix<Complex, Eigen::ColMajor> CmplxSpMat; /******************************************************************************* * SCALAR COEFFICIENTS ******************************************************************************/ /** * A trivial option for PauliTensor to represent Pauli strings up to global * scalar. * * Treated as +1 for casting to other coefficients and matrix evaluation. */ struct no_coeff_t {}; JSON_DECL(no_coeff_t) /** * A fourth root of unity {1, i, -1, -i}, represented as an unsigned integer * giving the power of i. * * E.g. val % 4: * 0: +1 * 1: +i * 2: -1 * 3: -i * * These are the phase coefficients generated in the Pauli group. Whilst * stabilisers are restricted to {1, -1}, the imaginary numbers are required for * closure under multiplication. For settings where a real value is needed, use * PauliTensor::is_real_negative() which asserts the value is real (throws an * exception otherwise) and returns a bool value to distinguish. */ typedef unsigned quarter_turns_t; /** * Other options for scalar coefficients include: * * Complex; floating-point complex number. Mostly used by the python binder to * present a phaseful interface with guaranteed success on converting to a * sparse matrix. * * Expr; a symbolic expression for a (possibly complex) coefficient. This tends * to be used in the context of Pauli exponentials of tracking the rotation * angle (along with its phase), where such synthesis functions map cP to * exp(i*cP*pi/2) (i.e. the coefficient is the angle of rotation in half-turns). */ /** * Returns the default coefficient value (scalar 1) for each coefficient type. * * @retval {} (no_coeff_t) * @retval 0 (quarter_turns_t) * @retval 1. (Complex) * @retval 1 (Expr) */ template <typename CoeffType> CoeffType default_coeff() = delete; template <> no_coeff_t default_coeff<no_coeff_t>(); template <> quarter_turns_t default_coeff<quarter_turns_t>(); template <> Complex default_coeff<Complex>(); template <> Expr default_coeff<Expr>(); /** * Cast a coefficient to a different type. * * Casting to no_coeff_t just drops the coefficient to focus on the string. * Casting from no_coeff_t treats it as the scalar 1. * * Casting to quarter_turns_t throws an exception if value is not in the range * {1, i, -1, -i}. * * Casting from Expr throws an exception if the coefficient is symbolic. * * @param coeff The coefficient to cast to another type. */ template <typename OriginalCoeff, typename NewCoeff> NewCoeff cast_coeff(const OriginalCoeff &coeff) = delete; template <> no_coeff_t cast_coeff<no_coeff_t, no_coeff_t>(const no_coeff_t &); template <> quarter_turns_t cast_coeff<no_coeff_t, quarter_turns_t>(const no_coeff_t &); template <> Complex cast_coeff<no_coeff_t, Complex>(const no_coeff_t &); template <> Expr cast_coeff<no_coeff_t, Expr>(const no_coeff_t &); template <> no_coeff_t cast_coeff<quarter_turns_t, no_coeff_t>(const quarter_turns_t &); template <> quarter_turns_t cast_coeff<quarter_turns_t, quarter_turns_t>( const quarter_turns_t &coeff); template <> Complex cast_coeff<quarter_turns_t, Complex>(const quarter_turns_t &coeff); template <> Expr cast_coeff<quarter_turns_t, Expr>(const quarter_turns_t &coeff); template <> no_coeff_t cast_coeff<Complex, no_coeff_t>(const Complex &); template <> quarter_turns_t cast_coeff<Complex, quarter_turns_t>(const Complex &coeff); template <> Complex cast_coeff<Complex, Complex>(const Complex &coeff); template <> Expr cast_coeff<Complex, Expr>(const Complex &coeff); template <> no_coeff_t cast_coeff<Expr, no_coeff_t>(const Expr &); template <> quarter_turns_t cast_coeff<Expr, quarter_turns_t>(const Expr &coeff); template <> Complex cast_coeff<Expr, Complex>(const Expr &coeff); template <> Expr cast_coeff<Expr, Expr>(const Expr &coeff); /** * Compare two coefficients of the same type with respect to an ordering. * * All values of no_coeff_t are equal. * Values of quarter_turns_t are compared modulo 4. * Values of Complex are compared lexicographically by the real part and then * imaginary. * Non-symbolic values of Expr are compared as Complex, symbolic * values are compared by the canonical form of SymEngine expressions. * * @param first A coefficient. * @param second Another coefficient of the same type. * @retval -1 first < second * @retval 0 first == second * @retval 1 first > second */ template <typename CoeffType> int compare_coeffs(const CoeffType &first, const CoeffType &second) = delete; template <> int compare_coeffs<no_coeff_t>(const no_coeff_t &, const no_coeff_t &); template <> int compare_coeffs<quarter_turns_t>( const quarter_turns_t &first, const quarter_turns_t &second); template <> int compare_coeffs<Complex>(const Complex &first, const Complex &second); template <> int compare_coeffs<Expr>(const Expr &first, const Expr &second); template <typename CoeffType> void print_coeff(std::ostream &os, const CoeffType &coeff) = delete; /** * Generates the coefficient prefix for PauliTensor::to_str() */ template <> void print_coeff<no_coeff_t>(std::ostream &, const no_coeff_t &); template <> void print_coeff<quarter_turns_t>( std::ostream &os, const quarter_turns_t &coeff); template <> void print_coeff<Complex>(std::ostream &os, const Complex &coeff); template <> void print_coeff<Expr>(std::ostream &os, const Expr &coeff); /** * Hash a coefficient, combining it with an existing hash of another structure. */ template <typename CoeffType> void hash_combine_coeff(std::size_t &seed, const CoeffType &coeff) = delete; template <> void hash_combine_coeff<no_coeff_t>(std::size_t &, const no_coeff_t &); template <> void hash_combine_coeff<quarter_turns_t>( std::size_t &seed, const quarter_turns_t &coeff); template <> void hash_combine_coeff<Complex>(std::size_t &seed, const Complex &coeff); template <> void hash_combine_coeff<Expr>(std::size_t &seed, const Expr &coeff); /** * Multiply together two coefficients of the same type. * * Multiplication of no_coeff_t is trivial. * Multiplication of quarter_turns_t adds the unsigned values (e^{i*a*pi/2} * * e^{i*b*pi/2} = e^{i*(a+b)*pi/2}). Multiplication of Complex/Expr is standard * multiplication. */ template <typename CoeffType> CoeffType multiply_coeffs(const CoeffType &first, const CoeffType &second) = delete; template <> no_coeff_t multiply_coeffs<no_coeff_t>(const no_coeff_t &, const no_coeff_t &); template <> quarter_turns_t multiply_coeffs<quarter_turns_t>( const quarter_turns_t &first, const quarter_turns_t &second); template <> Complex multiply_coeffs<Complex>(const Complex &first, const Complex &second); template <> Expr multiply_coeffs<Expr>(const Expr &first, const Expr &second); /******************************************************************************* * PAULI CONTAINERS ******************************************************************************/ /** * A sparse, Qubit-indexed Pauli container. * * A QubitPauliMap is generally treated the same as if all Pauli::I entries were * removed. */ typedef std::map<Qubit, Pauli> QubitPauliMap; /** * A dense, unsigned-indexed Pauli container. * * A DensePauliMap is generally treated the same regardless of any Pauli::Is * padded at the end. Each qubit index is treated as the corresponding Qubit id * from the default register. * * In future work, it may be interesting to consider * a symplectic representation (representing each Pauli by a pair of bits * representing X and Z) for both speed and memory efficiency. */ typedef std::vector<Pauli> DensePauliMap; /** * Cast between two different Pauli container types. * * Casting into a type with restricted indices (e.g. DensePauliMap expecting * default register qubits) may throw an exception. * * @param cont The Pauli container to convert to another type. */ template <typename OriginalContainer, typename NewContainer> NewContainer cast_container(const OriginalContainer &cont) = delete; template <> QubitPauliMap cast_container<QubitPauliMap, QubitPauliMap>( const QubitPauliMap &cont); template <> QubitPauliMap cast_container<DensePauliMap, QubitPauliMap>( const DensePauliMap &cont); template <> DensePauliMap cast_container<QubitPauliMap, DensePauliMap>( const QubitPauliMap &cont); template <> DensePauliMap cast_container<DensePauliMap, DensePauliMap>( const DensePauliMap &cont); /** * Compare two Pauli containers of the same type for ordering. * * Individual Paulis are ordered alphabetically as I < X < Y < Z. * Strings are ordered lexicographically, IZ < ZI (Zq[1] < Zq[0]). * * @param first A Pauli container * @param second Another Pauli container of the same type. * @retval -1 first < second * @retval 0 first == second * @retval 1 first > second */ template <typename PauliContainer> int compare_containers( const PauliContainer &first, const PauliContainer &second) = delete; template <> int compare_containers<QubitPauliMap>( const QubitPauliMap &first, const QubitPauliMap &second); template <> int compare_containers<DensePauliMap>( const DensePauliMap &first, const DensePauliMap &second); /** * Find the set of Qubits on which \p first and \p second have the same * non-trivial Pauli (X, Y, Z). */ std::set<Qubit> common_qubits( const QubitPauliMap &first, const QubitPauliMap &second); /** * Find the set of qubits (as unsigned integer indices) on which \p first and \p * second have the same non-trivial Pauli (X, Y, Z). */ std::set<unsigned> common_indices( const DensePauliMap &first, const DensePauliMap &second); /** * Find the set of Qubits on which \p first has a non-trivial Pauli (X, Y, Z) * but \p second either doesn't contain or maps to I. */ std::set<Qubit> own_qubits( const QubitPauliMap &first, const QubitPauliMap &second); /** * Find the set of qubits (as unsigned integer indices) on which \p first has a * non-trivial Pauli (X, Y, Z) but \p second either doesn't contain (>= size) or * maps to I. */ std::set<unsigned> own_indices( const DensePauliMap &first, const DensePauliMap &second); /** * Find the set of Qubits on which \p first and \p second have distinct * non-trivial Paulis (X, Y, Z). */ std::set<Qubit> conflicting_qubits( const QubitPauliMap &first, const QubitPauliMap &second); /** * Find the set of qubits (as unsigned integer indices) on which \p first and \p * second have distinct non-trivial Paulis (X, Y, Z). */ std::set<unsigned> conflicting_indices( const DensePauliMap &first, const DensePauliMap &second); /** * Return whether two Pauli containers commute as Pauli strings (there are an * even number of qubits on which they have distinct non-trivial Paulis). */ template <typename PauliContainer> bool commuting_containers( const PauliContainer &first, const PauliContainer &second) = delete; template <> bool commuting_containers<QubitPauliMap>( const QubitPauliMap &first, const QubitPauliMap &second); template <> bool commuting_containers<DensePauliMap>( const DensePauliMap &first, const DensePauliMap &second); /** * Generates the readable Pauli string portion of PauliTensor::to_str(). * * Dense strings are printed as e.g. XIYZ. * Sparse strings are printed as e.g. (Xq[0], Yq[2], Zq[3]). */ template <typename PauliContainer> void print_paulis(std::ostream &os, const PauliContainer &paulis) = delete; template <> void print_paulis<QubitPauliMap>(std::ostream &os, const QubitPauliMap &paulis); template <> void print_paulis<DensePauliMap>(std::ostream &os, const DensePauliMap &paulis); /** * Hash a Pauli container, combining it with an existing hash of another * structure. */ template <typename PauliContainer> void hash_combine_paulis(std::size_t &seed, const PauliContainer &paulis) = delete; template <> void hash_combine_paulis<QubitPauliMap>( std::size_t &seed, const QubitPauliMap &paulis); template <> void hash_combine_paulis<DensePauliMap>( std::size_t &seed, const DensePauliMap &paulis); /** * Return the number of Pauli::Ys in the container. Used for * PauliTensor::transpose(). */ template <typename PauliContainer> unsigned n_ys(const PauliContainer &paulis) = delete; template <> unsigned n_ys<QubitPauliMap>(const QubitPauliMap &paulis); template <> unsigned n_ys<DensePauliMap>(const DensePauliMap &paulis); /** * Returns a const reference to a lookup table for multiplying individual * Paulis. * * Maps {p0, p1} -> {k, p2} where p0*p1 = e^{i*k*pi/2}*p2, e.g. {Pauli::X, * Pauli::Y} -> {1, Pauli::Z} (X*Y = iZ). */ const std::map<std::pair<Pauli, Pauli>, std::pair<quarter_turns_t, Pauli>> & get_mult_matrix(); /** * Multiplies two Pauli containers component-wise, returning both the resulting * phase and string. * * Maps {P0, P1} -> {k, P2} where P0*P1 = e^{i*k*pi/2}*P2, e.g. {XIY, YZY} -> * {1, ZZI} (XIY*YZY = iZZI). */ template <typename PauliContainer> std::pair<quarter_turns_t, PauliContainer> multiply_strings( const PauliContainer &first, const PauliContainer &second) = delete; template <> std::pair<quarter_turns_t, QubitPauliMap> multiply_strings<QubitPauliMap>( const QubitPauliMap &first, const QubitPauliMap &second); template <> std::pair<quarter_turns_t, DensePauliMap> multiply_strings<DensePauliMap>( const DensePauliMap &first, const DensePauliMap &second); /** * Evaluates a Pauli container to a sparse matrix describing the tensor product * of each Pauli in the string. * * The matrix gives the operator in ILO-BE format, e.g. (Zq[0], Xq[1]): * 0 1 0 0 * 1 0 0 0 * 0 0 0 -1 * 0 0 -1 0 * * For sparse Pauli containers, just those qubits present in the container will * be treated as part of the Pauli string (e.g. (Zq[1], Iq[2]) is treated as ZI * since q[0] is ignored but q[2] is present in the string), so it is often * preferred to use the other variants which explicitly provide the expected * qubits. */ template <typename PauliContainer> CmplxSpMat to_sparse_matrix(const PauliContainer &paulis) = delete; template <> CmplxSpMat to_sparse_matrix<QubitPauliMap>(const QubitPauliMap &paulis); template <> CmplxSpMat to_sparse_matrix<DensePauliMap>(const DensePauliMap &paulis); /** * Evaluates a Pauli container to a sparse matrix describing the tensor product * of each Pauli in the string. * * Qubits are restricted to the default register, from q[0] to q[ \p n_qubits - * 1], then presents the operator in ILO-BE format (if a sparse container * contains Qubits outside of this range or not in the default register, an * exception is thrown). E.g. (Zq[0]), 2: * 1 0 0 0 * 0 -1 0 0 * 0 0 1 0 * 0 0 0 -1 */ template <typename PauliContainer> CmplxSpMat to_sparse_matrix(const PauliContainer &paulis, unsigned n_qubits) = delete; template <> CmplxSpMat to_sparse_matrix<QubitPauliMap>( const QubitPauliMap &paulis, unsigned n_qubits); template <> CmplxSpMat to_sparse_matrix<DensePauliMap>( const DensePauliMap &paulis, unsigned n_qubits); /** * Evaluates a Pauli container to a sparse matrix describing the tensor product * of each Pauli in the string. * * \p qubits dictates the order of the qubits in the tensor product, with the * operator returned in Big Endian format. E.g. (Zq[0], Xq[1]), [q[1], q[0]]: * 0 0 1 0 * 0 0 0 -1 * 1 0 0 0 * 0 -1 0 0 */ template <typename PauliContainer> CmplxSpMat to_sparse_matrix( const PauliContainer &paulis, const qubit_vector_t &qubits) = delete; template <> CmplxSpMat to_sparse_matrix<QubitPauliMap>( const QubitPauliMap &paulis, const qubit_vector_t &qubits); template <> CmplxSpMat to_sparse_matrix<DensePauliMap>( const DensePauliMap &paulis, const qubit_vector_t &qubits); /******************************************************************************* * PauliTensor TEMPLATE CLASS ******************************************************************************/ /** * PauliTensor<PauliContainer, CoeffType> * * A unified type for tensor products of Pauli operators, possibly with some * global scalar coefficient. It is parameterised in two ways: * - PauliContainer describes the data structure used to map qubits to Paulis. * This may be sparse or dense, and indexed by arbitrary Qubits or unsigneds * (referring to indices in the default register). * - CoeffType describes the kind of coefficient stored, ranging from no data to * restricted values, to symbolic expressions. * * Each implementation should be interoperable by casting. Some methods may only * be available for certain specialisations. */ template <typename PauliContainer, typename CoeffType> class PauliTensor { static_assert( std::is_same<PauliContainer, QubitPauliMap>::value || std::is_same<PauliContainer, DensePauliMap>::value, "PauliTensor must be either dense or qubit-indexed."); static_assert( std::is_same<CoeffType, no_coeff_t>::value || std::is_same<CoeffType, quarter_turns_t>::value || std::is_same<CoeffType, Complex>::value || std::is_same<CoeffType, Expr>::value, "PauliTensor must either support no coefficient, quarter turns, or " "arbitrary complex (floating point or symbolic) coefficients."); static const CoeffType default_coeff; public: PauliContainer string; CoeffType coeff; /** * Default constructor, giving the empty Pauli string with unit scalar. */ PauliTensor() : string(), coeff(default_coeff) {} /** * Constructor directly instantiating the Pauli string and coefficient. */ PauliTensor( const PauliContainer &_string, const CoeffType &_coeff = default_coeff) : string(_string), coeff(_coeff) {} /** * Convenience constructor for an individual Pauli in a sparse representation. */ template <typename PC = PauliContainer> PauliTensor( const Qubit &q, Pauli p, const CoeffType &_coeff = default_coeff, typename std::enable_if<std::is_same<PC, QubitPauliMap>::value>::type * = 0) : string({{q, p}}), coeff(_coeff) {} /** * Convenience constructor to immediately cast a dense Pauli string on the * default register to a sparse representation. */ template <typename PC = PauliContainer> PauliTensor( const DensePauliMap &_string, const CoeffType &_coeff = default_coeff, typename std::enable_if<std::is_same<PC, QubitPauliMap>::value>::type * = 0) : string(cast_container<DensePauliMap, QubitPauliMap>(_string)), coeff(_coeff) {} /** * Constructor for sparse representations which zips together an ordered list * of Qubits and Paulis. */ template <typename PC = PauliContainer> PauliTensor( const std::list<Qubit> &qubits, const std::list<Pauli> &paulis, const CoeffType &_coeff = default_coeff, typename std::enable_if<std::is_same<PC, QubitPauliMap>::value>::type * = 0) : string(), coeff(_coeff) { if (qubits.size() != paulis.size()) { throw std::logic_error( "Mismatch of Qubits and Paulis upon QubitPauliString " "construction"); } std::list<Pauli>::const_iterator p_it = paulis.begin(); for (const Qubit &qb : qubits) { Pauli p = *p_it; if (string.find(qb) != string.end()) { throw std::logic_error( "Non-unique Qubit inserted into QubitPauliString map"); } string[qb] = p; ++p_it; } } /** * Casting operator between different specialisations of PauliTensor. Casts * the Pauli container and coefficient separately. */ template <typename CastContainer, typename CastCoeffType> operator PauliTensor<CastContainer, CastCoeffType>() const { return PauliTensor<CastContainer, CastCoeffType>( cast_container<PauliContainer, CastContainer>(string), cast_coeff<CoeffType, CastCoeffType>(coeff)); } /** * Compares two PauliTensors of the same type in lexicographical order by the * Paulis first, then coefficients. * * Ordering rules for each of the Pauli containers or coefficient types may * vary. * * @param other Another PauliTensor of the same type. * @retval -1 this < other * @retval 0 this == other * @retval 1 this > other */ int compare(const PauliTensor<PauliContainer, CoeffType> &other) const { int cont_comp = compare_containers<PauliContainer>(this->string, other.string); if (cont_comp != 0) return cont_comp; return compare_coeffs<CoeffType>(this->coeff, other.coeff); } bool operator==(const PauliTensor<PauliContainer, CoeffType> &other) const { return (compare(other) == 0); } bool operator!=(const PauliTensor<PauliContainer, CoeffType> &other) const { return !(*this == other); } bool operator<(const PauliTensor<PauliContainer, CoeffType> &other) const { return compare(other) < 0; } /** * Checks for equivalence of PauliTensors, explicitly taking the coefficient * modulo \p n * * This is useful for treatment of Pauli exponentials, where the coefficient * becomes the rotation angle under exponentiation and so is unchanged under * some modulus. */ template <typename CT = CoeffType> typename std::enable_if<std::is_same<CT, Expr>::value, bool>::type equiv_mod( const PauliTensor<PauliContainer, CoeffType> &other, unsigned n) const { int cont_comp = compare_containers<PauliContainer>(this->string, other.string); return (cont_comp == 0) && equiv_expr(this->coeff, other.coeff, n); } /** * Compress a sparse PauliTensor by removing identity terms. */ template <typename PC = PauliContainer> typename std::enable_if<std::is_same<PC, QubitPauliMap>::value>::type compress() { QubitPauliMap::iterator it = string.begin(); while (it != string.end()) { if (it->second == Pauli::I) it = string.erase(it); else ++it; } } /** * Checks commutation of two PauliTensors by evaluating how many Qubits have * anti-commuting Paulis in the string. */ template <typename OtherCoeffType> bool commutes_with( const PauliTensor<PauliContainer, OtherCoeffType> &other) const { return commuting_containers<PauliContainer>(string, other.string); } /** * Find the set of Qubits on which this and \p other have the same * non-trivial Pauli (X, Y, Z). */ template <typename OtherCoeffType, typename PC = PauliContainer> typename std::enable_if< std::is_same<PC, QubitPauliMap>::value, std::set<Qubit>>::type common_qubits( const PauliTensor<PauliContainer, OtherCoeffType> &other) const { return tket::common_qubits(string, other.string); } /** * Find the set of Qubits on which this has a non-trivial Pauli (X, Y, Z) * but \p other either doesn't contain or maps to I. */ template <typename OtherCoeffType, typename PC = PauliContainer> typename std::enable_if< std::is_same<PC, QubitPauliMap>::value, std::set<Qubit>>::type own_qubits(const PauliTensor<PauliContainer, OtherCoeffType> &other) const { return tket::own_qubits(string, other.string); } /** * Find the set of Qubits on which this and \p other have distinct * non-trivial Paulis (X, Y, Z). */ template <typename OtherCoeffType, typename PC = PauliContainer> typename std::enable_if< std::is_same<PC, QubitPauliMap>::value, std::set<Qubit>>::type conflicting_qubits( const PauliTensor<PauliContainer, OtherCoeffType> &other) const { return tket::conflicting_qubits(string, other.string); } /** * Find the set of qubits (as unsigned integer indices) on which this and * \p other have the same non-trivial Pauli (X, Y, Z). */ template <typename OtherCoeffType, typename PC = PauliContainer> typename std::enable_if< std::is_same<PC, DensePauliMap>::value, std::set<unsigned>>::type common_indices( const PauliTensor<PauliContainer, OtherCoeffType> &other) const { return tket::common_indices(string, other.string); } /** * Find the set of qubits (as unsigned integer indices) on which this has a * non-trivial Pauli (X, Y, Z) but \p other either doesn't contain (>= size) * or maps to I. */ template <typename OtherCoeffType, typename PC = PauliContainer> typename std::enable_if< std::is_same<PC, DensePauliMap>::value, std::set<unsigned>>::type own_indices(const PauliTensor<PauliContainer, OtherCoeffType> &other) const { return tket::own_indices(string, other.string); } /** * Find the set of qubits (as unsigned integer indices) on which this and * \p other have distinct non-trivial Paulis (X, Y, Z). */ template <typename OtherCoeffType, typename PC = PauliContainer> typename std::enable_if< std::is_same<PC, DensePauliMap>::value, std::set<unsigned>>::type conflicting_indices( const PauliTensor<PauliContainer, OtherCoeffType> &other) const { return tket::conflicting_indices(string, other.string); } /** * Gets the Pauli at the given index within the string. * * For sparse representations, returns Pauli::I if index is not present. */ template <typename PC = PauliContainer> typename std::enable_if<std::is_same<PC, QubitPauliMap>::value, Pauli>::type get(const Qubit &qb) const { QubitPauliMap::const_iterator i = string.find(qb); if (i == string.end()) return Pauli::I; else return i->second; } template <typename PC = PauliContainer> typename std::enable_if<std::is_same<PC, DensePauliMap>::value, Pauli>::type get(unsigned qb) const { if (qb >= string.size()) return Pauli::I; else return string.at(qb); } /** * Sets the Pauli at the given index within the string. */ template <typename PC = PauliContainer> typename std::enable_if<std::is_same<PC, QubitPauliMap>::value>::type set( const Qubit &qb, Pauli p) { QubitPauliMap::iterator i = string.find(qb); if (i == string.end()) { if (p != Pauli::I) string.insert({qb, p}); } else { if (p == Pauli::I) string.erase(i); else i->second = p; } } template <typename PC = PauliContainer> typename std::enable_if<std::is_same<PC, DensePauliMap>::value>::type set( unsigned qb, Pauli p) { if (qb >= string.size()) string.resize(qb + 1, Pauli::I); string.at(qb) = p; } /** * Asserts coefficient is real, and returns whether it is negative. * * quarter_turns_t is used as the coefficient to restrict to the Pauli group. * This is most commonly used for stabiliser methods, in which case valid * coefficients must be +-1. It is common in such representations for these to * be distinguished just by a single phase bit which is true if negative, * false if positive. This method immediately gives that phase bit. * * @retval true if coeff % 4 == 2 (coefficient is -1) * @retval false if coeff % 4 == 0 (coefficient is +1) */ template <typename CT = CoeffType> typename std::enable_if<std::is_same<CT, quarter_turns_t>::value, bool>::type is_real_negative() const { switch (coeff % 4) { case 0: { return false; } case 2: { return true; } default: { throw std::logic_error( "is_real_negative() called on a PauliTensor with imaginary phase"); } } } /** * A human-readable form of the PauliTensor, incorporating the coefficient and * Pauli string. Format may depend on the type specialisations. */ std::string to_str() const { std::stringstream ss; print_coeff<CoeffType>(ss, coeff); print_paulis<PauliContainer>(ss, string); return ss.str(); } /** * Hash the PauliTensor. */ std::size_t hash_value() const { std::size_t seed = 0; hash_combine_paulis<PauliContainer>(seed, string); hash_combine_coeff<CoeffType>(seed, coeff); return seed; } /** * Update this to the transpose by negating the coefficient if the string * contains an odd number of Pauli::Ys. */ void transpose() { if (n_ys<PauliContainer>(string) % 2 == 1) coeff = multiply_coeffs<CoeffType>( coeff, cast_coeff<quarter_turns_t, CoeffType>(2)); } /** * Qubit-wise multiplication of two PauliTensors of the same type. */ PauliTensor<PauliContainer, CoeffType> operator*( const PauliTensor<PauliContainer, CoeffType> &other) const { std::pair<quarter_turns_t, PauliContainer> prod = multiply_strings<PauliContainer>(this->string, other.string); CoeffType new_coeff = multiply_coeffs<CoeffType>(this->coeff, other.coeff); new_coeff = multiply_coeffs<CoeffType>( new_coeff, cast_coeff<quarter_turns_t, CoeffType>(prod.first)); return PauliTensor<PauliContainer, CoeffType>(prod.second, new_coeff); } /** * Returns the set of free symbols in a symbolic PauliTensor. */ template <typename CT = CoeffType> typename std::enable_if<std::is_same<CT, Expr>::value, SymSet>::type free_symbols() const { return expr_free_symbols(coeff); } /** * Replaces given symbols with values in a symbolic PauliTensor. */ template <typename CT = CoeffType> typename std::enable_if< std::is_same<CT, Expr>::value, PauliTensor<PauliContainer, CoeffType>>::type symbol_substitution(const SymEngine::map_basic_basic &sub_map) const { return PauliTensor<PauliContainer, CoeffType>(string, coeff.subs(sub_map)); } /** * Returns the size of the underlying Pauli string. * * This is taken directly from the container, so may include some qubits * mapped to Pauli::I and vary around calling PauliTensor::compress(). */ unsigned size() const { return string.size(); } /** * Evaluates a PauliTensor to a sparse matrix describing the tensor product * of each Pauli in the string. Throws an exception if the coefficient is * symbolic. * * The matrix gives the operator in ILO-BE format, e.g. (Zq[0], Xq[1]): * 0 1 0 0 * 1 0 0 0 * 0 0 0 -1 * 0 0 -1 0 * * For sparse Pauli containers, just those qubits present in the container * will be treated as part of the Pauli string (e.g. (Zq[1], Iq[2]) is treated * as ZI since q[0] is ignored but q[2] is present in the string), so it is * often preferred to use the other variants which explicitly provide the * expected qubits. */ CmplxSpMat to_sparse_matrix() const { return cast_coeff<CoeffType, Complex>(coeff) * tket::to_sparse_matrix<PauliContainer>(string); } /** * Evaluates a PauliTensor to a sparse matrix describing the tensor product * of each Pauli in the string. Throws an exception if the coefficient is * symbolic. * * Qubits are restricted to the default register, from q[0] to q[ \p n_qubits * - 1], then presents the operator in ILO-BE format (if a sparse container * contains Qubits outside of this range or not in the default register, an * exception is thrown). E.g. (Zq[0]), 2: * 1 0 0 0 * 0 -1 0 0 * 0 0 1 0 * 0 0 0 -1 */ CmplxSpMat to_sparse_matrix(const unsigned n_qubits) const { return cast_coeff<CoeffType, Complex>(coeff) * tket::to_sparse_matrix<PauliContainer>(string, n_qubits); } /** * Evaluates a PauliTensor to a sparse matrix describing the tensor product * of each Pauli in the string. Throws an exception if the coefficient is * symbolic. * * \p qubits dictates the order of the qubits in the tensor product, with the * operator returned in Big Endian format. E.g. (Zq[0], Xq[1]), [q[1], q[0]]: * 0 0 1 0 * 0 0 0 -1 * 1 0 0 0 * 0 -1 0 0 */ CmplxSpMat to_sparse_matrix(const qubit_vector_t &qubits) const { return cast_coeff<CoeffType, Complex>(coeff) * tket::to_sparse_matrix<PauliContainer>(string, qubits); } /** * Applies the PauliTensor to a given statevector by matrix multiplication. * * Determines the number of qubits from the size of the statevector, and * assumes default register qubits in ILO-BE format. */ Eigen::VectorXcd dot_state(const Eigen::VectorXcd &state) const { // allowing room for big states unsigned long long n = state.size(); if (!(n && (!(n & (n - 1))))) throw std::logic_error("Statevector size is not a power of two."); unsigned n_qubits = 0; while (n) { n >>= 1; ++n_qubits; } --n_qubits; return (to_sparse_matrix(n_qubits) * state); } /** * Applies the PauliTensor to a given statevector by matrix multiplication. * * \p qubits dictates the order of Qubits in the state, assuming a Big Endian * format. An exception is thrown if the size of the state does not match up * with the number of Qubits given. */ Eigen::VectorXcd dot_state( const Eigen::VectorXcd &state, const qubit_vector_t &qubits) const { if (state.size() != 1 << qubits.size()) throw std::logic_error( "Size of statevector does not match number of qubits passed to " "dot_state"); return (to_sparse_matrix(qubits) * state); } /** * Determines the expectation value of a given statevector with respect to the * PauliTensor by matrix multiplication. * * Determines the number of qubits from the size of the statevector, and * assumes default register qubits in ILO-BE format. */ Complex state_expectation(const Eigen::VectorXcd &state) const { return state.dot(dot_state(state)); } /** * Determines the expectation value of a given statevector with respect to the * PauliTensor by matrix multiplication. * * \p qubits dictates the order of Qubits in the state, assuming a Big Endian * format. An exception is thrown if the size of the state does not match up * with the number of Qubits given. */ Complex state_expectation( const Eigen::VectorXcd &state, const qubit_vector_t &qubits) const { return state.dot(dot_state(state, qubits)); } }; // Initialise default coefficient template <typename PauliContainer, typename CoeffType> const CoeffType PauliTensor<PauliContainer, CoeffType>::default_coeff = tket::default_coeff<CoeffType>(); template <typename PauliContainer, typename CoeffType> void to_json( nlohmann::json &j, const PauliTensor<PauliContainer, CoeffType> &tensor) { j["string"] = tensor.string; j["coeff"] = tensor.coeff; } template <typename PauliContainer, typename CoeffType> void from_json( const nlohmann::json &j, PauliTensor<PauliContainer, CoeffType> &tensor) { tensor = PauliTensor<PauliContainer, CoeffType>( j.at("string").get<PauliContainer>(), j.at("coeff").get<CoeffType>()); } /******************************************************************************* * PauliTensor SPECIALISATION TYPEDEFS ******************************************************************************/ typedef PauliTensor<QubitPauliMap, no_coeff_t> SpPauliString; typedef PauliTensor<DensePauliMap, no_coeff_t> PauliString; typedef PauliTensor<QubitPauliMap, quarter_turns_t> SpPauliStabiliser; typedef PauliTensor<DensePauliMap, quarter_turns_t> PauliStabiliser; typedef PauliTensor<QubitPauliMap, Complex> SpCxPauliTensor; typedef PauliTensor<DensePauliMap, Complex> CxPauliTensor; typedef PauliTensor<QubitPauliMap, Expr> SpSymPauliTensor; typedef PauliTensor<DensePauliMap, Expr> SymPauliTensor; typedef std::vector<PauliStabiliser> PauliStabiliserVec; } // namespace tket
tket/tket/include/tket/Utils/PauliTensor.hpp/0
{ "file_path": "tket/tket/include/tket/Utils/PauliTensor.hpp", "repo_id": "tket", "token_count": 13326 }
379
// 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 "tket/ArchAwareSynth/SteinerTree.hpp" namespace tket { namespace aas { // Steiner Tree generation follows the method of Takahashi and // Matsuyama et al. see // https://en.wikipedia.org/wiki/Steiner_tree_problem#Approximating_the_Steiner_tree SteinerTree::SteinerTree( const PathHandler& pathhandler, std::list<unsigned>& nodes_to_add, unsigned root_node) { root = root_node; last_operation_cost = 0; init_tree(pathhandler, nodes_to_add); while (!nodes_to_add.empty()) { add_closest_node_to_tree(pathhandler, nodes_to_add); } tree_cost = calculate_cost(); } unsigned SteinerTree::calculate_cost() const { unsigned cost = 0; for (SteinerNodeType nt : node_types) { switch (nt) { case SteinerNodeType::ZeroInTree: { cost += 2; break; } case SteinerNodeType::OneInTree: { ++cost; break; } case SteinerNodeType::Leaf: { ++cost; break; } default: { // no action occurs break; } } } if (cost > 0) --cost; return cost; } unsigned SteinerTree::get_max_element() const { unsigned maxelement = 0; for (unsigned i = 0; i < node_types.size(); ++i) { if (node_types[i] != SteinerNodeType::OutOfTree) maxelement = i; } return maxelement; } std::vector<unsigned> SteinerTree::nodes() const { std::vector<unsigned> tree_nodes; for (unsigned i = 0; i < node_types.size(); ++i) { if (node_types[i] != SteinerNodeType::OutOfTree) { tree_nodes.push_back(i); } } return tree_nodes; } void SteinerTree::init_tree( const PathHandler& pathhandler, std::list<unsigned>& nodes_to_add) { if (nodes_to_add.empty()) throw std::logic_error("Cannot initialise empty Steiner Tree."); unsigned n = pathhandler.get_connectivity_matrix().rows(); node_types = std::vector<SteinerNodeType>(n, SteinerNodeType::OutOfTree); num_neighbours = std::vector<unsigned>(n, 0); if (nodes_to_add.size() == 1) { node_types[nodes_to_add.front()] = SteinerNodeType::Leaf; // A single root is considered a leaf tree_nodes = nodes_to_add; nodes_to_add.clear(); } else if (nodes_to_add.size() > 1) { // determine the shortest path unsigned node1 = nodes_to_add.front(), node2 = nodes_to_add.back(); unsigned min_distance = pathhandler.get_distance_matrix()(node1, node2); for (unsigned no1 : nodes_to_add) { for (unsigned no2 : nodes_to_add) { if (no1 != no2) { unsigned distance = pathhandler.get_distance_matrix()(no1, no2); if (distance < min_distance) { node1 = no1; node2 = no2; min_distance = distance; } } } } // neighbours must both be leaves if (pathhandler.get_distance_matrix()(node1, node2) == 1) { node_types[node1] = SteinerNodeType::Leaf; node_types[node2] = SteinerNodeType::Leaf; num_neighbours[node1] = 1; num_neighbours[node2] = 1; tree_nodes.push_back(node1); tree_nodes.push_back(node2); } // otherwise, 0 nodes exist between. else { node_types[node1] = SteinerNodeType::Leaf; num_neighbours[node1] = 1; tree_nodes.push_back(node1); add_path_to_tree(pathhandler, node1, node2); } nodes_to_add.remove(node1); nodes_to_add.remove(node2); } } void SteinerTree::add_path_to_tree( const PathHandler& pathhandler, unsigned node_in_tree, unsigned node_to_add) { // last node is a leaf, with one neighbor node_types[node_to_add] = SteinerNodeType::Leaf; num_neighbours[node_to_add] = 1; tree_nodes.push_back(node_to_add); if ((node_in_tree == pathhandler.get_size()) || (node_to_add == pathhandler.get_size())) { throw std::logic_error("searching for a node which is not in the tree"); } if (pathhandler.get_distance_matrix()(node_in_tree, node_to_add) < pathhandler.get_distance_matrix()(node_to_add, node_in_tree)) { if (pathhandler.get_path_matrix()(node_to_add, node_in_tree) == pathhandler.get_size()) { node_in_tree = pathhandler.get_path_matrix()(node_in_tree, node_to_add); } else { node_in_tree = pathhandler.get_path_matrix()(node_to_add, node_in_tree); } if ((node_in_tree == pathhandler.get_size()) || (node_to_add == pathhandler.get_size())) { throw std::logic_error("searching for a node which is not in the tree"); } while (node_in_tree != node_to_add) { // node in a path = zero node, it has two neighbbors node_types[node_in_tree] = SteinerNodeType::ZeroInTree; tree_nodes.push_back(node_in_tree); num_neighbours[node_in_tree] = 2; if (pathhandler.get_path_matrix()(node_to_add, node_in_tree) == pathhandler.get_size()) { node_in_tree = pathhandler.get_path_matrix()(node_in_tree, node_to_add); } else { node_in_tree = pathhandler.get_path_matrix()(node_to_add, node_in_tree); } if ((node_in_tree == pathhandler.get_size()) || (node_to_add == pathhandler.get_size())) { throw std::logic_error("searching for a node which is not in the tree"); } } } else { if (pathhandler.get_path_matrix()(node_to_add, node_in_tree) == pathhandler.get_size()) { node_to_add = pathhandler.get_path_matrix()(node_in_tree, node_to_add); } else { node_to_add = pathhandler.get_path_matrix()(node_to_add, node_in_tree); } if ((node_in_tree == pathhandler.get_size()) || (node_to_add == pathhandler.get_size())) { throw std::logic_error("searching for a node which is not in the tree"); } while (node_in_tree != node_to_add) { node_types[node_to_add] = SteinerNodeType::ZeroInTree; // node in a path = zero node tree_nodes.push_back(node_to_add); num_neighbours[node_to_add] = 2; // it has two neighbbors if (pathhandler.get_path_matrix()(node_to_add, node_in_tree) == pathhandler.get_size()) { node_to_add = pathhandler.get_path_matrix()(node_in_tree, node_to_add); } else { node_to_add = pathhandler.get_path_matrix()(node_to_add, node_in_tree); } if ((node_in_tree == pathhandler.get_size()) || (node_to_add == pathhandler.get_size())) { throw std::logic_error("searching for a node which is not in the tree"); } } } } void SteinerTree::add_closest_node_to_tree( const PathHandler& pathhandler, std::list<unsigned>& nodes_to_add) { unsigned closest_node = 0; unsigned distant_node = UINT_MAX; // initialise to "infinity" unsigned closest_tree_node( tree_nodes.front()); // closest steiner point to the nodes we want to add std::list<unsigned>::iterator itr1; std::list<unsigned>::iterator itr2; // take the two closest points (one of the tree, the other among the // nodes_to_add) for (unsigned node_to_add : nodes_to_add) { for (unsigned tree_node : tree_nodes) { if (pathhandler.get_distance_matrix()(tree_node, node_to_add) < distant_node) // graph is oriented, we want distance // tree->nodes_to_add { closest_node = node_to_add; closest_tree_node = tree_node; distant_node = pathhandler.get_distance_matrix()(tree_node, node_to_add); } } } nodes_to_add.remove(closest_node); // if the node of the tree is a leaf, then its a one node after adding the // new node if (node_types[closest_tree_node] == SteinerNodeType::Leaf) { node_types[closest_tree_node] = SteinerNodeType::OneInTree; } ++num_neighbours[closest_tree_node]; add_path_to_tree(pathhandler, closest_tree_node, closest_node); } // assumes i & j are neighbouring vertices int SteinerTree::cost_of_operation(unsigned i, unsigned j) const { SteinerNodeType i_type = node_types[i]; SteinerNodeType j_type = node_types[j]; // tedious case analysis switch (i_type) { case SteinerNodeType::ZeroInTree: { switch (j_type) { case SteinerNodeType::ZeroInTree: case SteinerNodeType::OneInTree: case SteinerNodeType::Leaf: case SteinerNodeType::OutOfTree: { return 0; } default: { TKET_ASSERT(!"[AAS]: Invalid cost, wrong SteinerNodeType"); } } break; } case SteinerNodeType::OneInTree: { switch (j_type) { case SteinerNodeType::ZeroInTree: case SteinerNodeType::Leaf: { return -1; } case SteinerNodeType::OneInTree: case SteinerNodeType::OutOfTree: { return 1; } default: { TKET_ASSERT(!"[AAS]: Invalid cost, wrong SteinerNodeType"); } } break; } case SteinerNodeType::Leaf: { switch (j_type) { case SteinerNodeType::ZeroInTree: case SteinerNodeType::Leaf: { return -1; } case SteinerNodeType::OneInTree: case SteinerNodeType::OutOfTree: { return 1; } default: { TKET_ASSERT(!"[AAS]: Invalid cost, wrong SteinerNodeType"); } } break; } case SteinerNodeType::OutOfTree: { switch (j_type) { case SteinerNodeType::ZeroInTree: case SteinerNodeType::OneInTree: case SteinerNodeType::Leaf: case SteinerNodeType::OutOfTree: { return 0; } default: { TKET_ASSERT(!"[AAS]: Invalid cost, wrong SteinerNodeType"); } } break; } default: { TKET_ASSERT(!"[AAS]: Invalid cost, wrong SteinerNodeType"); } } return 0; } OperationList SteinerTree::operations_available( const PathHandler& pathhandler) const { OperationList operations; for (unsigned i = 0; i != node_types.size(); ++i) { for (unsigned j = 0; j != node_types.size(); ++j) { if (i == j) continue; if (!pathhandler.get_connectivity_matrix()(i, j)) continue; if (node_types[i] == SteinerNodeType::OneInTree || node_types[i] == SteinerNodeType::Leaf) { if (node_types[j] == SteinerNodeType::ZeroInTree || node_types[j] == SteinerNodeType::Leaf) { operations.push_back({i, j}); } } } } return operations; } void SteinerTree::add_row(unsigned i, unsigned j) { /* CNOT with control j and target i */ SteinerNodeType i_type = node_types[i]; SteinerNodeType j_type = node_types[j]; last_operation_cost = cost_of_operation(i, j); tree_cost += last_operation_cost; switch (i_type) { case SteinerNodeType::ZeroInTree: { // no action occurs break; } case SteinerNodeType::OneInTree: { switch (j_type) { case SteinerNodeType::ZeroInTree: { node_types[j] = SteinerNodeType::OneInTree; break; } case SteinerNodeType::OneInTree: { node_types[j] = SteinerNodeType::ZeroInTree; break; } case SteinerNodeType::Leaf: { TKET_ASSERT(num_neighbours[i] != 0); TKET_ASSERT(num_neighbours[j] != 0); node_types[j] = SteinerNodeType::OutOfTree; num_neighbours[i] -= 1; num_neighbours[j] -= 1; if (num_neighbours[i] == 1) { node_types[i] = SteinerNodeType::Leaf; } break; } case SteinerNodeType::OutOfTree: { node_types[j] = SteinerNodeType::Leaf; node_types[i] = SteinerNodeType::OneInTree; num_neighbours[i] += 1; num_neighbours[j] += 1; break; } default: { TKET_ASSERT(!"[AAS]: Invalid row op, wrong SteinerNodeType"); } } break; } case SteinerNodeType::Leaf: { switch (j_type) { case SteinerNodeType::ZeroInTree: { node_types[j] = SteinerNodeType::OneInTree; break; } case SteinerNodeType::OneInTree: { node_types[j] = SteinerNodeType::ZeroInTree; break; } // only happens when there are 2 vertices lefts case SteinerNodeType::Leaf: { TKET_ASSERT(num_neighbours[i] != 0); TKET_ASSERT(num_neighbours[j] != 0); node_types[j] = SteinerNodeType::OutOfTree; node_types[i] = SteinerNodeType::OutOfTree; num_neighbours[i] -= 1; num_neighbours[j] -= 1; break; } case SteinerNodeType::OutOfTree: { node_types[j] = SteinerNodeType::Leaf; node_types[i] = SteinerNodeType::OneInTree; num_neighbours[i] += 1; num_neighbours[j] += 1; break; } default: { // Invalid combination of nodes types in add row operation TKET_ASSERT(false); } } break; } case SteinerNodeType::OutOfTree: { // no action occurs break; } default: { TKET_ASSERT(!"Invalid combination of nodes types in add row operation"); } } } bool SteinerTree::fully_reduced() const { return tree_cost == 0; } static std::pair<unsigned, std::vector<unsigned>> steiner_reduce( Circuit& circ, DiagMatrix& CNOT_matrix, const PathHandler& paths, unsigned col, unsigned root, std::list<unsigned>& nodes, bool upper, CNotSynthType cnottype) { std::pair<unsigned, std::vector<unsigned>> result; PathHandler directed_paths; std::list<unsigned> fresh_node_list(nodes); if (upper) { MatrixXb directed_connectivity = paths.get_connectivity_matrix(); for (unsigned i = 0; i < directed_connectivity.rows(); ++i) { for (unsigned j = 0; j < directed_connectivity.cols(); ++j) { if (i < root) directed_connectivity(i, j) = 0; if (j < root) directed_connectivity(i, j) = 0; } } directed_paths = PathHandler(directed_connectivity); } else { MatrixXb directed_connectivity = paths.get_connectivity_matrix(); if (cnottype == CNotSynthType::HamPath) { for (unsigned i = 0; i < directed_connectivity.rows(); ++i) { for (unsigned j = 0; j < directed_connectivity.cols(); ++j) { if (j > i) directed_connectivity(i, j) = 0; if ((j + 1 != i) && (j != i + 1)) directed_connectivity(i, j) = 0; } } } directed_paths = PathHandler(directed_connectivity); } SteinerTree cnot_tree = SteinerTree(directed_paths, fresh_node_list, root); // make list of edges, starting from root to leaves of tree std::list<std::pair<unsigned, unsigned>> parent_child_list; std::set<unsigned> possible_parents{root}; unsigned n_edges = cnot_tree.tree_nodes.size(); if (n_edges > 0) --n_edges; std::set<unsigned> visited_parents{root}; unsigned counterwhile = 0; while ((parent_child_list.size() < n_edges) && (counterwhile < n_edges * n_edges)) { ++counterwhile; std::set<unsigned> new_parents; for (unsigned node : cnot_tree.tree_nodes) { for (unsigned parent : possible_parents) { if (directed_paths.get_connectivity_matrix()(parent, node)) { if (visited_parents.find(node) == visited_parents.end()) { new_parents.insert(node); visited_parents.insert(node); parent_child_list.push_back({parent, node}); } } } } possible_parents = new_parents; } /* Remove zeros */ if (upper) { std::list<std::pair<unsigned, unsigned>> zeros; for (auto& [s0, s1] : parent_child_list) { if (!CNOT_matrix._matrix(s0, col)) { zeros.push_back({s0, s1}); } } while (!zeros.empty()) { std::pair<unsigned, unsigned> s_pair = zeros.back(); unsigned s0 = s_pair.first, s1 = s_pair.second; zeros.pop_back(); if (!CNOT_matrix._matrix(s0, col)) { CNOT_matrix.row_add(s1, s0); circ.add_op<unsigned>(OpType::CX, {s1, s0}); } } parent_child_list.reverse(); for (auto& [s0, s1] : parent_child_list) { CNOT_matrix.row_add(s0, s1); circ.add_op<unsigned>(OpType::CX, {s0, s1}); } } else { for (auto& [s0, s1] : parent_child_list) { if (!CNOT_matrix._matrix(s1, col)) { CNOT_matrix.row_add(s0, s1); circ.add_op<unsigned>(OpType::CX, {s0, s1}); } } parent_child_list.reverse(); for (auto& [s0, s1] : parent_child_list) { CNOT_matrix.row_add(s0, s1); circ.add_op<unsigned>(OpType::CX, {s0, s1}); } } result.first = cnot_tree.get_max_element(); result.second = cnot_tree.nodes(); return result; } static std::pair<unsigned, std::vector<unsigned>> steiner_reduce_rec( Circuit& circ, DiagMatrix& CNOT_matrix, const PathHandler& paths, unsigned col, unsigned root, std::list<unsigned>& nodes) { std::pair<unsigned, std::vector<unsigned>> result; std::list<unsigned> fresh_node_list(nodes); SteinerTree cnot_tree = SteinerTree(paths, fresh_node_list, root); // make list of edges, starting from root to leaves of tree std::list<std::pair<unsigned, unsigned>> parent_child_list; std::set<unsigned> possible_parents{root}; unsigned n_edges = cnot_tree.tree_nodes.size(); if (n_edges > 0) --n_edges; std::set<unsigned> visited_parents{root}; unsigned counterwhile = 0; while ((parent_child_list.size() < n_edges) && (counterwhile < n_edges * n_edges)) { ++counterwhile; std::set<unsigned> new_parents; for (unsigned node : cnot_tree.tree_nodes) { for (unsigned parent : possible_parents) { if (paths.get_connectivity_matrix()(parent, node)) { if (visited_parents.find(node) == visited_parents.end()) { new_parents.insert(node); visited_parents.insert(node); parent_child_list.push_back({parent, node}); } } } } possible_parents = new_parents; } /* Remove zeros */ for (auto& [s0, s1] : parent_child_list) { if (!CNOT_matrix._matrix(s1, col)) { CNOT_matrix.row_add(s0, s1); circ.add_op<unsigned>(OpType::CX, {s0, s1}); } } parent_child_list.reverse(); for (auto& [s0, s1] : parent_child_list) { CNOT_matrix.row_add(s0, s1); circ.add_op<unsigned>(OpType::CX, {s0, s1}); } result.first = cnot_tree.get_max_element(); result.second = cnot_tree.nodes(); return result; } void aas_cnot_synth_rec( DiagMatrix& CNOT_matrix, const PathHandler& paths, std::vector<unsigned>& pivot_cols, Circuit& cnot_circuit, std::vector<unsigned> usablenodes = {}) { // order usable nodes from highest to lowest element, the list should already // be close to the opposite of this order anyway. std::sort(usablenodes.begin(), usablenodes.end()); std::reverse(usablenodes.begin(), usablenodes.end()); for (unsigned current_row : usablenodes) { unsigned pivot = pivot_cols[current_row]; std::list<unsigned> nodes; for (unsigned r = 0; r != current_row; ++r) { if (CNOT_matrix._matrix(r, pivot)) { nodes.push_back(r); } } unsigned max_node_in_tree = 0; std::vector<unsigned> new_usable_nodes; if (!nodes.empty()) { nodes.push_back(current_row); std::pair<unsigned, std::vector<unsigned>> res = steiner_reduce_rec( cnot_circuit, CNOT_matrix, paths, pivot, current_row, nodes); max_node_in_tree = res.first; new_usable_nodes = res.second; } if (max_node_in_tree > current_row) { aas_cnot_synth_rec( CNOT_matrix, paths, pivot_cols, cnot_circuit, new_usable_nodes); } } } // see https://arxiv.org/abs/2004.06052 and https://github.com/Quantomatic/pyzx // for more information. Circuit aas_CNOT_synth( DiagMatrix& CNOT_matrix, const PathHandler& paths, CNotSynthType cnottype) { unsigned pivot = 0; unsigned max_node_in_tree = 0; std::vector<unsigned> usable_nodes(paths.get_size()); std::iota(usable_nodes.begin(), usable_nodes.end(), 0); std::vector<unsigned> pivot_cols; Circuit cnot_circuit(paths.get_size()); for (unsigned current_row = 0; current_row != CNOT_matrix.n_rows(); ++current_row) { bool found_pivot = false; std::list<unsigned> nodes; while ((!found_pivot) && pivot < CNOT_matrix.n_cols()) { for (unsigned r = current_row; r != CNOT_matrix.n_rows(); ++r) { if (CNOT_matrix._matrix(r, pivot)) { nodes.push_back(r); } } if (!nodes.empty()) { pivot_cols.push_back(pivot); found_pivot = true; } else { ++pivot; } } // can't try any more pivots if (!found_pivot) throw std::logic_error("Could not find pivot node in CNOT synthesis."); bool row_not_in_notes = std::none_of( nodes.cbegin(), nodes.cend(), [current_row](unsigned no) { return no == current_row; }); if (row_not_in_notes) nodes.push_front(current_row); std::pair<unsigned, std::vector<unsigned>> res = steiner_reduce( cnot_circuit, CNOT_matrix, paths, pivot, current_row, nodes, true, cnottype); max_node_in_tree = res.first; usable_nodes = res.second; ++pivot; } unsigned current_row = pivot_cols.size() - 1; while (current_row > 0) { std::list<unsigned> nodes; if (CNOT_matrix.is_id_until_columns(current_row)) { pivot = pivot_cols[current_row]; for (unsigned r = 0; r != current_row; ++r) { if (CNOT_matrix._matrix(r, pivot)) { nodes.push_back(r); } } if (!nodes.empty()) { nodes.push_back(current_row); std::pair<unsigned, std::vector<unsigned>> res = steiner_reduce( cnot_circuit, CNOT_matrix, paths, pivot, current_row, nodes, false, cnottype); max_node_in_tree = res.first; usable_nodes = res.second; } else { max_node_in_tree = 0; std::iota(usable_nodes.begin(), usable_nodes.end(), 0); } } if ((max_node_in_tree > current_row) && (cnottype == CNotSynthType::Rec)) { aas_cnot_synth_rec( CNOT_matrix, paths, pivot_cols, cnot_circuit, usable_nodes); } --current_row; TKET_ASSERT(CNOT_matrix.is_id_until_columns(current_row)); } // when constructing circuit, we want to // prepend gates, but it is easier to append and then take the dagger. return cnot_circuit; } Circuit CNotSwapSynth::get_circuit() { return circ; } void CNotSwapSynth::add_swap(unsigned first, unsigned second) { CNOT_matrix.row_add(first, second); CNOT_matrix.row_add(second, first); CNOT_matrix.row_add(first, second); circ.add_op<unsigned>(OpType::CX, {first, second}); circ.add_op<unsigned>(OpType::CX, {second, first}); circ.add_op<unsigned>(OpType::CX, {first, second}); } Circuit aas_CNOT_synth_SWAP(DiagMatrix& CNOT_matrix, const PathHandler& paths) { CNotSwapSynth cnot(paths, CNOT_matrix); TKET_ASSERT(cnot.valid_result()); return cnot.get_circuit(); } CNotSwapSynth::CNotSwapSynth( const PathHandler& pathhandler, const DiagMatrix& CNOT_mat) : paths(pathhandler), CNOT_matrix(CNOT_mat), circ(Circuit(paths.get_size())) { for (unsigned current_row = 0; current_row != CNOT_matrix.n_rows(); ++current_row) { if (!CNOT_matrix._matrix(current_row, current_row)) { // try to find element equal to 1 // and set diagonal element to 1 unsigned one = current_row; while (!CNOT_matrix._matrix(one, current_row)) { ++one; } unsigned current_node = swap_to_root(one, current_row); // remove the 1 with the use of the root CNOT_matrix.row_add(current_node, current_row); circ.add_op<unsigned>(OpType::CX, {current_node, current_row}); cleanup_swaps(); } if (!CNOT_matrix._matrix(current_row, current_row)) { throw std::logic_error( "The given matrix is not invertible, the input was not created by a " "cnot circuit"); } for (unsigned r = current_row + 1; r != CNOT_matrix.n_rows(); ++r) { if (CNOT_matrix._matrix(r, current_row)) { unsigned current_node = swap_to_root(r, current_row); CNOT_matrix.row_add(current_row, current_node); circ.add_op<unsigned>(OpType::CX, {current_row, current_node}); cleanup_swaps(); } } } // end of upper creation for (unsigned current_row = CNOT_matrix.n_rows() - 1; current_row > 0; --current_row) { for (unsigned r = 0; r < current_row; ++r) { if (CNOT_matrix._matrix(r, current_row)) { unsigned current_node = swap_to_root(r, current_row); CNOT_matrix.row_add(current_row, current_node); circ.add_op<unsigned>(OpType::CX, {current_row, current_node}); cleanup_swaps(); } } } } void CNotSwapSynth::cleanup_swaps() { while (!swaps.empty()) { std::pair<unsigned, unsigned> swap = swaps.top(); swaps.pop(); add_swap(swap.first, swap.second); } } unsigned CNotSwapSynth::swap_to_root( unsigned start_node, unsigned current_row) { unsigned current_node = start_node; while (paths.get_path_matrix()(current_node, current_row) != current_row) { unsigned new_node = paths.get_path_matrix()(current_node, current_row); add_swap(current_node, new_node); swaps.push({current_node, new_node}); current_node = new_node; } return current_node; } bool CNotSwapSynth::valid_result() { return CNOT_matrix.is_id(); } } // namespace aas } // namespace tket
tket/tket/src/ArchAwareSynth/SteinerTree.cpp/0
{ "file_path": "tket/tket/src/ArchAwareSynth/SteinerTree.cpp", "repo_id": "tket", "token_count": 11360 }
380
// 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 "tket/Circuit/Circuit.hpp" #include "tket/Utils/Json.hpp" namespace tket { void to_json(nlohmann::json& j, const Circuit& circ) { const auto name = circ.get_name(); if (name) { j["name"] = name.value(); } j["phase"] = circ.get_phase(); j["qubits"] = circ.all_qubits(); j["bits"] = circ.all_bits(); if (circ._number_of_wasm_wires > 0) { j["number_of_ws"] = circ._number_of_wasm_wires; } const auto impl = circ.implicit_qubit_permutation(); // empty maps are mapped to null instead of empty array if (impl.empty()) { j["implicit_permutation"] = nlohmann::json::array(); } else { j["implicit_permutation"] = impl; } j["commands"] = nlohmann::json::array(); for (const Command& com : circ) { j["commands"].push_back(com); } j["created_qubits"] = circ.created_qubits(); j["discarded_qubits"] = circ.discarded_qubits(); } void from_json(const nlohmann::json& j, Circuit& circ) { circ = Circuit(); if (j.contains("name")) { circ.set_name(j["name"].get<std::string>()); } circ.add_phase(j.at("phase").get<Expr>()); const auto& qubits = j.at("qubits").get<qubit_vector_t>(); for (const auto& qb : qubits) { circ.add_qubit(qb); } const auto& bits = j.at("bits").get<bit_vector_t>(); for (const auto& b : bits) { circ.add_bit(b); } if (j.contains("number_of_ws")) { circ.add_wasm_register(j.at("number_of_ws").get<unsigned>()); } for (const auto& j_com : j.at("commands")) { const auto& com = j_com.get<Command>(); circ.add_op(com.get_op_ptr(), com.get_args(), com.get_opgroup()); } const auto& imp_perm = j.at("implicit_permutation").get<qubit_map_t>(); circ.permute_boundary_output(imp_perm); // Check if key exists to work with circuits serialised using older tket // versions if (j.contains("created_qubits")) { for (const auto& j_q : j.at("created_qubits")) { const auto& q = j_q.get<Qubit>(); circ.qubit_create(q); } } if (j.contains("discarded_qubits")) { for (const auto& j_q : j.at("discarded_qubits")) { const auto& q = j_q.get<Qubit>(); circ.qubit_discard(q); } } } } // namespace tket
tket/tket/src/Circuit/CircuitJson.cpp/0
{ "file_path": "tket/tket/src/Circuit/CircuitJson.cpp", "repo_id": "tket", "token_count": 1059 }
381
// 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 "DecomposeCircuit.hpp" #include <sstream> #include <tkassert/Assert.hpp> #include "GateNodesBuffer.hpp" #include "tket/Circuit/Boxes.hpp" #include "tket/Circuit/Circuit.hpp" #include "tket/Circuit/PauliExpBoxes.hpp" #include "tket/Circuit/Simulation/PauliExpBoxUnitaryCalculator.hpp" #include "tket/Gate/Gate.hpp" #include "tket/Gate/GateUnitaryMatrix.hpp" #include "tket/Gate/GateUnitaryMatrixError.hpp" namespace tket { namespace tket_sim { namespace internal { typedef std::map<Qubit, unsigned> QMap; // No checks because only used internally static QMap get_qmap_no_checks( const Circuit& circ, const std::vector<unsigned>& parent_circuit_qubit_indices) { std::map<Qubit, unsigned> qmap; unsigned index = 0; for (const Qubit& q : circ.all_qubits()) { TKET_ASSERT(qmap.count(q) == 0); qmap[q] = parent_circuit_qubit_indices[index]; ++index; } TKET_ASSERT(qmap.size() <= parent_circuit_qubit_indices.size()); return qmap; } // Already known to be a box, with a nonempty Op ptr. // If possible (if the op is able to calculate its own unitary matrix), // fill the node triplets with the raw unitary matrix represented by this box. // Return true if it found the triplets. static bool fill_triplets_directly_from_box( GateNode& node, const std::shared_ptr<const Box>& box_ptr, double abs_epsilon) { std::optional<Eigen::MatrixXcd> u = box_ptr->get_box_unitary(); if (!u.has_value()) { return false; } node.triplets = tket::get_triplets(*u, abs_epsilon); return true; } static void add_global_phase(const Circuit& circ, GateNodesBuffer& buffer) { const auto global_phase = eval_expr(circ.get_phase()); if (!global_phase) { throw SymbolsNotSupported("Circuit has symbolic global phase"); } const double phase_value = global_phase.value(); buffer.add_global_phase(phase_value); } static void throw_with_op_error_message( const std::string& op_name, const QMap& qmap, const Circuit& circ, const std::string& extra_message) { std::stringstream ss; ss << "Subcircuit\n" << circ << "\nwith " << qmap.size() << " qubits, has op " << op_name << ". " << extra_message; throw CircuitInvalidity(ss.str()); } static void fill_qubit_indices( const unit_vector_t& args, const QMap& qmap, GateNode& node) { TKET_ASSERT(args.size() <= qmap.size()); node.qubit_indices.resize(args.size()); for (unsigned ii = 0; ii < args.size(); ++ii) { node.qubit_indices[ii] = qmap.at(Qubit(args[ii])); } } static void decompose_circuit_recursive( const Circuit& circ, GateNodesBuffer& buffer, const std::vector<unsigned>& parent_circuit_qubit_indices, double abs_epsilon) { const auto qmap = get_qmap_no_checks(circ, parent_circuit_qubit_indices); unit_vector_t args; GateNode node; for (const Command& command : circ) { const Op_ptr current_op = command.get_op_ptr(); TKET_ASSERT(current_op.get()); const OpType current_type = current_op->get_type(); if (is_classical_type(current_type) || is_projective_type(current_type) || current_type == OpType::Conditional) { throw GateUnitaryMatrixError( "Unsupported OpType " + current_op->get_name(), GateUnitaryMatrixError::Cause::GATE_NOT_IMPLEMENTED); } if (current_type == OpType::noop || current_type == OpType::Barrier) { continue; } const OpDesc desc = current_op->get_desc(); args = command.get_args(); fill_qubit_indices(args, qmap, node); if (desc.is_gate()) { const Gate* gate = dynamic_cast<const Gate*>(current_op.get()); TKET_ASSERT(gate); node.triplets = GateUnitaryMatrix::get_unitary_triplets(*gate, abs_epsilon); buffer.push(node); continue; } if (!desc.is_box()) { throw_with_op_error_message( desc.name(), qmap, circ, "This is not a gate or box type."); } std::shared_ptr<const Box> box_ptr = std::dynamic_pointer_cast<const Box>(current_op); TKET_ASSERT(box_ptr.get()); node.triplets.clear(); const bool found_unitary = fill_triplets_directly_from_box(node, box_ptr, abs_epsilon); if (!node.triplets.empty()) { TKET_ASSERT(found_unitary); buffer.push(node); continue; } TKET_ASSERT(!found_unitary); // Break this box down, recursively. std::shared_ptr<Circuit> box_circ = box_ptr->to_circuit(); if (!box_circ.get()) { throw_with_op_error_message( desc.name(), qmap, circ, "This is a box, which couldn't be " "broken down into a circuit"); } decompose_circuit_recursive( *box_circ, buffer, node.qubit_indices, abs_epsilon); } add_global_phase(circ, buffer); } void decompose_circuit( const Circuit& circ, GateNodesBuffer& buffer, double abs_epsilon) { // The qubits are just [0,1,2,...]. std::vector<unsigned> iota(circ.n_qubits()); std::iota(iota.begin(), iota.end(), 0); decompose_circuit_recursive(circ, buffer, iota, abs_epsilon); buffer.flush(); } } // namespace internal } // namespace tket_sim } // namespace tket
tket/tket/src/Circuit/Simulation/DecomposeCircuit.cpp/0
{ "file_path": "tket/tket/src/Circuit/Simulation/DecomposeCircuit.cpp", "repo_id": "tket", "token_count": 2182 }
382
// 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 "tket/Clifford/ChoiMixTableau.hpp" #include <boost/foreach.hpp> #include "tket/OpType/OpTypeInfo.hpp" namespace tket { static SymplecticTableau id_tab(unsigned n) { MatrixXb xmat(2 * n, 2 * n); xmat << MatrixXb::Identity(n, n), MatrixXb::Identity(n, n), MatrixXb::Zero(n, 2 * n); MatrixXb zmat(2 * n, 2 * n); zmat << MatrixXb::Zero(n, 2 * n), MatrixXb::Identity(n, n), MatrixXb::Identity(n, n); return SymplecticTableau(xmat, zmat, VectorXb::Zero(2 * n)); } ChoiMixTableau::ChoiMixTableau(unsigned n) : tab_(id_tab(n)), col_index_() { for (unsigned i = 0; i < n; ++i) { col_index_.insert({{Qubit(i), TableauSegment::Input}, i}); col_index_.insert({{Qubit(i), TableauSegment::Output}, n + i}); } } ChoiMixTableau::ChoiMixTableau(const qubit_vector_t& qbs) : tab_(id_tab(qbs.size())), col_index_() { unsigned n = qbs.size(); unsigned i = 0; for (const Qubit& qb : qbs) { col_index_.insert({{qb, TableauSegment::Input}, i}); col_index_.insert({{qb, TableauSegment::Output}, n + i}); ++i; } } ChoiMixTableau::ChoiMixTableau( const MatrixXb& xmat, const MatrixXb& zmat, const VectorXb& phase, unsigned n_ins) : tab_({}), col_index_() { unsigned n_rows = xmat.rows(); unsigned n_bounds = xmat.cols(); if (n_ins > n_bounds) throw std::invalid_argument( "Number of inputs of a Choi tableau cannot be larger than the " "number of qubits"); if ((zmat.cols() != n_bounds) || (zmat.rows() != n_rows) || (phase.size() != n_rows)) throw std::invalid_argument( "Choi tableau requires equally-sized components"); tab_ = SymplecticTableau(xmat, zmat, phase); if (tab_.anticommuting_rows() != MatrixXb::Zero(n_rows, n_rows)) throw std::invalid_argument("Rows of Choi tableau do not commute"); if (tab_.rank() != n_rows) throw std::invalid_argument("Rows of Choi tableau are not independent"); for (unsigned i = 0; i < n_ins; ++i) { col_index_.insert({{Qubit(i), TableauSegment::Input}, i}); } for (unsigned i = 0; i < n_bounds - n_ins; ++i) { col_index_.insert({{Qubit(i), TableauSegment::Output}, i}); } } ChoiMixTableau::ChoiMixTableau(const std::list<row_tensor_t>& rows) : tab_({}), col_index_() { std::set<Qubit> in_qubits; std::set<Qubit> out_qubits; for (const row_tensor_t& row : rows) { for (const std::pair<const Qubit, Pauli>& qb : row.first.string) { in_qubits.insert(qb.first); } for (const std::pair<const Qubit, Pauli>& qb : row.second.string) { out_qubits.insert(qb.first); } } unsigned n_rows = rows.size(); unsigned n_qbs = in_qubits.size() + out_qubits.size(); unsigned i = 0; for (const Qubit& qb : in_qubits) { col_index_.insert({{qb, TableauSegment::Input}, i}); ++i; } for (const Qubit& qb : out_qubits) { col_index_.insert({{qb, TableauSegment::Output}, i}); ++i; } MatrixXb xmat = MatrixXb::Zero(n_rows, n_qbs); MatrixXb zmat = MatrixXb::Zero(n_rows, n_qbs); VectorXb phase = VectorXb::Zero(n_rows); unsigned r = 0; for (const row_tensor_t& row : rows) { unsigned n_ys = 0; for (const std::pair<const Qubit, Pauli>& qb : row.first.string) { unsigned c = col_index_.left.at(col_key_t{qb.first, TableauSegment::Input}); if (qb.second == Pauli::X || qb.second == Pauli::Y) xmat(r, c) = true; if (qb.second == Pauli::Z || qb.second == Pauli::Y) zmat(r, c) = true; if (qb.second == Pauli::Y) ++n_ys; } for (const std::pair<const Qubit, Pauli>& qb : row.second.string) { unsigned c = col_index_.left.at(col_key_t{qb.first, TableauSegment::Output}); if (qb.second == Pauli::X || qb.second == Pauli::Y) xmat(r, c) = true; if (qb.second == Pauli::Z || qb.second == Pauli::Y) zmat(r, c) = true; } phase(r) = row.first.is_real_negative() ^ row.second.is_real_negative() ^ (n_ys % 2 == 1); ++r; } tab_ = SymplecticTableau(xmat, zmat, phase); } unsigned ChoiMixTableau::get_n_rows() const { return tab_.get_n_rows(); } unsigned ChoiMixTableau::get_n_boundaries() const { return col_index_.size(); } unsigned ChoiMixTableau::get_n_inputs() const { return input_qubits().size(); } unsigned ChoiMixTableau::get_n_outputs() const { return output_qubits().size(); } qubit_vector_t ChoiMixTableau::input_qubits() const { qubit_vector_t ins; BOOST_FOREACH ( tableau_col_index_t::left_const_reference entry, col_index_.left) { if (entry.first.second == TableauSegment::Input) ins.push_back(entry.first.first); } return ins; } qubit_vector_t ChoiMixTableau::output_qubits() const { qubit_vector_t outs; BOOST_FOREACH ( tableau_col_index_t::left_const_reference entry, col_index_.left) { if (entry.first.second == TableauSegment::Output) outs.push_back(entry.first.first); } return outs; } ChoiMixTableau::row_tensor_t ChoiMixTableau::stab_to_row_tensor( const PauliStabiliser& stab) const { QubitPauliMap in_qpm, out_qpm; for (unsigned i = 0; i < stab.string.size(); ++i) { Pauli p = stab.string.at(i); col_key_t col = col_index_.right.at(i); if (p != Pauli::I) { if (col.second == TableauSegment::Input) in_qpm.insert({col.first, p}); else out_qpm.insert({col.first, p}); } } return {SpPauliStabiliser(in_qpm), SpPauliStabiliser(out_qpm, stab.coeff)}; } PauliStabiliser ChoiMixTableau::row_tensor_to_stab( const row_tensor_t& ten) const { std::vector<Pauli> ps; for (unsigned i = 0; i < col_index_.size(); ++i) { col_key_t qb = col_index_.right.at(i); if (qb.second == TableauSegment::Input) ps.push_back(ten.first.get(qb.first)); else ps.push_back(ten.second.get(qb.first)); } return PauliStabiliser(ps, (ten.first.coeff + ten.second.coeff) % 4); } ChoiMixTableau::row_tensor_t ChoiMixTableau::get_row(unsigned i) const { ChoiMixTableau::row_tensor_t res = stab_to_row_tensor(tab_.get_pauli(i)); res.first.transpose(); res.second.coeff = (res.first.coeff + res.second.coeff) % 4; res.first.coeff = 0; return res; } ChoiMixTableau::row_tensor_t ChoiMixTableau::get_row_product( const std::vector<unsigned>& rows) const { row_tensor_t result = {{}, {}}; for (unsigned i : rows) { row_tensor_t row_i = stab_to_row_tensor(tab_.get_pauli(i)); result.first = result.first * row_i.first; result.second = result.second * row_i.second; } result.first.transpose(); result.second.coeff = (result.first.coeff + result.second.coeff) % 4; result.first.coeff = 0; return result; } void ChoiMixTableau::apply_S(const Qubit& qb, TableauSegment seg) { unsigned col = col_index_.left.at(col_key_t{qb, seg}); tab_.apply_S(col); } void ChoiMixTableau::apply_Z(const Qubit& qb, TableauSegment seg) { unsigned col = col_index_.left.at(col_key_t{qb, seg}); tab_.apply_Z(col); } void ChoiMixTableau::apply_V(const Qubit& qb, TableauSegment seg) { unsigned col = col_index_.left.at(col_key_t{qb, seg}); tab_.apply_V(col); } void ChoiMixTableau::apply_X(const Qubit& qb, TableauSegment seg) { unsigned col = col_index_.left.at(col_key_t{qb, seg}); tab_.apply_X(col); } void ChoiMixTableau::apply_H(const Qubit& qb, TableauSegment seg) { unsigned col = col_index_.left.at(col_key_t{qb, seg}); tab_.apply_H(col); } void ChoiMixTableau::apply_CX( const Qubit& control, const Qubit& target, TableauSegment seg) { unsigned uc = col_index_.left.at(col_key_t{control, seg}); unsigned ut = col_index_.left.at(col_key_t{target, seg}); tab_.apply_CX(uc, ut); } void ChoiMixTableau::apply_gate( OpType type, const qubit_vector_t& qbs, TableauSegment seg) { switch (type) { case OpType::Z: { apply_Z(qbs.at(0), seg); break; } case OpType::X: { apply_X(qbs.at(0), seg); break; } case OpType::Y: { apply_Z(qbs.at(0), seg); apply_X(qbs.at(0), seg); break; } case OpType::S: { apply_S(qbs.at(0), seg); break; } case OpType::Sdg: { apply_S(qbs.at(0), seg); apply_Z(qbs.at(0), seg); break; } case OpType::SX: case OpType::V: { apply_V(qbs.at(0), seg); break; } case OpType::SXdg: case OpType::Vdg: { apply_V(qbs.at(0), seg); apply_X(qbs.at(0), seg); break; } case OpType::H: { apply_H(qbs.at(0), seg); break; } case OpType::CX: { apply_CX(qbs.at(0), qbs.at(1), seg); break; } case OpType::CY: { if (seg == TableauSegment::Input) { apply_S(qbs.at(1), seg); apply_CX(qbs.at(0), qbs.at(1), seg); apply_S(qbs.at(1), seg); apply_Z(qbs.at(1), seg); } else { apply_S(qbs.at(1), seg); apply_Z(qbs.at(1), seg); apply_CX(qbs.at(0), qbs.at(1), seg); apply_S(qbs.at(1), seg); } break; } case OpType::CZ: { apply_H(qbs.at(1), seg); apply_CX(qbs.at(0), qbs.at(1), seg); apply_H(qbs.at(1), seg); break; } case OpType::ZZMax: { apply_CX(qbs.at(0), qbs.at(1), seg); apply_S(qbs.at(1), seg); apply_CX(qbs.at(0), qbs.at(1), seg); break; } case OpType::ECR: { if (seg == TableauSegment::Input) { apply_X(qbs.at(0), seg); apply_S(qbs.at(0), seg); apply_V(qbs.at(1), seg); apply_CX(qbs.at(0), qbs.at(1), seg); } else { apply_CX(qbs.at(0), qbs.at(1), seg); apply_S(qbs.at(0), seg); apply_X(qbs.at(0), seg); apply_V(qbs.at(1), seg); } break; } case OpType::ISWAPMax: { apply_V(qbs.at(0), seg); apply_V(qbs.at(1), seg); apply_CX(qbs.at(0), qbs.at(1), seg); apply_V(qbs.at(0), seg); apply_S(qbs.at(1), seg); apply_Z(qbs.at(1), seg); apply_CX(qbs.at(0), qbs.at(1), seg); apply_V(qbs.at(0), seg); apply_V(qbs.at(1), seg); break; } case OpType::SWAP: { apply_CX(qbs.at(0), qbs.at(1), seg); apply_CX(qbs.at(1), qbs.at(0), seg); apply_CX(qbs.at(0), qbs.at(1), seg); break; } case OpType::BRIDGE: { apply_CX(qbs.at(0), qbs.at(2), seg); break; } case OpType::Phase: case OpType::noop: { break; } case OpType::Reset: { if (seg == TableauSegment::Input) { post_select(qbs.at(0), TableauSegment::Input); unsigned col = get_n_boundaries(); unsigned rows = get_n_rows(); // reinsert qubit initialised to maximally mixed state (no coherent // stabilizers) col_index_.insert({{qbs.at(0), TableauSegment::Input}, col}); tab_.xmat.conservativeResize(rows, col + 1); tab_.xmat.col(col) = MatrixXb::Zero(rows, 1); tab_.zmat.conservativeResize(rows, col + 1); tab_.zmat.col(col) = MatrixXb::Zero(rows, 1); } else { discard_qubit(qbs.at(0), TableauSegment::Output); unsigned col = get_n_boundaries(); unsigned rows = get_n_rows(); // reinsert qubit initialised to |0> (add a Z stabilizer) col_index_.insert({{qbs.at(0), TableauSegment::Output}, col}); tab_.xmat.conservativeResize(rows + 1, col + 1); tab_.xmat.col(col) = MatrixXb::Zero(rows + 1, 1); tab_.xmat.row(rows) = MatrixXb::Zero(1, col + 1); tab_.zmat.conservativeResize(rows + 1, col + 1); tab_.zmat.col(col) = MatrixXb::Zero(rows + 1, 1); tab_.zmat.row(rows) = MatrixXb::Zero(1, col + 1); tab_.zmat(rows, col) = true; tab_.phase.conservativeResize(rows + 1); tab_.phase(rows) = false; } break; } case OpType::Collapse: { collapse_qubit(qbs.at(0), seg); break; } default: { throw BadOpType( "Cannot be applied to a ChoiMixTableau: not a unitary Clifford gate", type); } } } void ChoiMixTableau::apply_pauli( const SpPauliStabiliser& pauli, unsigned half_pis, TableauSegment seg) { PauliStabiliser ps; if (seg == TableauSegment::Input) { SpPauliStabiliser tr = pauli; tr.transpose(); ps = row_tensor_to_stab({tr, {}}); } else { ps = row_tensor_to_stab({{}, pauli}); } tab_.apply_pauli_gadget(ps, half_pis); } void ChoiMixTableau::post_select(const Qubit& qb, TableauSegment seg) { tab_.gaussian_form(); // If +Z or -Z is a stabilizer, it will appear as the only row containing Z // after gaussian elimination Check for the deterministic cases unsigned n_rows = get_n_rows(); unsigned n_cols = get_n_boundaries(); unsigned col = col_index_.left.at(col_key_t{qb, seg}); for (unsigned r = 0; r < n_rows; ++r) { if (tab_.zmat(r, col)) { bool only_z = true; for (unsigned c = 0; c < n_cols; ++c) { if ((tab_.xmat(r, c) || tab_.zmat(r, c)) && (c != col)) { only_z = false; break; } } if (!only_z) break; // Not deterministic // From here, we know we are in a deterministic case // If deterministically fail, throw an exception if (tab_.phase(r)) throw std::logic_error( "Post-selecting a tableau fails deterministically"); // Otherwise, we succeed and remove the stabilizer remove_row(r); remove_col(col); return; } } // For the remainder of the method we handle the non-deterministic case // Isolate a single row with an X (if one exists) std::optional<unsigned> x_row = std::nullopt; for (unsigned r = 0; r < n_rows; ++r) { if (tab_.xmat(r, col)) { if (x_row) { // Already found another row with an X, so combine them tab_.row_mult(*x_row, r); } else { // This is the first row with an X // Continue searching the rest to make it unique x_row = r; } } } if (x_row) { // Remove the anti-commuting stabilizer remove_row(*x_row); } remove_col(col); } void ChoiMixTableau::discard_qubit(const Qubit& qb, TableauSegment seg) { unsigned col = col_index_.left.at(col_key_t{qb, seg}); // Isolate a single row with an X (if one exists) std::optional<unsigned> x_row = std::nullopt; for (unsigned r = 0; r < get_n_rows(); ++r) { if (tab_.xmat(r, col)) { if (x_row) { // Already found another row with an X, so combine them tab_.row_mult(*x_row, r); } else { // This is the first row with an X // Continue searching the rest to make it unique x_row = r; } } } if (x_row) { // Remove the X stabilizer remove_row(*x_row); } // Isolate a single row with a Z (if one exists) std::optional<unsigned> z_row = std::nullopt; for (unsigned r = 0; r < get_n_rows(); ++r) { if (tab_.zmat(r, col)) { if (z_row) { // Already found another row with a Z, so combine them tab_.row_mult(*z_row, r); } else { // This is the first row with a Z // Continue searching the rest to make it unique z_row = r; } } } if (z_row) { // Remove the Z stabilizer remove_row(*z_row); } remove_col(col); } void ChoiMixTableau::collapse_qubit(const Qubit& qb, TableauSegment seg) { unsigned col = col_index_.left.at(col_key_t{qb, seg}); // Isolate a single row with an X (if one exists) std::optional<unsigned> x_row = std::nullopt; for (unsigned r = 0; r < get_n_rows(); ++r) { if (tab_.xmat(r, col)) { if (x_row) { // Already found another row with an X, so combine them tab_.row_mult(*x_row, r); } else { // This is the first row with an X // Continue searching the rest to make it unique x_row = r; } } } if (x_row) { // Remove the X stabilizer remove_row(*x_row); } } void ChoiMixTableau::remove_row(unsigned row) { if (row >= get_n_rows()) throw std::invalid_argument( "Cannot remove row " + std::to_string(row) + " from tableau with " + std::to_string(get_n_rows()) + " rows"); unsigned n_rows = get_n_rows(); unsigned n_cols = get_n_boundaries(); if (row < n_rows - 1) { tab_.xmat.row(row) = tab_.xmat.row(n_rows - 1); tab_.zmat.row(row) = tab_.zmat.row(n_rows - 1); tab_.phase(row) = tab_.phase(n_rows - 1); } tab_.xmat.conservativeResize(n_rows - 1, n_cols); tab_.zmat.conservativeResize(n_rows - 1, n_cols); tab_.phase.conservativeResize(n_rows - 1); } void ChoiMixTableau::remove_col(unsigned col) { if (col >= get_n_boundaries()) throw std::invalid_argument( "Cannot remove column " + std::to_string(col) + " from tableau with " + std::to_string(get_n_boundaries()) + " columns"); unsigned n_rows = get_n_rows(); unsigned n_cols = get_n_boundaries(); if (col < n_cols - 1) { tab_.xmat.col(col) = tab_.xmat.col(n_cols - 1); tab_.zmat.col(col) = tab_.zmat.col(n_cols - 1); } tab_.xmat.conservativeResize(n_rows, n_cols - 1); tab_.zmat.conservativeResize(n_rows, n_cols - 1); col_index_.right.erase(col); if (col < n_cols - 1) { tableau_col_index_t::right_iterator it = col_index_.right.find(n_cols - 1); col_key_t last = it->second; col_index_.right.erase(it); col_index_.insert({last, col}); } } void ChoiMixTableau::canonical_column_order(TableauSegment first) { std::set<Qubit> ins; std::set<Qubit> outs; BOOST_FOREACH ( tableau_col_index_t::left_const_reference entry, col_index_.left) { if (entry.first.second == TableauSegment::Input) ins.insert(entry.first.first); else outs.insert(entry.first.first); } tableau_col_index_t new_index; unsigned i = 0; if (first == TableauSegment::Input) { for (const Qubit& q : ins) { new_index.insert({{q, TableauSegment::Input}, i}); ++i; } } for (const Qubit& q : outs) { new_index.insert({{q, TableauSegment::Output}, i}); ++i; } if (first == TableauSegment::Output) { for (const Qubit& q : ins) { new_index.insert({{q, TableauSegment::Input}, i}); ++i; } } unsigned n_rows = get_n_rows(); MatrixXb xmat = MatrixXb::Zero(n_rows, i); MatrixXb zmat = MatrixXb::Zero(n_rows, i); for (unsigned j = 0; j < i; ++j) { col_key_t key = new_index.right.at(j); unsigned c = col_index_.left.at(key); xmat.col(j) = tab_.xmat.col(c); zmat.col(j) = tab_.zmat.col(c); } tab_ = SymplecticTableau(xmat, zmat, tab_.phase); col_index_ = new_index; } void ChoiMixTableau::gaussian_form() { tab_.gaussian_form(); } void ChoiMixTableau::rename_qubits( const qubit_map_t& qmap, TableauSegment seg) { tableau_col_index_t new_index; BOOST_FOREACH ( tableau_col_index_t::left_const_reference entry, col_index_.left) { auto found = qmap.find(entry.first.first); if (entry.first.second == seg && found != qmap.end()) new_index.insert({{found->second, seg}, entry.second}); else new_index.insert({entry.first, entry.second}); } col_index_ = new_index; } ChoiMixTableau ChoiMixTableau::compose( const ChoiMixTableau& first, const ChoiMixTableau& second) { // Merge tableau into a single one with only output qubits with default // indexing tableau_col_index_t first_qubits_to_names; tableau_col_index_t second_qubits_to_names; unsigned f_rows = first.get_n_rows(); unsigned f_cols = first.get_n_boundaries(); unsigned s_rows = second.get_n_rows(); unsigned s_cols = second.get_n_boundaries(); for (unsigned i = 0; i < f_cols; ++i) { first_qubits_to_names.insert({first.col_index_.right.at(i), i}); } for (unsigned i = 0; i < s_cols; ++i) { second_qubits_to_names.insert({second.col_index_.right.at(i), i + f_cols}); } MatrixXb fullx(f_rows + s_rows, f_cols + s_cols), fullz(f_rows + s_rows, f_cols + s_cols); fullx << first.tab_.xmat, MatrixXb::Zero(f_rows, s_cols), MatrixXb::Zero(s_rows, f_cols), second.tab_.xmat; fullz << first.tab_.zmat, MatrixXb::Zero(f_rows, s_cols), MatrixXb::Zero(s_rows, f_cols), second.tab_.zmat; VectorXb fullph(f_rows + s_rows); fullph << first.tab_.phase, second.tab_.phase; ChoiMixTableau combined(fullx, fullz, fullph, 0); // For each connecting pair of qubits, compose via a Bell post-selection for (unsigned i = 0; i < f_cols; ++i) { col_key_t ind = first_qubits_to_names.right.at(i); if (ind.second == TableauSegment::Output) { auto found = second_qubits_to_names.left.find( col_key_t{ind.first, TableauSegment::Input}); if (found != second_qubits_to_names.left.end()) { // Found a matching pair Qubit f_qb(i), s_qb(found->second); combined.apply_CX(f_qb, s_qb); combined.apply_gate(OpType::H, {f_qb}); combined.post_select(f_qb); combined.post_select(s_qb); } } } // Rename qubits to original names tableau_col_index_t new_index; BOOST_FOREACH ( tableau_col_index_t::left_const_reference col, combined.col_index_.left) { bool success = false; unsigned qb_num = col.first.first.index().at(0); auto found = first_qubits_to_names.right.find(qb_num); if (found != first_qubits_to_names.right.end()) { success = new_index.insert({found->second, col.second}).second; } else { success = new_index .insert({second_qubits_to_names.right.at(qb_num), col.second}) .second; } if (!success) throw std::logic_error( "Qubits aliasing after composing two ChoiMixTableau objects"); } combined.col_index_ = new_index; return combined; } std::ostream& operator<<(std::ostream& os, const ChoiMixTableau& tab) { for (unsigned i = 0; i < tab.get_n_rows(); ++i) { ChoiMixTableau::row_tensor_t row = tab.get_row(i); os << row.first.to_str() << "\t->\t" << row.second.to_str() << std::endl; } return os; } bool ChoiMixTableau::operator==(const ChoiMixTableau& other) const { return (col_index_ == other.col_index_) && (tab_ == other.tab_); } void to_json(nlohmann::json& j, const ChoiMixTableau::TableauSegment& seg) { j = (seg == ChoiMixTableau::TableauSegment::Input) ? "In" : "Out"; } void from_json(const nlohmann::json& j, ChoiMixTableau::TableauSegment& seg) { const std::string str_seg = j.get<std::string>(); seg = (str_seg == "In") ? ChoiMixTableau::TableauSegment::Input : ChoiMixTableau::TableauSegment::Output; } void to_json(nlohmann::json& j, const ChoiMixTableau& tab) { j["tab"] = tab.tab_; std::vector<ChoiMixTableau::col_key_t> qbs; for (unsigned i = 0; i < tab.get_n_boundaries(); ++i) { qbs.push_back(tab.col_index_.right.at(i)); } j["qubits"] = qbs; } void from_json(const nlohmann::json& j, ChoiMixTableau& tab) { j.at("tab").get_to(tab.tab_); std::vector<ChoiMixTableau::col_key_t> qbs = j.at("qubits").get<std::vector<ChoiMixTableau::col_key_t>>(); if (qbs.size() != tab.tab_.get_n_qubits()) throw std::invalid_argument( "Number of qubits in json ChoiMixTableau does not match tableau " "size."); tab.col_index_.clear(); for (unsigned i = 0; i < qbs.size(); ++i) { tab.col_index_.insert({qbs.at(i), i}); } } } // namespace tket
tket/tket/src/Clifford/ChoiMixTableau.cpp/0
{ "file_path": "tket/tket/src/Clifford/ChoiMixTableau.cpp", "repo_id": "tket", "token_count": 10704 }
383
// 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 <utility> #include "tket/Gate/GateUnitaryMatrixImplementations.hpp" #include "tket/Gate/GateUnitaryMatrixUtils.hpp" #include "tket/Utils/Constants.hpp" // This file is for gates with unitary matrices // computed using other ("primitive") gates. // Of course, this choice is subjective and could change. namespace tket { namespace internal { Eigen::Matrix4cd GateUnitaryMatrixImplementations::CU1(double lambda) { return GateUnitaryMatrixUtils::get_controlled_gate_unitary(U1(lambda)); } Eigen::Matrix4cd GateUnitaryMatrixImplementations::CU3( double theta, double phi, double lambda) { return GateUnitaryMatrixUtils::get_controlled_gate_unitary( U3(theta, phi, lambda)); } Eigen::Matrix2cd GateUnitaryMatrixImplementations::U2( double phi, double lambda) { return U3(0.5, phi, lambda); } Eigen::Matrix2cd GateUnitaryMatrixImplementations::U3( double theta, double phi, double lambda) { return std::polar(1.0, 0.5 * PI * (lambda + phi)) * Rz(phi) * Ry(theta) * Rz(lambda); } Eigen::Matrix2cd GateUnitaryMatrixImplementations::TK1( double alpha, double beta, double gamma) { return Rz(alpha) * Rx(beta) * Rz(gamma); } Eigen::Matrix4cd GateUnitaryMatrixImplementations::CRx(double alpha) { return GateUnitaryMatrixUtils::get_controlled_gate_unitary(Rx(alpha)); } Eigen::Matrix4cd GateUnitaryMatrixImplementations::CRy(double alpha) { return GateUnitaryMatrixUtils::get_controlled_gate_unitary(Ry(alpha)); } Eigen::Matrix4cd GateUnitaryMatrixImplementations::CRz(double alpha) { return GateUnitaryMatrixUtils::get_controlled_gate_unitary(Rz(alpha)); } Eigen::Matrix4cd GateUnitaryMatrixImplementations::TK2( double alpha, double beta, double gamma) { return XXPhase(alpha) * YYPhase(beta) * ZZPhase(gamma); } Eigen::Matrix4cd GateUnitaryMatrixImplementations::PhasedISWAP( double p, double t) { auto matr = ISWAP(t); const auto exp_term = std::polar(1.0, -2 * PI * p); matr(2, 1) *= exp_term; matr(1, 2) *= std::conj(exp_term); return matr; } Eigen::Matrix<std::complex<double>, 1, 1> GateUnitaryMatrixImplementations::Phase(double alpha) { return Eigen::Matrix<std::complex<double>, 1, 1>(std::exp(i_ * PI * alpha)); } Eigen::Matrix2cd GateUnitaryMatrixImplementations::PhasedX( double alpha, double beta) { const auto rz_beta_matr = Rz(beta); return rz_beta_matr * Rx(alpha) * rz_beta_matr.conjugate(); } Eigen::MatrixXcd GateUnitaryMatrixImplementations::NPhasedX( unsigned number_of_qubits, double alpha, double beta) { const auto phasedx_matr = PhasedX(alpha, beta); Eigen::MatrixXcd U = Eigen::MatrixXcd::Identity(1, 1); for (unsigned i = 0; i < number_of_qubits; i++) { Eigen::MatrixXcd V = Eigen::kroneckerProduct(phasedx_matr, U); U = std::move(V); } return U; } Eigen::MatrixXcd GateUnitaryMatrixImplementations::CnRy( unsigned int number_of_qubits, double alpha) { return GateUnitaryMatrixUtils::get_multi_controlled_gate_dense_unitary( Ry(alpha), number_of_qubits); } Eigen::MatrixXcd GateUnitaryMatrixImplementations::CnRx( unsigned int number_of_qubits, double alpha) { return GateUnitaryMatrixUtils::get_multi_controlled_gate_dense_unitary( Rx(alpha), number_of_qubits); } Eigen::MatrixXcd GateUnitaryMatrixImplementations::CnRz( unsigned int number_of_qubits, double alpha) { return GateUnitaryMatrixUtils::get_multi_controlled_gate_dense_unitary( Rz(alpha), number_of_qubits); } Eigen::MatrixXcd GateUnitaryMatrixImplementations::CnX( unsigned int number_of_qubits) { return GateUnitaryMatrixUtils::get_multi_controlled_gate_dense_unitary( X(), number_of_qubits); } Eigen::MatrixXcd GateUnitaryMatrixImplementations::CnZ( unsigned int number_of_qubits) { return GateUnitaryMatrixUtils::get_multi_controlled_gate_dense_unitary( Z(), number_of_qubits); } Eigen::MatrixXcd GateUnitaryMatrixImplementations::CnY( unsigned int number_of_qubits) { return GateUnitaryMatrixUtils::get_multi_controlled_gate_dense_unitary( Y(), number_of_qubits); } } // namespace internal } // namespace tket
tket/tket/src/Gate/GateUnitaryMatrixComposites.cpp/0
{ "file_path": "tket/tket/src/Gate/GateUnitaryMatrixComposites.cpp", "repo_id": "tket", "token_count": 1672 }
384
// 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 "ColouringPriority.hpp" #include <sstream> #include <stdexcept> #include <tkassert/Assert.hpp> #include "tket/Graphs/AdjacencyData.hpp" using std::map; using std::set; using std::size_t; using std::string; using std::vector; namespace tket { namespace graphs { static void fill_initial_node_sequence( ColouringPriority::Nodes& nodes, const AdjacencyData& adjacency_data, const set<std::size_t>& vertices_in_component, const set<std::size_t>& initial_clique) { nodes.reserve(vertices_in_component.size()); nodes.clear(); try { for (std::size_t clique_vertex : initial_clique) { // GCOVR_EXCL_START if (vertices_in_component.count(clique_vertex) == 0) { std::stringstream ss; ss << "initial clique vertex " << clique_vertex << " is not in this component"; throw std::runtime_error(ss.str()); } // GCOVR_EXCL_STOP nodes.emplace_back(); nodes.back().vertex = clique_vertex; } // Now, we do a breadth-first traversal of the remaining vertices, // adding all vertices only one step away from the current set. std::size_t current_nodes_begin = 0; set<std::size_t> vertices_seen = initial_clique; set<std::size_t> vertices_to_add; for (std::size_t counter = 0; counter < 2 * vertices_in_component.size(); ++counter) { const std::size_t current_nodes_end = nodes.size(); for (std::size_t i = current_nodes_begin; i < current_nodes_end; ++i) { const auto& neighbours = adjacency_data.get_neighbours(nodes[i].vertex); for (std::size_t neighbour : neighbours) { if (vertices_seen.count(neighbour) == 0) { vertices_to_add.insert(neighbour); } } } if (vertices_to_add.empty()) { break; } for (std::size_t neighbour : vertices_to_add) { vertices_seen.insert(neighbour); nodes.emplace_back(); nodes.back().vertex = neighbour; } vertices_to_add.clear(); current_nodes_begin = current_nodes_end; } // GCOVR_EXCL_START if (nodes.size() != vertices_in_component.size()) { throw std::runtime_error( "Final size check: number of filled " "nodes does not match number of vertices in this component"); } // GCOVR_EXCL_STOP } catch (const std::exception& e) { // GCOVR_EXCL_START TKET_ASSERT( AssertMessage() << "ColouringPriority: fill_initial_node_sequence: initial" << " clique size " << initial_clique.size() << ", " << vertices_in_component.size() << " vertices in" << " this component (full graph has " << adjacency_data.get_number_of_vertices() << " vertices)." << " So far, filled " << nodes.size() << " nodes." << " Error: " << e.what()); // GCOVR_EXCL_STOP } } // Quadratic, but we're not afraid; the main brute force colouring is // exponential! Assumes that "fill_initial_node_sequence" has just been called. // Fills in "earlier_neighbour_node_indices". static void fill_node_dependencies( ColouringPriority::Nodes& nodes, const AdjacencyData& adjacency_data) { for (std::size_t node_index = 1; node_index < nodes.size(); ++node_index) { auto& this_node = nodes[node_index]; for (std::size_t other_index = 0; other_index < node_index; ++other_index) { if (adjacency_data.edge_exists( this_node.vertex, nodes[other_index].vertex)) { this_node.earlier_neighbour_node_indices.emplace_back(other_index); } } } } const ColouringPriority::Nodes& ColouringPriority::get_nodes() const { return m_nodes; } // GCOVR_EXCL_START // currently used only within a tket assert macro string ColouringPriority::print_raw_data(bool relabel_to_simplify) const { map<std::size_t, std::size_t> old_vertex_to_new_vertex; if (relabel_to_simplify) { for (std::size_t i = 0; i < m_nodes.size(); ++i) { old_vertex_to_new_vertex[m_nodes[i].vertex] = i; } } else { for (const auto& node : m_nodes) { const auto v = node.vertex; old_vertex_to_new_vertex[v] = v; } } map<std::size_t, set<std::size_t>> data; for (const auto& node : m_nodes) { const auto this_v = old_vertex_to_new_vertex.at(node.vertex); const auto& earlier_v_indices = node.earlier_neighbour_node_indices; for (std::size_t i : earlier_v_indices) { const auto other_v = old_vertex_to_new_vertex.at(m_nodes[i].vertex); data[this_v].insert(other_v); data[other_v].insert(this_v); } } // Compress: remove (i,j) edges if i>j. { vector<std::size_t> v_to_erase; for (auto& entry : data) { v_to_erase.clear(); for (auto v : entry.second) { if (v < entry.first) { v_to_erase.push_back(v); } } for (auto v : v_to_erase) { entry.second.erase(v); } } } std::stringstream ss; ss << "\nNeighbours:\nconst std::map<std::size_t, std::vector<std::size_t>> " "data { "; for (const auto& entry : data) { if (!entry.second.empty()) { ss << "\n { " << entry.first << ", { "; for (auto v : entry.second) { ss << v << ", "; } ss << "} },"; } } ss << "\n};\n\n"; return ss.str(); } // GCOVR_EXCL_STOP ColouringPriority::ColouringPriority( const AdjacencyData& adjacency_data, const set<std::size_t>& vertices_in_component, const set<std::size_t>& initial_clique) : m_initial_clique(initial_clique) { fill_initial_node_sequence( m_nodes, adjacency_data, vertices_in_component, initial_clique); fill_node_dependencies(m_nodes, adjacency_data); } const set<std::size_t>& ColouringPriority::get_initial_clique() const { return m_initial_clique; } } // namespace graphs } // namespace tket
tket/tket/src/Graphs/ColouringPriority.cpp/0
{ "file_path": "tket/tket/src/Graphs/ColouringPriority.cpp", "repo_id": "tket", "token_count": 2695 }
385
// 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 "tket/Mapping/RoutingMethodJson.hpp" #include "tket/Mapping/LexiLabelling.hpp" namespace tket { void to_json(nlohmann::json& j, const RoutingMethod& rm) { j = rm.serialize(); } void from_json(const nlohmann::json& /*j*/, RoutingMethod& rm) { rm = RoutingMethod(); } void to_json(nlohmann::json& j, const std::vector<RoutingMethodPtr>& rmp_v) { for (const auto& r : rmp_v) { j.push_back(*r); } } void from_json(const nlohmann::json& j, std::vector<RoutingMethodPtr>& rmp_v) { for (const auto& c : j) { std::string name = c.at("name").get<std::string>(); if (name == "LexiLabellingMethod") { rmp_v.push_back(std::make_shared<LexiLabellingMethod>( LexiLabellingMethod::deserialize(c))); } else if (name == "LexiRouteRoutingMethod") { rmp_v.push_back(std::make_shared<LexiRouteRoutingMethod>( LexiRouteRoutingMethod::deserialize(c))); } else if (name == "RoutingMethod") { rmp_v.push_back(std::make_shared<RoutingMethod>()); } else if (name == "AASRouteRoutingMethod") { rmp_v.push_back(std::make_shared<AASRouteRoutingMethod>( AASRouteRoutingMethod::deserialize(c))); } else if (name == "AASLabellingMethod") { rmp_v.push_back(std::make_shared<AASLabellingMethod>( AASLabellingMethod::deserialize(c))); } else if (name == "MultiGateReorderRoutingMethod") { rmp_v.push_back(std::make_shared<MultiGateReorderRoutingMethod>( MultiGateReorderRoutingMethod::deserialize(c))); } else if (name == "BoxDecompositionRoutingMethod") { rmp_v.push_back(std::make_shared<BoxDecompositionRoutingMethod>( BoxDecompositionRoutingMethod::deserialize(c))); } else { std::logic_error( "Deserialization for given RoutingMethod not supported."); } } } } // namespace tket
tket/tket/src/Mapping/RoutingMethodJson.cpp/0
{ "file_path": "tket/tket/src/Mapping/RoutingMethodJson.cpp", "repo_id": "tket", "token_count": 923 }
386
// 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 "tket/Placement/Placement.hpp" namespace tket { GraphPlacement::Frontier::Frontier(const Circuit& _circ) : circ(_circ) { VertexVec input_slice; quantum_in_edges = std::make_shared<unit_frontier_t>(); boolean_in_edges = std::make_shared<b_frontier_t>(); for (const Qubit& qb : circ.all_qubits()) { Vertex input = circ.get_in(qb); input_slice.push_back(input); Edge candidate = circ.get_nth_out_edge(input, 0); quantum_in_edges->insert({qb, circ.skip_irrelevant_edges(candidate)}); } for (const Bit& bit : circ.all_bits()) { Vertex input = circ.get_in(bit); EdgeVec candidates = circ.get_nth_b_out_bundle(input, 0); boolean_in_edges->insert({bit, candidates}); } CutFrontier next_cut = circ.next_cut(quantum_in_edges, boolean_in_edges); slice = next_cut.slice; quantum_out_edges = next_cut.u_frontier; } void GraphPlacement::Frontier::next_slicefrontier() { quantum_in_edges = std::make_shared<unit_frontier_t>(); boolean_in_edges = std::make_shared<b_frontier_t>(); for (const std::pair<UnitID, Edge>& pair : quantum_out_edges->get<TagKey>()) { Edge new_e = circ.skip_irrelevant_edges(pair.second); quantum_in_edges->insert({pair.first, new_e}); Vertex targ = circ.target(new_e); EdgeVec targ_classical_ins = circ.get_in_edges_of_type(targ, EdgeType::Boolean); boolean_in_edges->insert( {Bit("frontier_bit", pair.first.index()), targ_classical_ins}); } CutFrontier next_cut = circ.next_cut(quantum_in_edges, boolean_in_edges); slice = next_cut.slice; quantum_out_edges = next_cut.u_frontier; } } // namespace tket
tket/tket/src/Placement/Frontier.cpp/0
{ "file_path": "tket/tket/src/Placement/Frontier.cpp", "repo_id": "tket", "token_count": 811 }
387
// 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 "tket/Transformations/CliffordReductionPass.hpp" #include "tket/Circuit/DAGDefs.hpp" #include "tket/PauliGraph/ConjugatePauliFunctions.hpp" namespace tket { /** * Finds Clifford circuit C such that * R[p](a); R[q](b) = C; RZ(a); RZ(b); C^\dagger if p==q or * C; RZ(a); RY(b); C^\dagger if p!=q */ static const std::map<std::pair<Pauli, Pauli>, std::list<OpType>> mapping_to_zz_or_zy_lut{ {{Pauli::X, Pauli::X}, {OpType::H}}, {{Pauli::X, Pauli::Y}, {OpType::H, OpType::Z}}, {{Pauli::X, Pauli::Z}, {OpType::H, OpType::S}}, {{Pauli::Y, Pauli::X}, {OpType::V, OpType::S}}, {{Pauli::Y, Pauli::Y}, {OpType::V}}, {{Pauli::Y, Pauli::Z}, {OpType::V, OpType::Z}}, {{Pauli::Z, Pauli::X}, {OpType::S}}, {{Pauli::Z, Pauli::Y}, {}}, {{Pauli::Z, Pauli::Z}, {}}, }; static const std::map<Pauli, OpType> pauli_to_pauli_gate_lut{ {Pauli::X, OpType::X}, {Pauli::Y, OpType::Y}, {Pauli::Z, OpType::Z}, }; /** * Consider an interaction of R[p0, p1](+-0.5); R[q0, q1](+-0.5) * where p0, p1, q0, q1 in {X, Y, Z}. * Returns the equivalent replacement circuit with fewer 2qb interactions. */ static Circuit interaction_replacement(const InteractionMatch &match) { const Pauli &p0 = match.point0.p; const Pauli &p1 = match.point1.p; const Pauli &q0 = match.rev0.p; const Pauli &q1 = match.rev1.p; Circuit replacement(2); if (match.point0.phase ^ match.point1.phase) { replacement.add_op<unsigned>(pauli_to_pauli_gate_lut.at(p0), {0}); replacement.add_op<unsigned>(pauli_to_pauli_gate_lut.at(p1), {1}); replacement.add_phase(0.5); } if (p0 == q0) { if (p1 == q1) { // R[p0, p1](1) = R[p0, I](1); R[I, p1](1) OpType op0 = pauli_to_pauli_gate_lut.at(p0); OpType op1 = pauli_to_pauli_gate_lut.at(p1); replacement.add_op<unsigned>(op0, {0}); replacement.add_op<unsigned>(op1, {1}); replacement.add_phase(-0.5); } else { // Map to R[Z, Z](0.5); R[Z, Y](0.5) Circuit basis_change(2); std::list<OpType> ops0 = mapping_to_zz_or_zy_lut.at({p0, q0}); std::list<OpType> ops1 = mapping_to_zz_or_zy_lut.at({p1, q1}); for (OpType op : ops0) { basis_change.add_op<unsigned>(op, {0}); } for (OpType op : ops1) { basis_change.add_op<unsigned>(op, {1}); } replacement.append(basis_change); replacement.add_op<unsigned>(OpType::V, {1}); replacement.add_op<unsigned>(OpType::ZZMax, {0, 1}); replacement.append(basis_change.dagger()); } } else { if (p1 == q1) { // Map to R[Z, Z](0.5); R[Y, Z](0.5) Circuit basis_change(2); std::list<OpType> ops0 = mapping_to_zz_or_zy_lut.at({p0, q0}); std::list<OpType> ops1 = mapping_to_zz_or_zy_lut.at({p1, q1}); for (OpType op : ops0) { basis_change.add_op<unsigned>(op, {0}); } for (OpType op : ops1) { basis_change.add_op<unsigned>(op, {1}); } replacement.append(basis_change); replacement.add_op<unsigned>(OpType::V, {0}); replacement.add_op<unsigned>(OpType::ZZMax, {0, 1}); replacement.append(basis_change.dagger()); } else { // Map to R[Z, Z](0.5); R[Y, Y](0.5) Circuit basis_change(2); std::list<OpType> ops0 = mapping_to_zz_or_zy_lut.at({p0, q0}); std::list<OpType> ops1 = mapping_to_zz_or_zy_lut.at({p1, q1}); for (OpType op : ops0) { basis_change.add_op<unsigned>(op, {0}); } for (OpType op : ops1) { basis_change.add_op<unsigned>(op, {1}); } replacement.append(basis_change); replacement.add_op<unsigned>(OpType::H, {0}); replacement.add_op<unsigned>(OpType::H, {1}); replacement.add_op<unsigned>(OpType::Z, {0}); replacement.add_op<unsigned>(OpType::Z, {1}); replacement.add_op<unsigned>(OpType::ZZMax, {0, 1}); replacement.add_op<unsigned>(OpType::H, {0}); replacement.add_op<unsigned>(OpType::H, {1}); replacement.add_op<unsigned>(OpType::SWAP, {0, 1}); replacement.add_phase(0.25); replacement.append(basis_change.dagger()); } } if (match.rev0.phase ^ match.rev1.phase) { replacement.add_op<unsigned>(pauli_to_pauli_gate_lut.at(q0), {0}); replacement.add_op<unsigned>(pauli_to_pauli_gate_lut.at(q1), {1}); replacement.add_phase(0.5); } return replacement; } /** * Given a 2qb Clifford gate, returns just the local operations applied around * the maximally-entangling gadget. */ static Circuit local_cliffords(OpType op) { Circuit locals(2); switch (op) { case OpType::CX: { locals.add_op<unsigned>(OpType::Sdg, {0}); locals.add_op<unsigned>(OpType::Vdg, {1}); break; } case OpType::CZ: { locals.add_op<unsigned>(OpType::Sdg, {0}); locals.add_op<unsigned>(OpType::Sdg, {1}); locals.add_phase(0.25); break; } case OpType::CY: { locals.add_op<unsigned>(OpType::Sdg, {0}); locals.add_op<unsigned>(OpType::V, {1}); locals.add_op<unsigned>(OpType::Sdg, {1}); locals.add_op<unsigned>(OpType::Vdg, {1}); locals.add_phase(0.25); break; } case OpType::ZZMax: { break; } default: { throw CircuitInvalidity( "Attempting to replace non-Clifford gate with Clifford " "optimisation"); break; } } return locals; } void CliffordReductionPass::insert_interaction_point(InteractionPoint ip) { itable.insert(ip); Vertex next = circ.target(ip.e); port_t next_p = circ.get_target_port(ip.e); bool commute = true; while (commute) { if (v_to_depth.find(next) == v_to_depth.end()) { commute = false; continue; } Op_ptr op = circ.get_Op_ptr_from_Vertex(next); if (!op->get_desc().is_gate()) { commute = false; continue; } OpType type = op->get_type(); switch (type) { case OpType::H: case OpType::S: case OpType::Sdg: case OpType::V: case OpType::Vdg: case OpType::X: case OpType::Y: case OpType::Z: { std::pair<Pauli, bool> new_basis = conjugate_Pauli(type, ip.p, true); ip.p = new_basis.first; ip.phase ^= new_basis.second; break; } case OpType::SWAP: { next_p = 1 - next_p; break; } default: { if (!circ.commutes_with_basis(next, ip.p, PortType::Target, next_p)) { commute = false; continue; } break; } } ip.e = circ.get_nth_out_edge(next, next_p); auto inserted = itable.insert(ip); commute = inserted.second; if (!commute) { // Now `inserted.first` points to the element of the table that // blocked insertion, i.e. had the same source/edge combination. // Check that its `p` and `phase` are correct: if not, something has // gone wrong. auto blocker = inserted.first; TKET_ASSERT(blocker->p == ip.p && blocker->phase == ip.phase); } next = circ.target(ip.e); next_p = circ.get_target_port(ip.e); } } std::optional<InteractionMatch> CliffordReductionPass::search_back_for_match( const RevInteractionPoint &rip0, const RevInteractionPoint &rip1) const { RevInteractionPoint point[2]; point[0] = rip0; point[1] = rip1; std::map<Edge, RevInteractionPoint> point_lookup; IndexMap im = circ.index_map(); // interactions met when commuting back; point lists are in causal order of // circuit: std::map<IVertex, std::list<InteractionPoint>> candidates[2]; for (unsigned i = 0; i < 2; ++i) { // Commute edge i back as far as possible bool commute = true; while (commute) { point_lookup.insert({point[i].e, point[i]}); auto r = itable.get<TagEdge>().equal_range(point[i].e); for (auto it = r.first; it != r.second; ++it) { Vertex v = it->source; candidates[i][{im.at(v), v}].push_front(*it); } Vertex pred = circ.source(point[i].e); port_t pred_port = circ.get_source_port(point[i].e); Op_ptr pred_op = circ.get_Op_ptr_from_Vertex(pred); if (!pred_op->get_desc().is_gate()) { commute = false; continue; } OpType type = pred_op->get_type(); switch (type) { case OpType::H: case OpType::S: case OpType::Sdg: case OpType::V: case OpType::Vdg: case OpType::X: case OpType::Y: case OpType::Z: { std::pair<Pauli, bool> new_basis = conjugate_Pauli(type, point[i].p); point[i].p = new_basis.first; point[i].phase ^= new_basis.second; break; } case OpType::SWAP: { pred_port = 1 - pred_port; break; } default: { commute = circ.commutes_with_basis( pred, point[i].p, PortType::Source, pred_port); break; } } point[i].e = circ.get_nth_in_edge(pred, pred_port); } } // Check for matching interactions for (const std::pair<const IVertex, std::list<InteractionPoint>> &pair : candidates[0]) { auto found = candidates[1].find(pair.first); if (found != candidates[1].end()) { std::optional<std::pair<InteractionPoint, InteractionPoint>> insert_point = valid_insertion_point(pair.second, found->second); if (insert_point) { InteractionMatch match = { insert_point->first, insert_point->second, point_lookup.at(insert_point->first.e), point_lookup.at(insert_point->second.e)}; if (!allow_swaps) { if (match.point0.p != match.rev0.p && match.point1.p != match.rev1.p) continue; } return match; } } } return std::nullopt; } void CliffordReductionPass::process_new_interaction(const Vertex &inter) { // Process the vertex as well as any new 2qb Cliffords that get inserted // while doing so (and so on until there are none left to process). std::list<Vertex> to_process = {inter}; while (!to_process.empty()) { Vertex v = to_process.front(); to_process.pop_front(); Op_ptr op = circ.get_Op_ptr_from_Vertex(v); Pauli basis0 = *op->commuting_basis(0); Pauli basis1 = *op->commuting_basis(1); EdgeVec ins = circ.get_in_edges(v); RevInteractionPoint rip0 = {ins.at(0), basis0, false}; RevInteractionPoint rip1 = {ins.at(1), basis1, false}; std::optional<InteractionMatch> match = search_back_for_match(rip0, rip1); if (match) { Circuit replacement = interaction_replacement(*match); Subcircuit site; site.q_in_hole = site.q_out_hole = {match->point0.e, match->point1.e}; Subcircuit inserted = substitute(replacement, site); const Vertex &source = match->point0.source; Circuit source_locals = local_cliffords(circ.get_OpType_from_Vertex(source)); Subcircuit source_site; source_site.q_in_hole = circ.get_in_edges(source); source_site.q_out_hole = { circ.get_nth_out_edge(source, 0), circ.get_nth_out_edge(source, 1)}; source_site.verts.insert(source); substitute(source_locals, source_site); Circuit v_locals = local_cliffords(op->get_type()); Subcircuit v_site; v_site.q_in_hole = circ.get_in_edges(v); v_site.q_out_hole = { circ.get_nth_out_edge(v, 0), circ.get_nth_out_edge(v, 1)}; v_site.verts.insert(v); substitute(v_locals, v_site); for (const Vertex &new_v : inserted.verts) { if (circ.n_in_edges(new_v) == 2 && circ.get_OpType_from_Vertex(new_v) != OpType::SWAP) { to_process.push_back(new_v); break; } } success = true; } else { std::vector<std::optional<Edge>> outs = circ.get_linear_out_edges(v); InteractionPoint ip0 = {*outs.at(0), v, basis0, false}; insert_interaction_point(ip0); InteractionPoint ip1 = {*outs.at(1), v, basis1, false}; insert_interaction_point(ip1); } } } Subcircuit CliffordReductionPass::substitute( const Circuit &to_insert, const Subcircuit &to_replace) { unsigned q_width = to_replace.q_in_hole.size(); TKET_ASSERT(q_width == 2); // Construct tables of predecessors, successors, units, in-edges, out-edges. // Only quantum circuit replacments here so don't care about classical stuff std::vector<VertPort> preds(q_width); std::vector<VertPort> succs(q_width); std::vector<UnitID> units(q_width); std::vector<Edge> in_edges(q_width); std::vector<Edge> out_edges(q_width); for (unsigned qi = 0; qi < q_width; ++qi) { const Edge &in = to_replace.q_in_hole.at(qi); const Edge &out = to_replace.q_out_hole.at(qi); preds[qi] = {circ.source(in), circ.get_source_port(in)}; succs[qi] = {circ.target(out), circ.get_target_port(out)}; units[qi] = e_to_unit.at(in); in_edges[qi] = in; out_edges[qi] = out; TKET_ASSERT(in == out || circ.target(in) == circ.source(out)); } // List of points that will be invalidated by the substitution. std::list<InteractionPoint> invalidated_points; // Lists of points having the same "in"/"out" edge as the replacement: // These are all invalidated (though the "in" ones can be replaced later // with the new edge). std::vector<std::list<InteractionPoint>> points_with_in(q_width); std::vector<std::list<InteractionPoint>> points_with_out(q_width); for (unsigned qi = 0; qi < q_width; ++qi) { auto r = itable.get<TagEdge>().equal_range(in_edges[qi]); for (auto it = r.first; it != r.second; it++) { points_with_in[qi].push_back(*it); invalidated_points.push_back(*it); } r = itable.get<TagEdge>().equal_range(out_edges[qi]); for (auto it = r.first; it != r.second; it++) { points_with_out[qi].push_back(*it); invalidated_points.push_back(*it); } } // For any (e0, v0) in points_with_out, any point (e1, v0) where e1 is in // the causal future of e0 is also invalidated. Calculate all the future // edges. EdgeList future_edges; VertexSet v_frontier; // keep track of visited vertices VertexSet visited; for (unsigned qi = 0; qi < q_width; ++qi) { Vertex target = circ.target(out_edges[qi]); visited.insert(target); v_frontier.insert(target); } while (!v_frontier.empty()) { EdgeSet out_edges; for (auto v : v_frontier) { if (v_to_depth.find(v) != v_to_depth.end()) { EdgeVec v_out_edges = circ.get_out_edges_of_type(v, EdgeType::Quantum); out_edges.insert(v_out_edges.begin(), v_out_edges.end()); } } future_edges.insert(future_edges.end(), out_edges.begin(), out_edges.end()); VertexSet new_v_frontier; for (auto e : out_edges) { Vertex target = circ.target(e); auto it = visited.insert(target); if (it.second) { // add vertex to the next frontier if the vertex has not been visited new_v_frontier.insert(target); } } v_frontier = std::move(new_v_frontier); } // Invalidate the (e1, v0) as above. VertexSet invalid_sources; for (unsigned qi = 0; qi < q_width; ++qi) { for (auto ip : points_with_out[qi]) { TKET_ASSERT(ip.e == out_edges[qi]); invalid_sources.insert(ip.source); } } for (auto e1 : future_edges) { auto r = itable.get<TagEdge>().equal_range(e1); for (auto it = r.first; it != r.second; ++it) { if (invalid_sources.find(it->source) != invalid_sources.end()) { invalidated_points.push_back(*it); } } } // Erase the invalidated points from the table. for (auto ip : invalidated_points) { itable.erase(ip.key()); } // Erase edges from e_to_unit for (unsigned qi = 0; qi < q_width; ++qi) { e_to_unit.erase(in_edges[qi]); e_to_unit.erase(out_edges[qi]); // Depth of to_replace is at most 1, so there are no other edges } // Remove replaced vertices from depth and units maps and erase all points // from the itable that have a replaced vertex as source. for (const Vertex &v : to_replace.verts) { v_to_depth.erase(v); v_to_units.erase(v); auto r = itable.get<TagSource>().equal_range(v); for (auto next = r.first; next != r.second; r.first = next) { ++next; itable.erase(itable.project<TagKey>(r.first)); } } circ.substitute(to_insert, to_replace); // Update the tables of in and out edges, and amend the stored points for (unsigned qi = 0; qi < q_width; ++qi) { in_edges[qi] = circ.get_nth_out_edge(preds[qi].first, preds[qi].second); out_edges[qi] = circ.get_nth_in_edge(succs[qi].first, succs[qi].second); for (InteractionPoint &ip : points_with_in[qi]) { ip.e = in_edges[qi]; } } // Construct inserted Subcircuit, update e_to_unit and v_to_units, and // add new vertices to v_to_depth, with (temporary) value 0. Subcircuit inserted; for (unsigned qi = 0; qi < q_width; ++qi) { Edge in = in_edges[qi]; inserted.q_in_hole.push_back(in); Edge out = out_edges[qi]; inserted.q_out_hole.push_back(out); while (in != out) { Vertex next = circ.target(in); inserted.verts.insert(next); e_to_unit.insert({in, units[qi]}); v_to_depth.insert({next, 0}); v_to_units[next].insert(units[qi]); in = circ.get_nth_out_edge(next, circ.get_target_port(in)); } e_to_unit.insert({in, units[qi]}); } // Now `v_to_depth` is 0 at all `inserted.verts`. Fix this and propagate // updates to the depth map into the future cone, ensuring that the depths // are strictly increasing along wires. Stop when we reach a vertex that // isn't already in v_to_depth (because we haven't processed it yet). for (unsigned qi = 0; qi < q_width; ++qi) { Edge in = in_edges[qi]; Vertex next = circ.target(in); if (next != succs[qi].first) { if (v_to_depth.at(preds[qi].first) >= v_to_depth[next]) { // We may have already set v_to_depth[next] to a higher value // when tracing another qubit, so the check above is necessary. v_to_depth[next] = v_to_depth.at(preds[qi].first) + 1; } std::function<bool(const Vertex &, const Vertex &)> c = [&](const Vertex &a, const Vertex &b) { unsigned deptha = v_to_depth.at(a); unsigned depthb = v_to_depth.at(b); if (deptha == depthb) { unit_set_t unitsa = v_to_units.at(a); unit_set_t unitsb = v_to_units.at(b); return unitsa < unitsb; } return deptha < depthb; }; std::set<Vertex> to_search; to_search.insert(next); while (!to_search.empty()) { Vertex v = *std::min_element(to_search.begin(), to_search.end(), c); to_search.erase(v); unsigned v_depth = v_to_depth.at(v); EdgeVec outs = circ.get_all_out_edges(v); for (const Edge &e : outs) { Vertex succ = circ.target(e); std::map<Vertex, unsigned>::iterator succ_it = v_to_depth.find(succ); if (succ_it != v_to_depth.end()) { if (succ_it->second <= v_depth) { succ_it->second = v_depth + 1; if (v_depth >= current_depth) { current_depth = v_depth + 1; } to_search.insert(succ); } } } } } } // Re-insert all the interaction points we erased above. for (unsigned qi = 0; qi < q_width; ++qi) { for (const InteractionPoint &ip : points_with_in[qi]) { insert_interaction_point(ip); } } return inserted; } std::optional<Edge> CliffordReductionPass::find_earliest_successor( const Edge &source, const EdgeSet &candidates) const { typedef std::function<bool(Vertex, Vertex)> Comp; Comp c = [&](Vertex a, Vertex b) { unsigned deptha = v_to_depth.at(a); unsigned depthb = v_to_depth.at(b); if (deptha == depthb) { unit_set_t unitsa = v_to_units.at(a); unit_set_t unitsb = v_to_units.at(b); return unitsa < unitsb; } return deptha < depthb; }; std::set<Vertex, Comp> to_search(c); to_search.insert(circ.target(source)); while (!to_search.empty()) { Vertex v = *to_search.begin(); to_search.erase(to_search.begin()); EdgeVec outs = circ.get_all_out_edges(v); for (const Edge &e : outs) { if (candidates.find(e) != candidates.end()) return e; Vertex succ = circ.target(e); if (v_to_depth.find(succ) != v_to_depth.end()) to_search.insert(succ); } } return std::nullopt; } std::optional<std::pair<InteractionPoint, InteractionPoint>> CliffordReductionPass::valid_insertion_point( const std::list<InteractionPoint> &seq0, const std::list<InteractionPoint> &seq1) const { // seq0 is chain of edges (in temporal order) from the first qubit // likewise seq1 for the other qubit InteractionPoint seq0max = seq0.back(); InteractionPoint seq1max = seq1.back(); if (circ.in_causal_order( circ.source(seq1max.e), circ.target(seq0max.e), true, v_to_depth, v_to_units, false)) { // Search for any points in seq1 from future of seq0max EdgeSet candidates; std::map<Edge, InteractionPoint> lookup; for (const InteractionPoint &ip : seq1) { candidates.insert(ip.e); lookup.insert({ip.e, ip}); } std::optional<Edge> successor = find_earliest_successor(seq0max.e, candidates); if (!successor || successor == seq1.front().e) return std::nullopt; Vertex v = circ.source(*successor); port_t p = circ.get_source_port(*successor); if (circ.get_OpType_from_Vertex(v) == OpType::SWAP) p = 1 - p; return {{seq0max, lookup.at(circ.get_nth_in_edge(v, p))}}; } else if (circ.in_causal_order( circ.source(seq0max.e), circ.target(seq1max.e), true, v_to_depth, v_to_units, false)) { // Search for any points in seq0 from future of seq1max EdgeSet candidates; std::map<Edge, InteractionPoint> lookup; for (const InteractionPoint &ip : seq0) { candidates.insert(ip.e); lookup.insert({ip.e, ip}); } std::optional<Edge> successor = find_earliest_successor(seq1max.e, candidates); if (!successor || successor == seq0.front().e) return std::nullopt; Vertex v = circ.source(*successor); port_t p = circ.get_source_port(*successor); if (circ.get_OpType_from_Vertex(v) == OpType::SWAP) p = 1 - p; return {{lookup.at(circ.get_nth_in_edge(v, p)), seq1max}}; } else { // seq0max and seq1max are space-like separated return {{seq0max, seq1max}}; } } CliffordReductionPass::CliffordReductionPass(Circuit &c, bool swaps) : circ(c), itable(), v_to_depth(), success(false), current_depth(1), allow_swaps(swaps) { v_to_units = circ.vertex_unit_map(); e_to_unit = circ.edge_unit_map(); } bool CliffordReductionPass::reduce_circuit(Circuit &circ, bool allow_swaps) { CliffordReductionPass context(circ, allow_swaps); SliceVec slices = circ.get_slices(); for (const Vertex &in : circ.all_inputs()) { context.v_to_depth.insert({in, 0}); } // Process all 2qb Clifford vertices. for (const Slice &sl : slices) { for (const Vertex &v : sl) { context.v_to_depth.insert({v, context.current_depth}); Op_ptr op = circ.get_Op_ptr_from_Vertex(v); if (!op->get_desc().is_gate()) continue; EdgeVec ins = circ.get_in_edges(v); std::vector<std::optional<Edge>> outs = circ.get_linear_out_edges(v); OpType type = op->get_type(); std::list<InteractionPoint> new_points; switch (type) { case OpType::H: case OpType::S: case OpType::Sdg: case OpType::V: case OpType::Vdg: case OpType::X: case OpType::Y: case OpType::Z: { auto r = context.itable.get<TagEdge>().equal_range(ins[0]); for (auto it = r.first; it != r.second; ++it) { InteractionPoint ip = *it; std::pair<Pauli, bool> new_basis = conjugate_Pauli(type, ip.p, true); ip.p = new_basis.first; ip.phase ^= new_basis.second; ip.e = *outs[0]; new_points.push_back(ip); } break; } case OpType::SWAP: { auto r0 = context.itable.get<TagEdge>().equal_range(ins[0]); for (auto it = r0.first; it != r0.second; ++it) { InteractionPoint ip = *it; ip.e = *outs[1]; new_points.push_back(ip); } auto r1 = context.itable.get<TagEdge>().equal_range(ins[1]); for (auto it = r1.first; it != r1.second; ++it) { InteractionPoint ip = *it; ip.e = *outs[0]; new_points.push_back(ip); } break; } default: { for (unsigned i = 0; i < ins.size(); ++i) { auto r = context.itable.get<TagEdge>().equal_range(ins[i]); for (auto it = r.first; it != r.second; ++it) { InteractionPoint ip = *it; if (circ.commutes_with_basis(v, ip.p, PortType::Target, i)) { ip.e = *outs[i]; new_points.push_back(ip); } } } break; } } for (const InteractionPoint &ip : new_points) { context.itable.insert(ip); } switch (type) { case OpType::CX: case OpType::CY: case OpType::CZ: case OpType::ZZMax: { context.process_new_interaction(v); break; } default: { break; } } } ++context.current_depth; } if (allow_swaps) { circ.replace_SWAPs(); } return context.success; } namespace Transforms { Transform clifford_reduction(bool allow_swaps) { return Transform([=](Circuit &circ) { return CliffordReductionPass::reduce_circuit(circ, allow_swaps); }); } } // namespace Transforms CliffordReductionPassTester::CliffordReductionPassTester(Circuit &circ) : context(circ, true) { // populate v_to_depth for (const Vertex &in : circ.all_inputs()) { context.v_to_depth.insert({in, 0}); } SliceVec slices = circ.get_slices(); for (const Slice &sl : slices) { for (const Vertex &v : sl) { context.v_to_depth.insert({v, context.current_depth}); } } } std::optional<std::pair<InteractionPoint, InteractionPoint>> CliffordReductionPassTester::valid_insertion_point( const std::list<InteractionPoint> &seq0, const std::list<InteractionPoint> &seq1) const { return context.valid_insertion_point(seq0, seq1); } } // namespace tket
tket/tket/src/Transformations/CliffordReductionPass.cpp/0
{ "file_path": "tket/tket/src/Transformations/CliffordReductionPass.cpp", "repo_id": "tket", "token_count": 12251 }
388
// 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 "tket/Transformations/SingleQubitSquash.hpp" #include <cstddef> #include <numeric> #include "Circuit/Command.hpp" #include "Gate/GatePtr.hpp" #include "tket/Circuit/Circuit.hpp" #include "tket/Circuit/DAGDefs.hpp" #include "tket/Gate/Gate.hpp" namespace tket { SingleQubitSquash::SingleQubitSquash( std::unique_ptr<AbstractSquasher> squasher, Circuit &circ, bool reversed, bool always_squash_symbols) : squasher_(std::move(squasher)), circ_(circ), reversed_(reversed), always_squash_symbols_(always_squash_symbols) {} SingleQubitSquash::SingleQubitSquash(const SingleQubitSquash &other) : squasher_(other.squasher_->clone()), circ_(other.circ_), reversed_(other.reversed_), always_squash_symbols_(other.always_squash_symbols_) {} bool SingleQubitSquash::squash() { bool success = false; VertexVec inputs = circ_.q_inputs(); VertexVec outputs = circ_.q_outputs(); for (unsigned i = 0; i < circ_.n_qubits(); ++i) { Edge in = circ_.get_nth_out_edge(inputs[i], 0); Edge out = circ_.get_nth_in_edge(outputs[i], 0); if (reversed_) { success |= squash_between(out, in); } else { success |= squash_between(in, out); } } return success; } bool SingleQubitSquash::squash_between(const Edge &in, const Edge &out) { squasher_->clear(); Edge e = in; Vertex v = next_vertex(e); std::vector<Gate_ptr> single_chain; VertexVec bin; bool success = false; Condition condition = std::nullopt; while (true) { Op_ptr v_op = circ_.get_Op_ptr_from_Vertex(v); OpType v_type = v_op->get_type(); bool move_to_next_vertex = false; bool reset_search = false; Condition this_condition = std::nullopt; if (v_type == OpType::Conditional) { // => deal with conditional case this_condition = get_condition(v); v_op = static_cast<const Conditional &>(*v_op).get_op(); v_type = v_op->get_type(); if (single_chain.empty()) { condition = this_condition; } } bool is_squashable = circ_.n_in_edges_of_type(v, EdgeType::Quantum) == 1 && is_gate_type(v_type) && squasher_->accepts(as_gate_ptr(v_op)); if (e != out && condition == this_condition && is_squashable) { // => add gate to current squash squasher_->append(as_gate_ptr(reversed_ ? v_op->dagger() : v_op)); move_to_next_vertex = true; } else { // => squash and reset reset_search = true; if (single_chain.empty()) { // => nothing to do, move on move_to_next_vertex = true; } else { Circuit sub; std::optional<Pauli> commutation_colour = std::nullopt; if (is_gate_type(v_type) && v_op->n_qubits() > 1) { commutation_colour = circ_.commuting_basis(v, PortType::Target, next_port(e)); move_to_next_vertex = true; } auto pair = squasher_->flush(commutation_colour); sub = pair.first; Gate_ptr left_over_gate = pair.second; if (left_over_gate != nullptr) { // => commute leftover through before squashing insert_left_over_gate(left_over_gate, next_edge(v, e), condition); left_over_gate = nullptr; } if (reversed_) { sub = sub.dagger(); } // we squash if the replacement is at least as good as the original // (and it's not a no-op) if (sub_is_better(sub, single_chain)) { substitute(sub, bin, e, condition); success = true; } } } if (e == out || is_last_optype(v_type)) { squasher_->clear(); break; } if (move_to_next_vertex) { if (is_gate_type(v_type)) { bin.push_back(v); single_chain.push_back(as_gate_ptr(v_op)); } e = next_edge(v, e); v = next_vertex(e); } if (reset_search) { bin.clear(); single_chain.clear(); squasher_->clear(); condition = std::nullopt; } } return success; } void SingleQubitSquash::substitute( const Circuit &sub, const VertexVec &single_chain, Edge &e, const Condition &condition) { // backup edge VertPort backup = {next_vertex(e), next_port(e)}; if (condition) { circ_.substitute_conditional( sub, single_chain.front(), Circuit::VertexDeletion::No); } else { circ_.substitute(sub, single_chain.front(), Circuit::VertexDeletion::No); } circ_.remove_vertices( VertexSet{single_chain.begin(), single_chain.end()}, Circuit::GraphRewiring::Yes, Circuit::VertexDeletion::Yes); // restore backup e = prev_edge(backup); } void SingleQubitSquash::insert_left_over_gate( Op_ptr left_over, const Edge &e, const Condition &condition) { if (reversed_) { left_over = left_over->dagger(); } EdgeVec preds; op_signature_t sigs; if (condition) { left_over = std::make_shared<Conditional>( left_over, (unsigned)condition->first.size(), condition->second); } Vertex new_v = circ_.add_vertex(left_over); if (condition) { for (const VertPort &vp : condition->first) { preds.push_back(circ_.get_nth_out_edge(vp.first, vp.second)); sigs.push_back(EdgeType::Boolean); } } preds.push_back(e); sigs.push_back(EdgeType::Quantum); circ_.rewire(new_v, preds, sigs); } bool SingleQubitSquash::sub_is_better( const Circuit &sub, const std::vector<Gate_ptr> chain) const { const unsigned n_gates = sub.n_gates(); if (n_gates > chain.size()) { return false; } if (!sub.is_symbolic() || always_squash_symbols_) { return n_gates < chain.size() || !is_equal(sub, chain, reversed_); } // For symbolic circuits, we don't want to squash gates if it blows up the // complexity of the expressions. As a crude but adequate measure, we compare // the total size of the string representations. return std::accumulate( sub.begin(), sub.end(), std::size_t{0}, [](std::size_t a, const Command &cmd) { return a + cmd.get_op_ptr()->get_name().size(); }) < std::accumulate( chain.begin(), chain.end(), std::size_t{0}, [](std::size_t a, const Gate_ptr &gpr) { return a + gpr->get_name().size(); }); } // returns a description of the condition of current vertex SingleQubitSquash::Condition SingleQubitSquash::get_condition(Vertex v) const { Op_ptr v_op = circ_.get_Op_ptr_from_Vertex(v); OpType v_type = v_op->get_type(); if (v_type != OpType::Conditional) { throw BadOpType("Cannot get condition from non-conditional OpType", v_type); } const Conditional &cond_op = static_cast<const Conditional &>(*v_op); EdgeVec ins = circ_.get_in_edges(v); Condition cond = std::pair<std::list<VertPort>, unsigned>(); for (port_t p = 0; p < cond_op.get_width(); ++p) { Edge in_p = ins.at(p); VertPort vp = {circ_.source(in_p), circ_.get_source_port(in_p)}; cond->first.push_back(vp); } cond->second = cond_op.get_value(); return cond; } // simple utils respecting reversed boolean Vertex SingleQubitSquash::next_vertex(const Edge &e) const { return reversed_ ? circ_.source(e) : circ_.target(e); } port_t SingleQubitSquash::next_port(const Edge &e) const { return reversed_ ? circ_.get_source_port(e) : circ_.get_target_port(e); } Edge SingleQubitSquash::prev_edge(const VertPort &pair) const { return reversed_ ? circ_.get_nth_out_edge(pair.first, pair.second) : circ_.get_nth_in_edge(pair.first, pair.second); } Edge SingleQubitSquash::next_edge(const Vertex &v, const Edge &e) const { return reversed_ ? circ_.get_last_edge(v, e) : circ_.get_next_edge(v, e); } bool SingleQubitSquash::is_last_optype(OpType type) const { return (reversed_ && is_initial_q_type(type)) || (!reversed_ && is_final_q_type(type)); } bool SingleQubitSquash::is_equal( const Circuit &circ, const std::vector<Gate_ptr> &gates, bool reversed) { if (reversed) { return is_equal(circ, {gates.rbegin(), gates.rend()}); } if (circ.n_qubits() != 1) { throw CircuitInvalidity("Only circuits with one qubit are supported"); } auto it1 = circ.begin(); auto it2 = gates.cbegin(); while (it1 != circ.end() && it2 != gates.end()) { const Gate_ptr op1 = as_gate_ptr(it1->get_op_ptr()); const Gate_ptr op2 = as_gate_ptr(*it2); if (!(*op1 == *op2)) { return false; } ++it1; ++it2; } if (it1 != circ.end() || it2 != gates.cend()) { return false; } return true; } } // namespace tket
tket/tket/src/Transformations/SingleQubitSquash.cpp/0
{ "file_path": "tket/tket/src/Transformations/SingleQubitSquash.cpp", "repo_id": "tket", "token_count": 3821 }
389
// 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 <tkassert/Assert.hpp> #include "tket/Utils/GraphHeaders.hpp" #include "tket/ZX/ZXDiagram.hpp" namespace tket { namespace zx { ZXVert ZXDiagram::add_vertex(ZXGen_ptr op) { ZXVertProperties vp{op}; return boost::add_vertex(vp, *graph); } ZXVert ZXDiagram::add_vertex(ZXType type, QuantumType qtype) { ZXGen_ptr op = ZXGen::create_gen(type, qtype); return add_vertex(op); } ZXVert ZXDiagram::add_vertex( ZXType type, const Expr& param, QuantumType qtype) { ZXGen_ptr op = ZXGen::create_gen(type, param, qtype); return add_vertex(op); } ZXVert ZXDiagram::add_clifford_vertex( ZXType type, bool param, QuantumType qtype) { ZXGen_ptr op = ZXGen::create_gen(type, param, qtype); return add_vertex(op); } Wire ZXDiagram::add_wire( const ZXVert& va, const ZXVert& vb, const WireProperties& prop) { auto [wire, added] = boost::add_edge(va, vb, prop, *graph); // add_edge only returns false if the graph cannot support parallel edges, but // we have set it up to allow this TKET_ASSERT(added); return wire; } Wire ZXDiagram::add_wire( const ZXVert& va, const ZXVert& vb, ZXWireType type, QuantumType qtype, std::optional<unsigned> va_port, std::optional<unsigned> vb_port) { return add_wire(va, vb, {type, qtype, va_port, vb_port}); } void ZXDiagram::remove_vertex(const ZXVert& v) { // Remove from boundary if `v` is a boundary vertex if (is_boundary_type(get_zxtype(v))) { ZXVertVec::iterator v_it = std::find(boundary.begin(), boundary.end(), v); if (v_it != boundary.end()) boundary.erase(v_it); } boost::clear_vertex(v, *graph); boost::remove_vertex(v, *graph); } void ZXDiagram::remove_wire(const Wire& w) { boost::remove_edge(w, *graph); } bool ZXDiagram::remove_wire( const ZXVert& va, const ZXVert& vb, const WireProperties& prop, ZXDiagram::WireSearchOption directed) { BGL_FORALL_OUTEDGES(va, w, *graph, ZXGraph) { if ((target(w) == vb) && (get_wire_info(w) == prop)) { remove_wire(w); return true; } } // Recheck with reverse wire direction (including ports on the two ends) if (directed == WireSearchOption::UNDIRECTED) { WireProperties rev_props = prop; rev_props.source_port = prop.target_port; rev_props.target_port = prop.source_port; return remove_wire(vb, va, rev_props, WireSearchOption::DIRECTED); } return false; } void ZXDiagram::symbol_substitution(const symbol_map_t& symbol_map) { SymEngine::map_basic_basic sub_map; for (const std::pair<const Sym, Expr>& p : symbol_map) { ExprPtr s = p.first; ExprPtr e = p.second; sub_map[s] = e; } symbol_substitution(sub_map); } void ZXDiagram::symbol_substitution( const std::map<Sym, double, SymEngine::RCPBasicKeyLess>& symbol_map) { SymEngine::map_basic_basic sub_map; for (std::pair<Sym, Expr> p : symbol_map) { ExprPtr s = p.first; ExprPtr e = Expr(p.second); sub_map[s] = e; } symbol_substitution(sub_map); } void ZXDiagram::symbol_substitution(const SymEngine::map_basic_basic& sub_map) { scalar = scalar.subs(sub_map); BGL_FORALL_VERTICES(v, *graph, ZXGraph) { ZXGen_ptr new_op = get_vertex_ZXGen_ptr(v)->symbol_substitution(sub_map); if (new_op) set_vertex_ZXGen_ptr(v, new_op); } } SymSet ZXDiagram::free_symbols() const { SymSet symbols = expr_free_symbols(get_scalar()); BGL_FORALL_VERTICES(v, *graph, ZXGraph) { const SymSet s = get_vertex_ZXGen_ptr(v)->free_symbols(); symbols.insert(s.begin(), s.end()); } return symbols; } bool ZXDiagram::is_symbolic() const { return !free_symbols().empty(); } static void check_valid_wire( const std::optional<unsigned>& port, QuantumType qtype, const std::optional<unsigned>& n_ports, std::vector<bool>& ports_found, ZXGen_ptr op) { if (port) { if (!n_ports) throw ZXError("Wire at a named port of an undirected vertex"); else if (ports_found.at(*port)) throw ZXError("Multiple wires on the same port of a vertex"); else ports_found.at(*port) = true; } else if (n_ports) throw ZXError("Wire at an unnamed port of a directed vertex"); if (!op->valid_edge(port, qtype)) throw ZXError("QuantumType of wire is incompatible with the given port"); } void ZXDiagram::check_validity() const { std::set<ZXVert> boundary_lookup; for (const ZXVert& b : boundary) { if (!is_boundary_type(get_zxtype(b))) throw ZXError("Non-boundary vertex type in boundary"); if (!boundary_lookup.insert(b).second) throw ZXError("Vertex appears in boundary multiple times"); } BGL_FORALL_VERTICES(v, *graph, ZXGraph) { ZXGen_ptr op = get_vertex_ZXGen_ptr(v); ZXType type = op->get_type(); if (is_boundary_type(type)) { if (degree(v) != 1) throw ZXError("Boundary vertex does not have degree 1"); if (boundary_lookup.find(v) == boundary_lookup.end()) throw ZXError("Vertex of boundary type is not in the boundary"); } std::optional<unsigned> n_ports = std::nullopt; if (is_directed_type(type)) { const ZXDirected& dir = static_cast<const ZXDirected&>(*op); n_ports = dir.n_ports(); } std::vector<bool> ports_found(n_ports ? *n_ports : 0, false); BGL_FORALL_OUTEDGES(v, w, *graph, ZXGraph) { check_valid_wire(source_port(w), get_qtype(w), n_ports, ports_found, op); } BGL_FORALL_INEDGES(v, w, *graph, ZXGraph) { check_valid_wire(target_port(w), get_qtype(w), n_ports, ports_found, op); } if (n_ports && !std::all_of( ports_found.begin(), ports_found.end(), [](const bool& b) { return b; })) throw ZXError("Not all ports of a directed vertex have wires connected"); } } } // namespace zx } // namespace tket
tket/tket/src/ZX/ZXDManipulation.cpp/0
{ "file_path": "tket/tket/src/ZX/ZXDManipulation.cpp", "repo_id": "tket", "token_count": 2527 }
390
// 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 "tket/Circuit/Circuit.hpp" #include "tket/Circuit/DummyBox.hpp" #include "tket/Circuit/ResourceData.hpp" namespace tket { SCENARIO("DummyBox") { GIVEN("ResourceData") { DummyBox dbox0( 1, 0, ResourceData{ {{OpType::H, ResourceBounds<unsigned>(3, 4)}}, ResourceBounds<unsigned>(2, 3), {{OpType::H, ResourceBounds<unsigned>(3)}}, ResourceBounds<unsigned>()}); DummyBox dbox1( 2, 0, ResourceData{ {{OpType::H, ResourceBounds<unsigned>(3, 4)}, {OpType::CX, ResourceBounds<unsigned>(2, 8)}}, ResourceBounds<unsigned>(2, 3), {{OpType::CX, ResourceBounds<unsigned>(2, 8)}}, ResourceBounds<unsigned>(4, 8)}); Circuit c(2); c.add_op<unsigned>(OpType::CX, {0, 1}); c.add_box(dbox0, {0}); c.add_box(dbox1, {0, 1}); ResourceData data = c.get_resources(); ResourceData expected{ {{OpType::H, ResourceBounds<unsigned>(6, 8)}, {OpType::CX, ResourceBounds<unsigned>(3, 9)}}, ResourceBounds<unsigned>(5, 7), {{OpType::H, ResourceBounds<unsigned>(3)}, {OpType::CX, ResourceBounds<unsigned>(3, 9)}}, ResourceBounds<unsigned>(5, 9)}; CHECK(data == expected); } } } // namespace tket
tket/tket/test/src/Circuit/test_DummyBox.cpp/0
{ "file_path": "tket/tket/test/src/Circuit/test_DummyBox.cpp", "repo_id": "tket", "token_count": 802 }
391
// 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. #pragma once #include <cstddef> #include <limits> namespace tket { namespace graphs { namespace tests { struct EdgeSequence; struct RandomGraphParameters; /** * Parameters to specify how to run tests. We want to generate graphs * by adding edges one-by-one. * We then colour the graphs in sequence, and check that the colouring * is valid for EVERY previous graph, and also * that the number of colours used is an increasing sequence. * (which does not GUARANTEE that the colouring is optimal, but does * give some extra confidence that it might be). */ struct EdgeSequenceColouringParameters { /** * Colour only every k graphs, so value 1 means colour EVERY graph. * Checking a colouring is much cheaper than generating it, * so we test each calculated colouring against EVERY previous graph. */ std::size_t step_skip_size = 1; /** Stop the test when you've done this many colourings. */ std::size_t max_number_of_colourings = std::numeric_limits<std::size_t>::max(); /** Stop the test when the graph has this many edges. */ std::size_t max_number_of_edges = std::numeric_limits<std::size_t>::max(); /** * This counts how many times the graph colouring function was called. * I think it's good practice to check the value at the end of a test. * The actual value is unimportant, just whether it changes between commits. * The reasons are: * (i) Check that we are actually testing something; it's all too easy * to have bugs in test data which mean we're not testing anything, * or as much as we thought. * (ii) If something changes unexpectedly, either due to the algorithms * or test data, then we have a chance of spotting it. * (iii) Although it could give a false sense of security, it's always nice * to see that a test is doing 1000 colourings, rather than just 5, say. */ std::size_t total_number_of_colourings = 0; /** * Take the parameters for generating random graphs, * actually generate them, then test the colourings. * @param parameters An object with functions to generate random graphs * of a certain type, edge-by-edge. * @param edge_sequence The object which actually calls the "parameters" * object to construct the edges, and store them. * @return The number of calculated colourings in this call. (Useful as an * extra check). */ std::size_t test_colourings( RandomGraphParameters& parameters, EdgeSequence& edge_sequence); }; } // namespace tests } // namespace graphs } // namespace tket
tket/tket/test/src/Graphs/EdgeSequenceColouringParameters.hpp/0
{ "file_path": "tket/tket/test/src/Graphs/EdgeSequenceColouringParameters.hpp", "repo_id": "tket", "token_count": 900 }
392
// 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 "../testutil.hpp" #include "tket/Utils/Expression.hpp" namespace tket { namespace test_Expression { SCENARIO("Basic Expr evaluation", "[ops]") { GIVEN("A constant") { Expr e(2.5); REQUIRE(test_equiv_val(e, 0.5)); } GIVEN("A symbol") { Sym s = SymEngine::symbol("a"); Expr e = Expr(s); REQUIRE(!eval_expr_mod(e)); SymEngine::map_basic_basic smap; smap[s] = Expr(3.4); Expr ee = e.subs(smap); REQUIRE(test_equiv_val(ee, 1.4)); } GIVEN("A non-empty sum") { Sym s = SymEngine::symbol("b"); Expr e = 0.2 + Expr(s) + 0.5 + Expr(s); REQUIRE(!eval_expr_mod(e)); SymEngine::map_basic_basic smap; smap[s] = Expr(0.3); Expr ee = e.subs(smap); REQUIRE(test_equiv_val(ee, 1.3)); } GIVEN("A non-empty product") { Sym s = SymEngine::symbol("b"); Expr e = 0.2 * Expr(s) * 0.5 * Expr(s); REQUIRE(!eval_expr_mod(e)); SymEngine::map_basic_basic smap; smap[s] = Expr(3.); Expr ee = e.subs(smap); REQUIRE(test_equiv_val(ee, 0.9)); } GIVEN("A more complicated expression") { Sym s = SymEngine::symbol("d"); Expr e = -0.3 + (3.4 * Expr(SymEngine::sin(Expr(s) - 2.3))); SymEngine::map_basic_basic smap; smap[s] = Expr(2.3); Expr ee = e.subs(smap); REQUIRE(test_equiv_val(ee, 1.7)); } } SCENARIO("Expression uniqueness", "[ops]") { GIVEN("Two equivalent constants") { Expr a(0.5); Expr b(2 * 3. / 4 - 1); b = SymEngine::evalf(b, 53); REQUIRE(a == b); } GIVEN("Two different constants") { Expr a(2.); Expr b0(2); Expr b1(3.); REQUIRE(a != b0); REQUIRE(a != b1); } GIVEN("Two identical symbols") { Expr a("alpha"); Expr b("alpha"); REQUIRE(a == b); } GIVEN("Two different symbols") { Expr a("alpha"); Expr b("beta"); REQUIRE(a != b); } GIVEN("Parsed atan2") { Expr a("alpha"); Expr b("beta"); Expr at(SymEngine::atan2(a, b)); Expr at2 = Expr("atan2(alpha, beta)"); REQUIRE(at == at2); } } } // namespace test_Expression } // namespace tket
tket/tket/test/src/Ops/test_Expression.cpp/0
{ "file_path": "tket/tket/test/src/Ops/test_Expression.cpp", "repo_id": "tket", "token_count": 1178 }
393
// 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 "tket/ZX/Rewrite.hpp" namespace tket { namespace zx { namespace test_ZXAxioms { SCENARIO("Simplify to a graph-like diagram") { GIVEN("A manually-constructed diagram") { /** * Diagram on https://arxiv.org/pdf/1902.03178.pdf, Figure 2 * We have added an extra input / output pair for testing purposes. */ ZXDiagram diag1(5, 5, 0, 0); ZXVertVec diag1_inputs = diag1.get_boundary(ZXType::Input); ZXVertVec diag1_outputs = diag1.get_boundary(ZXType::Output); ZXVert zSpid1 = diag1.add_vertex(ZXType::ZSpider); ZXVert zSpid2 = diag1.add_vertex(ZXType::ZSpider); ZXVert zSpid3 = diag1.add_vertex(ZXType::ZSpider); ZXVert phZSpid1 = diag1.add_vertex(ZXType::ZSpider, 0.5); ZXVert phZSpid2 = diag1.add_vertex(ZXType::ZSpider, 1.); ZXVert xSpid1 = diag1.add_vertex(ZXType::XSpider); ZXVert xSpid2 = diag1.add_vertex(ZXType::XSpider); ZXVert xSpid3 = diag1.add_vertex(ZXType::XSpider); diag1.add_wire(diag1_inputs[0], zSpid1); diag1.add_wire(zSpid1, phZSpid1); diag1.add_wire(phZSpid1, zSpid2); diag1.add_wire(zSpid2, diag1_outputs[0], ZXWireType::H); diag1.add_wire(zSpid1, xSpid1); diag1.add_wire(zSpid2, xSpid2); diag1.add_wire(diag1_inputs[1], xSpid1, ZXWireType::H); diag1.add_wire(xSpid1, zSpid3); diag1.add_wire(zSpid3, xSpid2); diag1.add_wire(xSpid2, phZSpid2); diag1.add_wire(phZSpid2, diag1_outputs[1]); diag1.add_wire(zSpid3, xSpid3); diag1.add_wire(diag1_inputs[2], xSpid3, ZXWireType::H); diag1.add_wire(xSpid3, diag1_outputs[2]); diag1.add_wire(diag1_inputs[3], diag1_outputs[3], ZXWireType::H); diag1.add_wire(diag1_inputs[4], diag1_outputs[4], ZXWireType::Basic); REQUIRE_NOTHROW(diag1.check_validity()); // Replace X with Z spiders CHECK(Rewrite::red_to_green().apply(diag1)); REQUIRE(diag1.count_vertices(ZXType::XSpider) == 0); REQUIRE(diag1.count_vertices(ZXType::ZSpider) == 8); // Spider fusion CHECK(Rewrite::spider_fusion().apply(diag1)); REQUIRE(diag1.count_vertices(ZXType::ZSpider) == 6); // Parallel edge pair removal CHECK_FALSE(Rewrite::parallel_h_removal().apply(diag1)); // Remove hadamard edges connected directly to the boundaries CHECK(Rewrite::io_extension().apply(diag1)); REQUIRE(diag1.count_vertices(ZXType::ZSpider) == 10); // Boundary vertices sharing spiders // Deal with directly connected in/outputs CHECK(Rewrite::separate_boundaries().apply(diag1)); REQUIRE(diag1.count_vertices(ZXType::ZSpider) == 13); REQUIRE_NOTHROW(diag1.check_validity()); } } SCENARIO("Testing Spider fusion") { GIVEN("A manually-constructed diagram") { ZXDiagram diag2(2, 1, 0, 0); ZXVertVec diag2_inputs = diag2.get_boundary(ZXType::Input); ZXVertVec diag2_outputs = diag2.get_boundary(ZXType::Output); ZXVert spid1 = diag2.add_vertex(ZXType::ZSpider, 0.1); ZXVert spid2 = diag2.add_vertex(ZXType::ZSpider, 0.3); ZXVert spid3 = diag2.add_vertex(ZXType::ZSpider); ZXVert spid4 = diag2.add_vertex(ZXType::ZSpider, 0.5); ZXVert spid5 = diag2.add_vertex(ZXType::ZSpider); diag2.add_wire( diag2_inputs[0], spid1, ZXWireType::Basic, QuantumType::Quantum); diag2.add_wire(diag2_inputs[1], spid5, ZXWireType::H, QuantumType::Quantum); diag2.add_wire(spid1, spid2, ZXWireType::H, QuantumType::Quantum); diag2.add_wire(spid2, spid3, ZXWireType::Basic, QuantumType::Quantum); diag2.add_wire(spid3, spid2, ZXWireType::H, QuantumType::Quantum); diag2.add_wire(spid3, spid4, ZXWireType::H, QuantumType::Quantum); diag2.add_wire(spid4, spid5, ZXWireType::Basic, QuantumType::Quantum); diag2.add_wire(spid5, spid1, ZXWireType::Basic, QuantumType::Quantum); diag2.add_wire( spid3, diag2_outputs[0], ZXWireType::Basic, QuantumType::Quantum); diag2.add_wire(spid3, spid3, ZXWireType::Basic, QuantumType::Quantum); diag2.add_wire(spid3, spid3, ZXWireType::H, QuantumType::Quantum); REQUIRE_NOTHROW(diag2.check_validity()); // Remove self-loops CHECK(Rewrite::self_loop_removal().apply(diag2)); // Spider fusion CHECK(Rewrite::spider_fusion().apply(diag2)); REQUIRE(diag2.count_vertices(ZXType::ZSpider) == 2); // Remove self-loops after fusion CHECK(Rewrite::self_loop_removal().apply(diag2)); // Parallel edge pair removal CHECK(Rewrite::parallel_h_removal().apply(diag2)); // Remove hadamard edges connected directly to the boundaries CHECK(Rewrite::io_extension().apply(diag2)); REQUIRE_NOTHROW(diag2.check_validity()); } GIVEN("A scalar diagram") { ZXDiagram diag3(0, 0, 0, 0); ZXVert v1 = diag3.add_vertex(ZXType::ZSpider); ZXVert v2 = diag3.add_vertex(ZXType::ZSpider); ZXVert v3 = diag3.add_vertex(ZXType::ZSpider, 3.22); ZXVert v4 = diag3.add_vertex(ZXType::ZSpider); ZXVert v5 = diag3.add_vertex(ZXType::ZSpider); ZXVert v6 = diag3.add_vertex(ZXType::ZSpider); diag3.add_wire(v1, v4, ZXWireType::H); diag3.add_wire(v4, v5, ZXWireType::Basic); diag3.add_wire(v5, v4, ZXWireType::H); diag3.add_wire(v5, v6, ZXWireType::Basic); diag3.add_wire(v6, v3, ZXWireType::H); diag3.add_wire(v3, v2, ZXWireType::Basic); diag3.add_wire(v2, v3, ZXWireType::H); diag3.add_wire(v2, v1, ZXWireType::Basic); REQUIRE_NOTHROW(diag3.check_validity()); // Self-loop finding CHECK_FALSE(Rewrite::self_loop_removal().apply(diag3)); // Spider fusion CHECK(Rewrite::spider_fusion().apply(diag3)); REQUIRE(diag3.count_vertices(ZXType::ZSpider) == 2); // Self loop removal after fusion CHECK(Rewrite::self_loop_removal().apply(diag3)); // Parallel edge pair removal CHECK(Rewrite::parallel_h_removal().apply(diag3)); // Remove hadamard edges connected directly to the boundaries CHECK_FALSE(Rewrite::io_extension().apply(diag3)); // Deal with directly connected in/outputs CHECK_FALSE(Rewrite::separate_boundaries().apply(diag3)); REQUIRE(diag3.count_vertices(ZXType::ZSpider) == 2); REQUIRE_NOTHROW(diag3.check_validity()); } } SCENARIO("ZXBox decomposition") { GIVEN("Nested ZXBoxes") { ZXDiagram innermost(1, 0, 0, 2); ZXVertVec innermost_ins = innermost.get_boundary(ZXType::Input); ZXVertVec innermost_outs = innermost.get_boundary(ZXType::Output); ZXVert innermost_spid = innermost.add_vertex(ZXType::XSpider, QuantumType::Classical); innermost.add_wire( innermost_ins[0], innermost_spid, ZXWireType::Basic, QuantumType::Quantum); innermost.add_wire( innermost_outs[0], innermost_spid, ZXWireType::Basic, QuantumType::Classical); innermost.add_wire( innermost_outs[1], innermost_spid, ZXWireType::Basic, QuantumType::Classical); ZXGen_ptr inner_box_gen = std::make_shared<const ZXBox>(innermost); ZXDiagram inner(0, 2, 0, 0); ZXVertVec inner_outs = inner.get_boundary(); ZXVert inner_box = inner.add_vertex(inner_box_gen); ZXVert inner_spid = inner.add_vertex(ZXType::ZSpider, QuantumType::Classical); inner.add_wire( inner_box, inner_outs[0], ZXWireType::H, QuantumType::Quantum, 0); inner.add_wire( inner_spid, inner_box, ZXWireType::Basic, QuantumType::Classical, std::nullopt, 1); inner.add_wire( inner_box, inner_spid, ZXWireType::Basic, QuantumType::Classical, 2); inner.add_wire(inner_spid, inner_outs[1]); ZXGen_ptr box_gen = std::make_shared<const ZXBox>(inner); ZXDiagram diag(1, 1, 0, 0); ZXVertVec b = diag.get_boundary(); ZXVert box = diag.add_vertex(box_gen); ZXVert spid = diag.add_vertex(ZXType::ZSpider, 1., QuantumType::Quantum); diag.add_wire(box, b[0], ZXWireType::Basic, QuantumType::Quantum, 0); diag.add_wire(box, spid, ZXWireType::Basic, QuantumType::Quantum, 1); diag.add_wire(spid, b[1]); REQUIRE_NOTHROW(diag.check_validity()); CHECK(Rewrite::decompose_boxes().apply(diag)); CHECK(diag.count_vertices(ZXType::ZXBox) == 0); CHECK(diag.count_vertices(ZXType::ZSpider) == 2); CHECK(diag.count_vertices(ZXType::XSpider) == 1); CHECK(Rewrite::parallel_h_removal().apply(diag)); CHECK(Rewrite::spider_fusion().apply(diag)); REQUIRE_NOTHROW(diag.check_validity()); } } SCENARIO("Mapping Hadamard edges to basic edges") { GIVEN("A diagram with a mixture of edge types") { ZXDiagram diag(1, 1, 1, 1); ZXVertVec ins = diag.get_boundary(ZXType::Input); ZXVertVec outs = diag.get_boundary(ZXType::Output); ZXVert z = diag.add_vertex(ZXType::ZSpider, QuantumType::Classical); ZXVert x = diag.add_vertex(ZXType::XSpider); diag.add_wire(ins[0], x, ZXWireType::H); diag.add_wire(ins[1], z, ZXWireType::H, QuantumType::Classical); diag.add_wire(outs[0], z, ZXWireType::Basic); diag.add_wire(outs[1], z, ZXWireType::Basic, QuantumType::Classical); REQUIRE_NOTHROW(diag.check_validity()); CHECK(Rewrite::basic_wires().apply(diag)); CHECK(diag.count_wires(ZXWireType::H) == 0); CHECK(diag.count_wires(ZXWireType::Basic) == 6); CHECK(diag.count_vertices(ZXType::Hbox) == 2); CHECK(diag.get_qtype(diag.neighbours(ins[0])[0]) == QuantumType::Quantum); CHECK(diag.get_qtype(diag.neighbours(ins[1])[0]) == QuantumType::Classical); CHECK_FALSE(Rewrite::basic_wires().apply(diag)); } } SCENARIO("Check rewrite combinators act the same as individual rewrites") { ZXDiagram diag(1, 1, 0, 0); ZXVertVec ins = diag.get_boundary(ZXType::Input); ZXVertVec outs = diag.get_boundary(ZXType::Output); ZXVert z = diag.add_vertex(ZXType::ZSpider); ZXVert x = diag.add_vertex(ZXType::XSpider); diag.add_wire(ins[0], z); diag.add_wire(z, z); diag.add_wire(z, x, ZXWireType::H); diag.add_wire(z, x, ZXWireType::Basic); diag.add_wire(x, x, ZXWireType::H); diag.add_wire(x, outs[0]); GIVEN("A diagram undergoing a sequence of rewrites") { ZXDiagram copy = diag; Rewrite seq = Rewrite::sequence( {Rewrite::self_loop_removal(), Rewrite::spider_fusion()}); CHECK(seq.apply(copy)); // Both should make changes CHECK(seq.apply(copy)); // More self loops created by fusion CHECK_FALSE(seq.apply(copy)); // No more changes } GIVEN("Iterated rewrites on a diagram") { ZXDiagram copy = diag; Rewrite seq = Rewrite::sequence( {Rewrite::self_loop_removal(), Rewrite::spider_fusion()}); Rewrite loop = Rewrite::repeat(seq); CHECK(loop.apply(copy)); // Should iterate until completion CHECK_FALSE(loop.apply(copy)); // Check for completion } GIVEN("Iterated (with metric) rewrites on a diagram") { ZXDiagram copy = diag; Rewrite seq = Rewrite::sequence( {Rewrite::self_loop_removal(), Rewrite::spider_fusion()}); Rewrite loop = Rewrite::repeat_with_metric(seq, &ZXDiagram::n_vertices); CHECK(loop.apply(copy)); // Should iterate until completion CHECK_FALSE(loop.apply(copy)); // Check for completion } GIVEN("Iterated (while) rewrites on a diagram") { ZXDiagram copy = diag; Rewrite loop = Rewrite::repeat_while( Rewrite::self_loop_removal(), Rewrite::spider_fusion()); CHECK(loop.apply(copy)); // Should iterate until completion CHECK_FALSE(loop.apply(copy)); // Check for completion } } } // namespace test_ZXAxioms } // namespace zx } // namespace tket
tket/tket/test/src/ZX/test_ZXAxioms.cpp/0
{ "file_path": "tket/tket/test/src/ZX/test_ZXAxioms.cpp", "repo_id": "tket", "token_count": 5210 }
394
// 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 <boost/dynamic_bitset.hpp> #include <catch2/catch_test_macros.hpp> #include <numeric> #include "Simulation/ComparisonFunctions.hpp" #include "testutil.hpp" #include "tket/Circuit/CircPool.hpp" #include "tket/Circuit/Simulation/CircuitSimulator.hpp" #include "tket/Gate/GateUnitaryMatrix.hpp" #include "tket/Gate/SymTable.hpp" #include "tket/Transformations/CliffordReductionPass.hpp" #include "tket/Transformations/Decomposition.hpp" #include "tket/Transformations/OptimisationPass.hpp" #include "tket/Transformations/Replacement.hpp" #include "tket/Transformations/Transform.hpp" namespace tket { namespace test_ControlDecomp { static bool approx_equal(const Complex& c1, const Complex& c2) { return (std::abs(c1 - c2) < ERR_EPS); } static bool check_incrementer_borrow_n_qubits(const unsigned n) { Circuit inc = CircPool::incrementer_borrow_n_qubits(n); bool correct = true; const StateVector sv = tket_sim::get_statevector(inc); for (unsigned i = 0; i < sv.size(); ++i) { // incremented the |0...00> state to be |0...10> incl. garbage qubits // (depending on def. of qubit significance) if (i == pow(2, 2 * n - 2)) correct &= (std::abs(sv[i]) > EPS); else correct &= (std::abs(sv[i]) < ERR_EPS); } Circuit xcirc = Circuit(2 * n); for (unsigned i = 1; i < 2 * n; i += 2) xcirc.add_op<unsigned>(OpType::X, {i}); xcirc.append(inc); const StateVector sv2 = tket_sim::get_statevector(xcirc); for (unsigned i = 0; i < sv2.size(); ++i) { if (i == 0) correct &= (std::abs(sv2[i]) > EPS); else correct &= (std::abs(sv2[i]) < ERR_EPS); } return correct; } static bool check_incrementer_borrow_1_qubit(const unsigned n) { Circuit inc = CircPool::incrementer_borrow_1_qubit(n); REQUIRE(inc.n_vertices() - inc.n_gates() == (n + 1) * 2); Transforms::synthesise_tket().apply(inc); const StateVector sv = tket_sim::get_statevector(inc); bool correct = true; for (unsigned i = 0; i < sv.size(); ++i) { // |00...0> -> |00...1> if (i == pow(2, n)) correct &= (std::abs(sv[i]) > EPS); else correct &= (std::abs(sv[i]) < ERR_EPS); } Circuit xcirc = Circuit(n + 1); for (unsigned i = 0; i < n; i++) xcirc.add_op<unsigned>(OpType::X, {i}); xcirc.append(inc); const StateVector sv2 = tket_sim::get_statevector(xcirc); for (unsigned i = 0; i < sv2.size(); ++i) { // |01...1> -> |00...0> if (i == 0) correct &= (std::abs(sv2[i]) > EPS); else correct &= (std::abs(sv2[i]) < ERR_EPS); } return correct; } static bool check_incrementer_linear_depth( const unsigned n, const unsigned number) { boost::dynamic_bitset<> in_bits(n, number); Circuit circ(n); for (unsigned i = 0; i < n; i++) { if (in_bits[i]) { circ.add_op<unsigned>(OpType::X, {i}); } } Circuit inc = CircPool::incrementer_linear_depth(n); circ.append(inc); unsigned long correct_out_long = in_bits.to_ulong() + 1UL; boost::dynamic_bitset<> correct_out_bits(n, correct_out_long); // Get the index of the entry that should have a "1" (with a phase difference) unsigned sv_set_idx = 0; for (unsigned i = 0; i < correct_out_bits.size(); i++) { if (correct_out_bits[i] == 1) { sv_set_idx = sv_set_idx + (1 << (n - i - 1)); } } const StateVector sv = tket_sim::get_statevector(circ); for (unsigned i = 0; i < sv.size(); ++i) { if (i == sv_set_idx) { if (std::abs(std::abs(sv[i]) - 1) >= ERR_EPS) return false; } else { if (std::abs(sv[i]) >= ERR_EPS) return false; } } return true; } // Explicitly construct CnU matrix static Eigen::MatrixXcd get_CnU_matrix( unsigned n_controls, const Eigen::Matrix2cd& U) { unsigned m_size = pow(2, n_controls + 1); Eigen::MatrixXcd correct_matrix = Eigen::MatrixXcd::Identity(m_size, m_size); correct_matrix(m_size - 2, m_size - 2) = U(0, 0); correct_matrix(m_size - 2, m_size - 1) = U(0, 1); correct_matrix(m_size - 1, m_size - 2) = U(1, 0); correct_matrix(m_size - 1, m_size - 1) = U(1, 1); return correct_matrix; } static Eigen::MatrixXcd get_CnX_matrix(unsigned n_controls) { Eigen::Matrix2cd x = GateUnitaryMatrix::get_unitary(OpType::X, 1, {}); return get_CnU_matrix(n_controls, x); } static Eigen::MatrixXcd get_CnY_matrix(unsigned n_controls) { Eigen::Matrix2cd y = GateUnitaryMatrix::get_unitary(OpType::Y, 1, {}); return get_CnU_matrix(n_controls, y); } static Eigen::MatrixXcd get_CnZ_matrix(unsigned n_controls) { Eigen::Matrix2cd z = GateUnitaryMatrix::get_unitary(OpType::Z, 1, {}); return get_CnU_matrix(n_controls, z); } SCENARIO("Test decomposition using CX") { OpType cntype; std::function<Eigen::MatrixXcd(unsigned)> matrix_func; WHEN("CnX") { cntype = OpType::CnX; matrix_func = get_CnX_matrix; } WHEN("CnY") { cntype = OpType::CnY; matrix_func = get_CnY_matrix; } WHEN("CnZ") { cntype = OpType::CnZ; matrix_func = get_CnZ_matrix; } std::vector<std::pair<unsigned, unsigned>> n_ctr_2q_count{ {3, 14}, {4, 36}, {6, 120}}; for (auto pair : n_ctr_2q_count) { const Op_ptr op = get_op_ptr(cntype, std::vector<Expr>(), pair.first + 1); Circuit decomposed_circ = CX_circ_from_multiq(op); auto u = tket_sim::get_unitary(decomposed_circ); REQUIRE((matrix_func(pair.first) - u).cwiseAbs().sum() < ERR_EPS); REQUIRE(decomposed_circ.count_gates(OpType::CX) == pair.second); } } SCENARIO("Test decomposition using TK2") { OpType cntype; std::function<Eigen::MatrixXcd(unsigned)> matrix_func; WHEN("CnX") { cntype = OpType::CnX; matrix_func = get_CnX_matrix; } WHEN("CnY") { cntype = OpType::CnY; matrix_func = get_CnY_matrix; } WHEN("CnZ") { cntype = OpType::CnZ; matrix_func = get_CnZ_matrix; } std::vector<std::pair<unsigned, unsigned>> n_ctr_2q_count{ {3, 14}, {4, 36}, {6, 61}}; for (auto pair : n_ctr_2q_count) { const Op_ptr op = get_op_ptr(cntype, std::vector<Expr>(), pair.first + 1); Circuit decomposed_circ = TK2_circ_from_multiq(op); auto u = tket_sim::get_unitary(decomposed_circ); REQUIRE((matrix_func(pair.first) - u).cwiseAbs().sum() < ERR_EPS); REQUIRE(decomposed_circ.count_gates(OpType::TK2) == pair.second); } } SCENARIO("Decompose some circuits with CCX gates") { GIVEN("Two CCX gates") { Circuit circ(3); circ.add_op<unsigned>(OpType::CCX, {0, 1, 2}); circ.add_op<unsigned>(OpType::CCX, {0, 1, 2}); Circuit circ2(3); const StateVector sv2 = tket_sim::get_statevector(circ2); Transforms::decomp_CCX().apply(circ); const StateVector sv1 = tket_sim::get_statevector(circ); REQUIRE(tket_sim::compare_statevectors_or_unitaries(sv1, sv2)); WHEN("Check gate numbering") { Circuit circ3(3); circ3.add_op<unsigned>(OpType::CCX, {0, 1, 2}); Transforms::decomp_CCX().apply(circ3); REQUIRE(circ3.n_gates() == 15); REQUIRE(circ3.n_vertices() == 21); REQUIRE(circ3.n_qubits() == 3); } } } SCENARIO("Test switch statement") { Circuit test(1); test.add_op<unsigned>(OpType::Ry, 1.95, {0}); GIVEN("A circuit and a CnRy(Pi/2)") { Circuit circ; const double p = 0.5; WHEN("Vertex with no edges") { Op_ptr cnry = get_op_ptr(OpType::CnRy, p); circ.add_vertex(cnry); REQUIRE_THROWS(Transforms::decomp_controlled_Rys().apply(circ)); } WHEN("Vertex with 1 edge") { circ.add_blank_wires(1); circ.add_op<unsigned>( OpType::CnRy, p, {0}); // automatically converted to Ry REQUIRE(!Transforms::decomp_controlled_Rys().apply(circ)); REQUIRE(circ.n_vertices() == 3); // 1 in, 1 out, 1 Ry REQUIRE(circ.n_gates() == 1); REQUIRE(circ.count_gates(OpType::Ry) == 1); VertexSet ry_set = circ.get_gates_of_type(OpType::Ry); Vertex ry = *ry_set.begin(); REQUIRE(test_equiv_val( (circ.get_Op_ptr_from_Vertex(ry))->get_params().at(0), p, 4)); REQUIRE(verify_n_qubits_for_ops(circ)); } WHEN("Vertex with 2 edges") { circ.add_blank_wires(2); circ.add_op<unsigned>(OpType::CnRy, p, {0, 1}); REQUIRE(Transforms::decomp_controlled_Rys().apply(circ)); REQUIRE(circ.n_vertices() == 8); REQUIRE(circ.n_gates() == 4); REQUIRE(circ.count_gates(OpType::CX) == 2); REQUIRE(circ.count_gates(OpType::Ry) == 2); VertexSet ry_set = circ.get_gates_of_type(OpType::Ry); for (const Vertex& v : ry_set) { Expr param = (circ.get_Op_ptr_from_Vertex(v))->get_params().at(0); REQUIRE( (test_equiv_val(param, p / 2) || test_equiv_val(param, -p / 2))); } REQUIRE(verify_n_qubits_for_ops(circ)); } WHEN("Vertex with 3 edges") { circ.add_blank_wires(3); circ.add_op<unsigned>(OpType::CnRy, p, {0, 1, 2}); REQUIRE(Transforms::decomp_controlled_Rys().apply(circ)); REQUIRE(circ.n_gates() == 14); REQUIRE(circ.count_gates(OpType::CX) == 8); REQUIRE(circ.count_gates(OpType::Ry) == 6); REQUIRE(verify_n_qubits_for_ops(circ)); } } } SCENARIO("Test switch statement long", "[.long]") { Circuit test(1); test.add_op<unsigned>(OpType::Ry, 1.95, {0}); const Eigen::Matrix2cd correct_block = tket_sim::get_unitary(test); GIVEN("A circuit and a CnRy(Pi/2)") { Circuit circ; WHEN("N-qubit CnRy gates") { THEN("Test with params nonzero") { for (unsigned N = 4; N < 10; ++N) { Circuit circ(N); std::vector<unsigned> qbs(N); std::iota(qbs.begin(), qbs.end(), 0); std::vector<Expr> params1{1.95}; circ.add_op<unsigned>(OpType::CnRy, params1, qbs); REQUIRE(Transforms::decomp_controlled_Rys().apply(circ)); const Eigen::MatrixXcd m = tket_sim::get_unitary(circ); const Eigen::Matrix2cd m_block = m.block(m.cols() - 2, m.rows() - 2, 2, 2); bool correctness = true; for (unsigned i = 0; i < 2; ++i) { for (unsigned j = 0; j < 2; ++j) { if (!approx_equal(m_block(i, j), correct_block(i, j))) { correctness = false; } } } REQUIRE(correctness); correctness = true; for (unsigned i = 0; i < m.rows() - 2; ++i) { for (unsigned j = 0; j < m.cols() - 2; ++j) { if (i == j) { if (!approx_equal(std::abs(m(i, j)), 1)) correctness = false; } else { if (!approx_equal(std::abs(m(i, j)), 0.)) correctness = false; } } } REQUIRE(correctness); REQUIRE(verify_n_qubits_for_ops(circ)); } } } } } SCENARIO("Test incrementer using n borrowed qubits") { GIVEN("0 qbs") { Circuit inc = CircPool::incrementer_borrow_n_qubits(0); REQUIRE(inc.n_vertices() == 0); } GIVEN("A 1qb incrementer") { Circuit inc = CircPool::incrementer_borrow_n_qubits(1); REQUIRE(inc.n_gates() == 1); REQUIRE(inc.count_gates(OpType::X) == 1); } GIVEN("A 2qb incrementer") { REQUIRE(check_incrementer_borrow_n_qubits(2)); } GIVEN("A 3qb incrementer") { REQUIRE(check_incrementer_borrow_n_qubits(3)); } GIVEN("A 4qb incrementer") { REQUIRE(check_incrementer_borrow_n_qubits(4)); } GIVEN("A 5qb incrementer") { REQUIRE(check_incrementer_borrow_n_qubits(5)); } GIVEN("A n-qb incrementer, 5<n<10") { // tket_sim doesn't support computing a unitary from a 12 qubits circuit // hence we only test that the incrementer can be constructed as intended. for (unsigned n = 6; n < 10; ++n) { Circuit inc = CircPool::incrementer_borrow_n_qubits(n); REQUIRE(inc.n_qubits() == 2 * n); REQUIRE(inc.count_gates(OpType::CCX) == (n - 1) * 4); REQUIRE(Transforms::synthesise_tket().apply(inc)); } } } SCENARIO("Test incrementer using 1 borrowed qubit") { GIVEN("Check the top incrementer is mapped correctly") { const unsigned k = 3; Circuit inc(2 * k); Circuit top_incrementer = CircPool::incrementer_borrow_n_qubits(k); std::vector<unsigned> top_qbs(2 * k); for (unsigned i = 0; i != k; ++i) { top_qbs[2 * i] = i + k; // garbage qubits top_qbs[2 * i + 1] = i; // qbs we are trying to increment inc.add_op<unsigned>(OpType::X, {i}); } inc.append_qubits(top_incrementer, top_qbs); Transforms::decomp_CCX().apply(inc); const StateVector sv = tket_sim::get_statevector(inc); bool correct = true; for (unsigned i = 0; i < sv.size(); ++i) { if (i == 0) correct &= (std::abs(sv[i]) > EPS); else correct &= (std::abs(sv[i]) < ERR_EPS); } REQUIRE(correct); } GIVEN( "Check that the controlled bot incrementer is mapped correctly for " "odd qb no") { const unsigned j = 3; Circuit inc(2 * j); Circuit bottom_incrementer = CircPool::incrementer_borrow_n_qubits(j); std::vector<unsigned> bot_qbs(2 * j); for (unsigned i = 0; i != j; ++i) { bot_qbs[2 * i] = i; // 0,2,4...n-1 //garbage qubits if (i != 0) bot_qbs[2 * i + 1] = i + j - 1; // 3,5...n //other qbs we are actually trying to increment } bot_qbs[1] = 2 * j - 1; // incremented qubit 0 in incrementer is bottom one inc.add_op<unsigned>(OpType::X, {2 * j - 1}); inc.append_qubits(bottom_incrementer, bot_qbs); Transforms::decomp_CCX().apply(inc); const StateVector sv = tket_sim::get_statevector(inc); bool correct = true; for (unsigned i = 0; i < sv.size(); ++i) { // |100000> -> |001000> if (i == 4) correct &= (std::abs(sv[i]) > EPS); else correct &= (std::abs(sv[i]) < ERR_EPS); } REQUIRE(correct); } GIVEN( "Check that the controlled bot incrementer is mapped correctly for " "even qb no") { const unsigned j = 4; const unsigned k = 3; const unsigned n = 6; Circuit inc(n + 1); for (unsigned i = k; i != n; ++i) { inc.add_op<unsigned>(OpType::X, {i}); } Circuit bottom_incrementer = CircPool::incrementer_borrow_n_qubits( j - 1); // insert incrementer over remaining qubits std::vector<unsigned> bot_qbs(2 * j - 2); for (unsigned i = 0; i != j - 1; ++i) { bot_qbs[2 * i] = i; // 0,2,4...n-1 //garbage qubits if (i != 0) bot_qbs[2 * i + 1] = i + k - 1; // 3,5...n //other qbs we are actually trying to increment } bot_qbs[1] = n; // incremented qubit 0 in incrementer is bottom one inc.append_qubits(bottom_incrementer, bot_qbs); Transforms::decomp_CCX().apply(inc); const StateVector sv = tket_sim::get_statevector(inc); bool correct = true; for (unsigned i = 0; i < sv.size(); ++i) { // |100000> -> |001000> if (i == 15) correct &= (std::abs(sv[i]) > EPS); else correct &= (std::abs(sv[i]) < ERR_EPS); } REQUIRE(correct); } GIVEN("A 0 qubit incrementer") { Circuit inc = CircPool::incrementer_borrow_1_qubit(0); REQUIRE(inc.n_qubits() == 1); REQUIRE(inc.n_vertices() == 2); REQUIRE(inc.n_gates() == 0); } GIVEN("A 1 qubit incrementer") { Circuit inc = CircPool::incrementer_borrow_1_qubit(1); REQUIRE(inc.n_qubits() == 2); REQUIRE(inc.n_vertices() == 5); REQUIRE(inc.n_gates() == 1); } GIVEN("A 2 qubit incrementer") { REQUIRE(check_incrementer_borrow_1_qubit(2)); } GIVEN("A 3 qubit incrementer") { REQUIRE(check_incrementer_borrow_1_qubit(3)); } GIVEN("A 4 qubit incrementer") { REQUIRE(check_incrementer_borrow_1_qubit(4)); } GIVEN("A 5 qubit incrementer") { REQUIRE(check_incrementer_borrow_1_qubit(5)); } GIVEN("A 6 qubit incrementer") { REQUIRE(check_incrementer_borrow_1_qubit(6)); } GIVEN("A 7 qubit incrementer") { REQUIRE(check_incrementer_borrow_1_qubit(7)); } GIVEN("A 8 qubit incrementer") { REQUIRE(check_incrementer_borrow_1_qubit(8)); } GIVEN("A 9 qubit incrementer") { REQUIRE(check_incrementer_borrow_1_qubit(9)); } GIVEN("A 10 qubit incrementer") { REQUIRE(check_incrementer_borrow_1_qubit(10)); } } SCENARIO("Test linear depth incrementer") { GIVEN("0 qb") { Circuit circ = CircPool::incrementer_linear_depth(0); REQUIRE(circ.n_qubits() == 0); } GIVEN("1 qb") { REQUIRE(check_incrementer_linear_depth(1, 0)); REQUIRE(check_incrementer_linear_depth(1, 1)); } GIVEN("2 qbs") { REQUIRE(check_incrementer_linear_depth(2, 0)); REQUIRE(check_incrementer_linear_depth(2, 1)); REQUIRE(check_incrementer_linear_depth(2, 2)); REQUIRE(check_incrementer_linear_depth(2, 3)); } GIVEN("3 qbs") { REQUIRE(check_incrementer_linear_depth(3, 0)); REQUIRE(check_incrementer_linear_depth(3, 1)); REQUIRE(check_incrementer_linear_depth(3, 5)); REQUIRE(check_incrementer_linear_depth(3, 7)); } GIVEN("4 qbs") { REQUIRE(check_incrementer_linear_depth(4, 0)); REQUIRE(check_incrementer_linear_depth(4, 1)); REQUIRE(check_incrementer_linear_depth(4, 10)); REQUIRE(check_incrementer_linear_depth(4, 15)); } GIVEN("5 qbs") { REQUIRE(check_incrementer_linear_depth(5, 0)); REQUIRE(check_incrementer_linear_depth(5, 1)); REQUIRE(check_incrementer_linear_depth(5, 26)); REQUIRE(check_incrementer_linear_depth(5, 31)); } GIVEN("8 qbs") { REQUIRE(check_incrementer_linear_depth(8, 0)); REQUIRE(check_incrementer_linear_depth(8, 1)); REQUIRE(check_incrementer_linear_depth(8, 100)); REQUIRE(check_incrementer_linear_depth(8, 255)); } } SCENARIO("Test a CnX is decomposed correctly when bootstrapped", "[.long]") { GIVEN("Test CnX unitary for 3 to 9 controls") { for (unsigned n = 3; n < 10; ++n) { Circuit circ = CircPool::CnX_normal_decomp(n); const Eigen::MatrixXcd m = tket_sim::get_unitary(circ); REQUIRE(m.isApprox(get_CnX_matrix(n), ERR_EPS)); } } } SCENARIO( "Test a CnX is decomposed correctly using the linear depth method", "[.long]") { GIVEN("Test CnX unitary for 0 to 9 controls") { for (unsigned n = 0; n < 10; ++n) { Eigen::MatrixXcd x = GateUnitaryMatrix::get_unitary(OpType::X, 1, {}); Circuit circ = CircPool::CnU_linear_depth_decomp(n, x); const Eigen::MatrixXcd m = tket_sim::get_unitary(circ); REQUIRE(m.isApprox(get_CnX_matrix(n), ERR_EPS)); } } } SCENARIO("Test a CnU is decomposed correctly using the linear depth method") { GIVEN("Test CnU unitary for n={0,1,2,3,5} controls") { for (unsigned i = 0; i < 100; i++) { Eigen::Matrix2cd U = random_unitary(2, i); std::vector<unsigned> test_ns = {0, 1, 2, 3, 5}; for (auto n : test_ns) { Circuit circ = CircPool::CnU_linear_depth_decomp(n, U); const Eigen::MatrixXcd m = tket_sim::get_unitary(circ); REQUIRE(m.isApprox(get_CnU_matrix(n, U), ERR_EPS)); } } } } SCENARIO( "Test a CnU is decomposed correctly using the gray code method", "[.long]") { GIVEN("Test CnU unitary for n={0,1,2,3,5} controls") { for (unsigned i = 0; i < 100; i++) { Eigen::Matrix2cd U = random_unitary(2, i); std::vector<unsigned> test_ns = {0, 1, 2, 3, 5}; for (auto n : test_ns) { Circuit circ = CircPool::CnU_gray_code_decomp(n, U); const Eigen::MatrixXcd m = tket_sim::get_unitary(circ); REQUIRE(m.isApprox(get_CnU_matrix(n, U), ERR_EPS)); } } } } static Eigen::MatrixXcd get_su2_matrix( const Expr& alpha, const Expr& theta, const Expr& beta) { Circuit c1 = Circuit(1); c1.add_op<unsigned>(OpType::Rz, beta, {0}); c1.add_op<unsigned>(OpType::Ry, theta, {0}); c1.add_op<unsigned>(OpType::Rz, alpha, {0}); return tket_sim::get_unitary(c1); } SCENARIO("Test CnSU2_linear_decomp") { GIVEN("Test identity") { std::vector<std::vector<Expr>> rotations = { {0, 0, 4}, {0, 0, 0}, {1, 4, 3}, {1, 0, 7}, {1, 6, 1}, {1.5, -6, 4.5}}; std::vector<unsigned> test_ns = {0, 1, 2, 3, 4, 5}; for (auto n : test_ns) { for (auto angles : rotations) { Circuit circ = CircPool::CnSU2_linear_decomp(n, angles[0], angles[1], angles[2]); const Eigen::MatrixXcd U = get_su2_matrix(angles[0], angles[1], angles[2]); REQUIRE(U.isApprox(Eigen::Matrix2cd::Identity(), ERR_EPS)); REQUIRE(circ.n_gates() == 0); } } } GIVEN("Test Y rotation") { std::vector<std::vector<Expr>> rotations = { {0, 0.377, 0}, {3, 4.2, -1}, {2, 1.1, 0}, {5, -0.5, -1}, {4, 1.2, 0}}; std::vector<unsigned> test_ns = {0, 1, 2, 3, 4, 5}; for (auto n : test_ns) { for (auto angles : rotations) { Circuit circ = CircPool::CnSU2_linear_decomp(n, angles[0], angles[1], angles[2]); const Eigen::MatrixXcd U = get_su2_matrix(angles[0], angles[1], angles[2]); const Eigen::MatrixXcd m = tket_sim::get_unitary(circ); REQUIRE(m.isApprox(get_CnU_matrix(n, U), ERR_EPS)); // check the method detects pure ry if (n == 1) { REQUIRE(circ.n_gates() == 4); REQUIRE(circ.count_gates(OpType::CX) == 2); REQUIRE(circ.count_gates(OpType::Ry) == 2); } else if (n == 2) { REQUIRE(circ.n_gates() == 4); REQUIRE(circ.count_gates(OpType::CX) == 2); REQUIRE(circ.count_gates(OpType::CRy) == 2); } } } } GIVEN("Test rotations where W=AXBX") { std::vector<std::vector<Expr>> rotations = { {3.7, 0.377, -0.3}, {3.4, 4.2, -2.6}}; std::vector<unsigned> test_ns = {0, 1, 2, 3, 4, 5}; for (auto n : test_ns) { for (auto angles : rotations) { Circuit circ = CircPool::CnSU2_linear_decomp(n, angles[0], angles[1], angles[2]); const Eigen::MatrixXcd U = get_su2_matrix(angles[0], angles[1], angles[2]); const Eigen::MatrixXcd m = tket_sim::get_unitary(circ); REQUIRE(m.isApprox(get_CnU_matrix(n, U), ERR_EPS)); if (n == 1) { REQUIRE(circ.n_gates() == 6); REQUIRE(circ.count_gates(OpType::CX) == 2); REQUIRE(circ.count_gates(OpType::Ry) == 2); REQUIRE(circ.count_gates(OpType::Rz) == 2); } else if (n == 2) { REQUIRE(circ.n_gates() == 6); REQUIRE(circ.count_gates(OpType::CX) == 2); REQUIRE(circ.count_gates(OpType::CRy) == 2); REQUIRE(circ.count_gates(OpType::CRz) == 2); } } } } GIVEN("Test symbolic rotations") { Sym a = SymTable::fresh_symbol("a"); Expr ea(a); Sym b = SymTable::fresh_symbol("b"); Expr eb(b); Sym c = SymTable::fresh_symbol("c"); Expr ec(c); std::map<Sym, double, SymEngine::RCPBasicKeyLess> symbol_map = { {a, 0.3112}, {b, 1.178}, {c, -0.911}}; std::vector<unsigned> test_ns = {0, 1, 2, 3, 5}; for (auto n : test_ns) { Circuit circ = CircPool::CnSU2_linear_decomp(n, ea, eb, ec); const Eigen::MatrixXcd U = get_su2_matrix(symbol_map[a], symbol_map[b], symbol_map[c]); circ.symbol_substitution(symbol_map); const Eigen::MatrixXcd m = tket_sim::get_unitary(circ); REQUIRE(m.isApprox(get_CnU_matrix(n, U), ERR_EPS)); } } GIVEN("Test arbitrary rotations") { std::vector<std::vector<Expr>> rotations = { {3.3, 0.377, -0.11}, {1.3, 0, 0.13}}; std::vector<unsigned> test_ns = {0, 1, 2, 3, 4, 5}; for (auto n : test_ns) { for (auto angles : rotations) { Circuit circ = CircPool::CnSU2_linear_decomp(n, angles[0], angles[1], angles[2]); const Eigen::MatrixXcd U = get_su2_matrix(angles[0], angles[1], angles[2]); const Eigen::MatrixXcd m = tket_sim::get_unitary(circ); REQUIRE(m.isApprox(get_CnU_matrix(n, U), ERR_EPS)); } } } } SCENARIO( "Test controlled rotation gates are decomposed correctly using the gray " "code method", "[.long]") { GIVEN("Test CnRy for n={0,1,2,3,5} controls") { const Eigen::Matrix2cd ry = Gate(OpType::Ry, {Expr(3.1)}, 1).get_unitary(); for (unsigned i = 0; i < 100; i++) { std::vector<unsigned> test_ns = {0, 1, 2, 3, 5}; for (auto n : test_ns) { Circuit circ = CircPool::CnU_gray_code_decomp( n, as_gate_ptr(get_op_ptr(OpType::Ry, 3.1))); const Eigen::MatrixXcd m = tket_sim::get_unitary(circ); REQUIRE(m.isApprox(get_CnU_matrix(n, ry), ERR_EPS)); } } } GIVEN("Test CnRx for n={0,1,2,3,5} controls") { const Eigen::Matrix2cd rx = Gate(OpType::Rx, {Expr(0.1)}, 1).get_unitary(); for (unsigned i = 0; i < 100; i++) { std::vector<unsigned> test_ns = {0, 1, 2, 3, 5}; for (auto n : test_ns) { Circuit circ = CircPool::CnU_gray_code_decomp( n, as_gate_ptr(get_op_ptr(OpType::Rx, 0.1))); const Eigen::MatrixXcd m = tket_sim::get_unitary(circ); REQUIRE(m.isApprox(get_CnU_matrix(n, rx), ERR_EPS)); } } } GIVEN("Test CnRz for n={0,1,2,3,5} controls") { const Eigen::Matrix2cd rz = Gate(OpType::Rz, {Expr(2.7)}, 1).get_unitary(); for (unsigned i = 0; i < 100; i++) { std::vector<unsigned> test_ns = {0, 1, 2, 3, 5}; for (auto n : test_ns) { Circuit circ = CircPool::CnU_gray_code_decomp( n, as_gate_ptr(get_op_ptr(OpType::Rz, 2.7))); const Eigen::MatrixXcd m = tket_sim::get_unitary(circ); REQUIRE(m.isApprox(get_CnU_matrix(n, rz), ERR_EPS)); } } } GIVEN("Test CnU1 for n={0,1,2,3,5} controls") { const Eigen::Matrix2cd u1 = Gate(OpType::U1, {Expr(1.5)}, 1).get_unitary(); for (unsigned i = 0; i < 100; i++) { std::vector<unsigned> test_ns = {0, 1, 2, 3, 5}; for (auto n : test_ns) { Circuit circ = CircPool::CnU_gray_code_decomp( n, as_gate_ptr(get_op_ptr(OpType::U1, 1.5))); const Eigen::MatrixXcd m = tket_sim::get_unitary(circ); REQUIRE(m.isApprox(get_CnU_matrix(n, u1), ERR_EPS)); } } } } SCENARIO("Test a CnX is decomposed correctly using the Gray code method") { GIVEN("Test CnX unitary for 0 to 8 controls") { Circuit circ_x = CircPool::CnX_gray_decomp(0); REQUIRE(circ_x.n_gates() == 1); REQUIRE(circ_x.count_gates(OpType::X) == 1); Circuit circ_cx = CircPool::CnX_gray_decomp(1); REQUIRE(circ_cx.n_gates() == 1); REQUIRE(circ_cx.count_gates(OpType::CX) == 1); for (unsigned n = 2; n < 8; ++n) { Circuit circ = CircPool::CnX_gray_decomp(n); const Eigen::MatrixXcd m = tket_sim::get_unitary(circ); REQUIRE(m.isApprox(get_CnX_matrix(n), ERR_EPS)); switch (n) { case 2: { REQUIRE(circ.count_gates(OpType::CX) <= 6); break; } case 3: { REQUIRE(circ.count_gates(OpType::CX) <= 14); break; } case 4: { REQUIRE(circ.count_gates(OpType::CX) <= 36); break; } case 5: { REQUIRE(circ.count_gates(OpType::CX) <= 92); break; } case 6: { REQUIRE(circ.count_gates(OpType::CX) <= 188); break; } case 7: { REQUIRE(circ.count_gates(OpType::CX) <= 380); break; } } } } } SCENARIO("Test decomp_arbitrary_controlled_gates") { GIVEN("Circuit with multi-controlled gates") { Circuit circ(3); circ.add_op<unsigned>(OpType::CnRy, 0.33, {0, 1, 2}); circ.add_op<unsigned>(OpType::CnRx, 0.33, {0, 1, 2}); circ.add_op<unsigned>(OpType::CnRz, 0.33, {0, 1, 2}); circ.add_op<unsigned>(OpType::CnY, {0, 1, 2}); circ.add_op<unsigned>(OpType::CnZ, {1, 0, 2}); circ.add_op<unsigned>(OpType::CnX, {0, 2, 1}); circ.add_op<unsigned>(OpType::CCX, {2, 1, 0}); auto u = tket_sim::get_unitary(circ); REQUIRE(Transforms::decomp_arbitrary_controlled_gates().apply(circ)); REQUIRE(circ.count_gates(OpType::CnRy) == 0); REQUIRE(circ.count_gates(OpType::CnRx) == 0); REQUIRE(circ.count_gates(OpType::CnRz) == 0); REQUIRE(circ.count_gates(OpType::CnY) == 0); REQUIRE(circ.count_gates(OpType::CnZ) == 0); REQUIRE(circ.count_gates(OpType::CnX) == 0); REQUIRE(circ.count_gates(OpType::CCX) == 0); auto v = tket_sim::get_unitary(circ); REQUIRE((u - v).cwiseAbs().sum() < ERR_EPS); } GIVEN("Circuit without multi-controlled gates") { Circuit circ(3); circ.add_op<unsigned>(OpType::CRy, 0.33, {0, 1}); circ.add_op<unsigned>(OpType::CRz, 0.5, {1, 2}); circ.add_op<unsigned>(OpType::CX, {1, 2}); circ.add_op<unsigned>(OpType::Rx, 0.7, {0}); REQUIRE(!Transforms::decomp_arbitrary_controlled_gates().apply(circ)); } } SCENARIO("Test cnx_pairwise_decomposition") { GIVEN("Circuit without CnX") { Circuit circ(3); circ.add_op<unsigned>(OpType::CX, {1, 2}); REQUIRE(!Transforms::cnx_pairwise_decomposition().apply(circ)); } GIVEN("Circuit with C0X and C1X") { Circuit circ(2); circ.add_op<unsigned>(OpType::CnX, {0}); circ.add_op<unsigned>(OpType::CnX, {0, 1}); auto u = tket_sim::get_unitary(circ); REQUIRE(Transforms::cnx_pairwise_decomposition().apply(circ)); auto v = tket_sim::get_unitary(circ); REQUIRE((u - v).cwiseAbs().sum() < ERR_EPS); REQUIRE(circ.count_gates(OpType::CnX) == 0); } GIVEN("test adding C1Z") { Circuit circ(2); circ.add_op<unsigned>(OpType::CnZ, {0}); circ.add_op<unsigned>(OpType::CnZ, {0, 1}); REQUIRE(circ.count_gates(OpType::CnZ) == 1); } GIVEN("test adding C1Y") { Circuit circ(2); circ.add_op<unsigned>(OpType::CnY, {0}); circ.add_op<unsigned>(OpType::CnY, {0, 1}); REQUIRE(circ.count_gates(OpType::CnY) == 1); } GIVEN("Circuit with a pair of CCX") { Circuit circ(3); circ.add_op<unsigned>(OpType::CCX, {0, 1, 2}); circ.add_op<unsigned>(OpType::CCX, {2, 0, 1}); auto u = tket_sim::get_unitary(circ); REQUIRE(Transforms::cnx_pairwise_decomposition().apply(circ)); REQUIRE(Transforms::clifford_simp().apply(circ)); auto v = tket_sim::get_unitary(circ); REQUIRE((u - v).cwiseAbs().sum() < ERR_EPS); // The CX count would normally be 12 REQUIRE(circ.count_gates(OpType::CX) < 12); } GIVEN("CnX without overlapping qubits") { Circuit circ(10); circ.add_op<unsigned>(OpType::CnX, {0, 1, 2, 3, 4}); circ.add_op<unsigned>(OpType::CnX, {5, 6, 7, 8, 9}); auto u = tket_sim::get_unitary(circ); REQUIRE(Transforms::cnx_pairwise_decomposition().apply(circ)); auto v = tket_sim::get_unitary(circ); REQUIRE((u - v).cwiseAbs().sum() < ERR_EPS); } GIVEN("Circuit with a odd number of CnX") { Circuit circ(6); circ.add_op<unsigned>(OpType::CnX, {0, 1, 2, 3, 4, 5}); circ.add_op<unsigned>(OpType::CnX, {1, 2, 3, 4, 5, 0}); circ.add_op<unsigned>(OpType::CnX, {3, 1, 4, 5, 0, 2}); auto u = tket_sim::get_unitary(circ); REQUIRE(Transforms::cnx_pairwise_decomposition().apply(circ)); REQUIRE(Transforms::decompose_multi_qubits_CX().apply(circ)); auto v = tket_sim::get_unitary(circ); REQUIRE((u - v).cwiseAbs().sum() < ERR_EPS); // The CX count would normally be 240 REQUIRE(circ.count_gates(OpType::CX) < 217); } GIVEN("Circuit with conditional CnX") { Circuit circ(6, 1); circ.add_conditional_gate<unsigned>(OpType::CnX, {}, {0, 1}, {0}, 1); circ.add_conditional_gate<unsigned>( OpType::CnX, {}, {0, 1, 2, 3, 4, 5}, {0}, 1); circ.add_conditional_gate<unsigned>( OpType::CnX, {}, {1, 2, 3, 4, 5, 0}, {0}, 1); circ.add_conditional_gate<unsigned>( OpType::CnX, {}, {3, 1, 4, 5, 0, 2}, {0}, 1); REQUIRE(Transforms::cnx_pairwise_decomposition().apply(circ)); } GIVEN("Circuit with a few more CnX") { Circuit circ(6); circ.add_op<unsigned>(OpType::CnX, {0, 1, 2, 3, 4, 5}); circ.add_op<unsigned>(OpType::CnX, {1, 2, 3, 4, 5, 0}); circ.add_op<unsigned>(OpType::CnX, {2, 3, 4, 5, 0, 1}); circ.add_op<unsigned>(OpType::CnX, {3, 4, 5, 0, 1, 2}); circ.add_op<unsigned>(OpType::CnX, {4, 5, 0, 1, 2, 3}); circ.add_op<unsigned>(OpType::CnX, {5, 0, 1, 2, 3, 4}); auto u = tket_sim::get_unitary(circ); REQUIRE(Transforms::cnx_pairwise_decomposition().apply(circ)); REQUIRE(Transforms::decompose_multi_qubits_CX().apply(circ)); auto v = tket_sim::get_unitary(circ); REQUIRE((u - v).cwiseAbs().sum() < ERR_EPS); // The CX count would normally be 480 REQUIRE(circ.count_gates(OpType::CX) < 409); } } } // namespace test_ControlDecomp } // namespace tket
tket/tket/test/src/test_ControlDecomp.cpp/0
{ "file_path": "tket/tket/test/src/test_ControlDecomp.cpp", "repo_id": "tket", "token_count": 15427 }
395
// 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 <tket/Transformations/Decomposition.hpp> #include "CircuitsForTesting.hpp" #include "testutil.hpp" #include "tket/Circuit/Boxes.hpp" #include "tket/Circuit/CircUtils.hpp" #include "tket/Circuit/PauliExpBoxes.hpp" #include "tket/Circuit/Simulation/CircuitSimulator.hpp" #include "tket/Converters/Converters.hpp" #include "tket/Diagonalisation/Diagonalisation.hpp" #include "tket/Gate/SymTable.hpp" #include "tket/PauliGraph/ConjugatePauliFunctions.hpp" #include "tket/PauliGraph/PauliGraph.hpp" #include "tket/Transformations/PauliOptimisation.hpp" #include "tket/Transformations/Rebase.hpp" namespace tket { namespace test_PauliGraph { SCENARIO("Correct creation of PauliGraphs") { GIVEN("A Clifford circuit") { Circuit circ(3); circ.add_op<unsigned>(OpType::CX, {0, 1}); circ.add_op<unsigned>(OpType::S, {1}); circ.add_op<unsigned>(OpType::CX, {0, 1}); circ.add_op<unsigned>(OpType::CX, {1, 2}); circ.add_op<unsigned>(OpType::Vdg, {1}); circ.add_op<unsigned>(OpType::CX, {1, 0}); circ.add_op<unsigned>(OpType::Phase, 0.8, {}); PauliGraph pg = circuit_to_pauli_graph(circ); UnitaryRevTableau correct_tab = circuit_to_unitary_rev_tableau(circ); REQUIRE(pg.get_clifford_ref() == correct_tab); } GIVEN("A 1qb circuit") { Circuit circ(1); circ.add_op<unsigned>(OpType::Rz, 0.3, {0}); circ.add_op<unsigned>(OpType::Rx, 0.6, {0}); circ.add_op<unsigned>(OpType::Ry, 1.2, {0}); circ.add_op<unsigned>(OpType::Rz, 0.3, {0}); PauliGraph pg = circuit_to_pauli_graph(circ); REQUIRE(pg.n_vertices() == 4); } GIVEN("A 2qb circuit with no interaction") { Circuit circ(2); circ.add_op<unsigned>(OpType::Rz, 0.3, {0}); circ.add_op<unsigned>(OpType::Rx, 0.6, {0}); circ.add_op<unsigned>(OpType::Ry, 1.2, {0}); circ.add_op<unsigned>(OpType::Rz, 0.3, {0}); circ.add_op<unsigned>(OpType::Ry, 0.2, {1}); circ.add_op<unsigned>(OpType::Rx, 1.6, {1}); circ.add_op<unsigned>(OpType::Rz, 1.3, {1}); PauliGraph pg = circuit_to_pauli_graph(circ); REQUIRE(pg.n_vertices() == 7); } GIVEN("A 2qb circuit with some anti-commuting interaction") { Circuit circ(2); circ.add_op<unsigned>(OpType::Rz, 0.3, {0}); circ.add_op<unsigned>(OpType::Ry, 0.2, {1}); circ.add_op<unsigned>(OpType::XXPhase, 1.1, {0, 1}); PauliGraph pg = circuit_to_pauli_graph(circ); REQUIRE(pg.n_vertices() == 3); } GIVEN("A 2qb circuit with some commuting interaction") { Circuit circ(2); circ.add_op<unsigned>(OpType::Rz, 0.3, {0}); circ.add_op<unsigned>(OpType::Rz, 0.2, {1}); circ.add_op<unsigned>(OpType::ZZPhase, 1.1, {0, 1}); PauliGraph pg = circuit_to_pauli_graph(circ); REQUIRE(pg.n_vertices() == 3); } GIVEN("A 2qb circuit a Clifford-angled ZZPhase") { Circuit circ(2); circ.add_op<unsigned>(OpType::Rz, 0.3, {0}); circ.add_op<unsigned>(OpType::Rz, 0.2, {1}); circ.add_op<unsigned>(OpType::ZZPhase, 0.5, {0, 1}); PauliGraph pg = circuit_to_pauli_graph(circ); REQUIRE(pg.n_vertices() == 2); } GIVEN("A 1qb circuit with stuff to merge") { Circuit circ(1); circ.add_op<unsigned>(OpType::Rz, 0.3, {0}); circ.add_op<unsigned>(OpType::Rz, 1.3, {0}); circ.add_op<unsigned>(OpType::Rx, 0.6, {0}); circ.add_op<unsigned>(OpType::Rz, 1.1, {0}); circ.add_op<unsigned>(OpType::Rz, 0.3, {0}); PauliGraph pg = circuit_to_pauli_graph(circ); REQUIRE(pg.n_vertices() == 3); } GIVEN("A 2qb circuit with stuff to merge") { Circuit circ(2); circ.add_op<unsigned>(OpType::Rz, 0.3, {0}); circ.add_op<unsigned>(OpType::Rz, 0.2, {1}); circ.add_op<unsigned>(OpType::ZZPhase, 1.1, {0, 1}); circ.add_op<unsigned>(OpType::Rz, 0.8, {0}); circ.add_op<unsigned>(OpType::ZZPhase, 1.6, {1, 0}); PauliGraph pg = circuit_to_pauli_graph(circ); REQUIRE(pg.n_vertices() == 3); } GIVEN("A circuit with Cliffords and non-Cliffords") { Circuit circ(2); circ.add_op<unsigned>(OpType::Rz, 0.3, {0}); circ.add_op<unsigned>(OpType::CX, {0, 1}); circ.add_op<unsigned>(OpType::Rz, 0.4, {0}); circ.add_op<unsigned>(OpType::H, {0}); circ.add_op<unsigned>(OpType::Rz, 1.1, {0}); circ.add_op<unsigned>(OpType::Rz, 1.8, {1}); PauliGraph pg = circuit_to_pauli_graph(circ); REQUIRE(pg.n_vertices() == 3); } GIVEN("A dense example") { Circuit circ(4); circ.add_op<unsigned>(OpType::Rz, 0.3, {0}); circ.add_op<unsigned>(OpType::Rz, 0.3, {1}); circ.add_op<unsigned>(OpType::Rz, 0.3, {2}); circ.add_op<unsigned>(OpType::Rz, 0.3, {3}); circ.add_op<unsigned>(OpType::Ry, 0.3, {0}); circ.add_op<unsigned>(OpType::Ry, 0.3, {1}); circ.add_op<unsigned>(OpType::Ry, 0.3, {2}); circ.add_op<unsigned>(OpType::Ry, 0.3, {3}); circ.add_op<unsigned>(OpType::CX, {0, 1}); circ.add_op<unsigned>(OpType::CX, {1, 2}); circ.add_op<unsigned>(OpType::CX, {2, 3}); circ.add_op<unsigned>(OpType::Rz, 0.3, {0}); circ.add_op<unsigned>(OpType::Rz, 0.3, {1}); circ.add_op<unsigned>(OpType::Rz, 0.3, {2}); circ.add_op<unsigned>(OpType::Rz, 0.3, {3}); circ.add_op<unsigned>(OpType::Ry, 0.3, {0}); circ.add_op<unsigned>(OpType::Ry, 0.3, {1}); circ.add_op<unsigned>(OpType::Ry, 0.3, {2}); circ.add_op<unsigned>(OpType::Ry, 0.3, {3}); PauliGraph pg = circuit_to_pauli_graph(circ); REQUIRE(pg.n_vertices() == 16); } GIVEN("A more interesting example (tof_3)") { Circuit circ(5); circ.add_op<unsigned>(OpType::H, {3}); circ.add_op<unsigned>(OpType::H, {4}); circ.add_op<unsigned>(OpType::CX, {1, 4}); circ.add_op<unsigned>(OpType::Tdg, {4}); circ.add_op<unsigned>(OpType::CX, {0, 4}); circ.add_op<unsigned>(OpType::T, {4}); circ.add_op<unsigned>(OpType::CX, {1, 4}); circ.add_op<unsigned>(OpType::Tdg, {4}); circ.add_op<unsigned>(OpType::CX, {0, 4}); circ.add_op<unsigned>(OpType::T, {4}); circ.add_op<unsigned>(OpType::T, {1}); circ.add_op<unsigned>(OpType::CX, {0, 1}); circ.add_op<unsigned>(OpType::T, {0}); circ.add_op<unsigned>(OpType::Tdg, {1}); circ.add_op<unsigned>(OpType::CX, {0, 1}); circ.add_op<unsigned>(OpType::H, {4}); circ.add_op<unsigned>(OpType::H, {4}); circ.add_op<unsigned>(OpType::H, {4}); circ.add_op<unsigned>(OpType::CX, {4, 3}); circ.add_op<unsigned>(OpType::Tdg, {3}); circ.add_op<unsigned>(OpType::CX, {2, 3}); circ.add_op<unsigned>(OpType::T, {3}); circ.add_op<unsigned>(OpType::CX, {4, 3}); circ.add_op<unsigned>(OpType::Tdg, {3}); circ.add_op<unsigned>(OpType::CX, {2, 3}); circ.add_op<unsigned>(OpType::T, {3}); circ.add_op<unsigned>(OpType::T, {4}); circ.add_op<unsigned>(OpType::CX, {2, 4}); circ.add_op<unsigned>(OpType::T, {2}); circ.add_op<unsigned>(OpType::Tdg, {4}); circ.add_op<unsigned>(OpType::CX, {2, 4}); circ.add_op<unsigned>(OpType::H, {3}); circ.add_op<unsigned>(OpType::H, {3}); circ.add_op<unsigned>(OpType::H, {3}); circ.add_op<unsigned>(OpType::H, {4}); circ.add_op<unsigned>(OpType::CX, {1, 4}); circ.add_op<unsigned>(OpType::Tdg, {4}); circ.add_op<unsigned>(OpType::CX, {0, 4}); circ.add_op<unsigned>(OpType::T, {4}); circ.add_op<unsigned>(OpType::CX, {1, 4}); circ.add_op<unsigned>(OpType::Tdg, {4}); circ.add_op<unsigned>(OpType::CX, {0, 4}); circ.add_op<unsigned>(OpType::T, {4}); circ.add_op<unsigned>(OpType::T, {1}); circ.add_op<unsigned>(OpType::CX, {0, 1}); circ.add_op<unsigned>(OpType::T, {0}); circ.add_op<unsigned>(OpType::Tdg, {1}); circ.add_op<unsigned>(OpType::CX, {0, 1}); circ.add_op<unsigned>(OpType::H, {4}); circ.add_op<unsigned>(OpType::H, {4}); circ.add_op<unsigned>(OpType::H, {4}); PauliGraph pg = circuit_to_pauli_graph(circ); REQUIRE(pg.n_vertices() == 15); } GIVEN("A circuit with a PauliExpBox") { Circuit circ(2); circ.add_op<unsigned>(OpType::ZZPhase, 0.2, {0, 1}); circ.add_op<unsigned>(OpType::Vdg, {0}); circ.add_op<unsigned>(OpType::H, {1}); PauliExpBox peb({{Pauli::Y, Pauli::X}, 0.333}); circ.add_box(peb, {0, 1}); PauliGraph pg = circuit_to_pauli_graph(circ); REQUIRE(pg.n_vertices() == 1); } } SCENARIO("TopSortIterator") { GIVEN("An empty circuit") { Circuit circ(2); REQUIRE_NOTHROW(circuit_to_pauli_graph(circ)); } } SCENARIO("Synthesising PauliGraphs") { GIVEN("A dense example") { Circuit circ(4); circ.add_op<unsigned>(OpType::Rz, 0.3, {0}); circ.add_op<unsigned>(OpType::Rz, 0.3, {1}); circ.add_op<unsigned>(OpType::Rz, 0.3, {2}); circ.add_op<unsigned>(OpType::Rz, 0.3, {3}); circ.add_op<unsigned>(OpType::Ry, 0.3, {0}); circ.add_op<unsigned>(OpType::Ry, 0.3, {1}); circ.add_op<unsigned>(OpType::Ry, 0.3, {2}); circ.add_op<unsigned>(OpType::Ry, 0.3, {3}); circ.add_op<unsigned>(OpType::CX, {0, 1}); circ.add_op<unsigned>(OpType::CX, {1, 2}); circ.add_op<unsigned>(OpType::CX, {2, 3}); circ.add_op<unsigned>(OpType::Rz, 0.3, {0}); circ.add_op<unsigned>(OpType::Rz, 0.3, {1}); circ.add_op<unsigned>(OpType::Rz, 0.3, {2}); circ.add_op<unsigned>(OpType::Rz, 0.3, {3}); circ.add_op<unsigned>(OpType::Ry, 0.3, {0}); circ.add_op<unsigned>(OpType::Ry, 0.3, {1}); circ.add_op<unsigned>(OpType::Ry, 0.3, {2}); circ.add_op<unsigned>(OpType::Ry, 0.3, {3}); const Eigen::MatrixXcd circ_unitary = tket_sim::get_unitary(circ); PauliGraph pg = circuit_to_pauli_graph(circ); pg.sanity_check(); WHEN("Synthesising individually") { Circuit synth = pauli_graph_to_pauli_exp_box_circuit_individually(pg); Transforms::decomp_boxes().apply(synth); pg.sanity_check(); Eigen::MatrixXcd synth_unitary = tket_sim::get_unitary(synth); REQUIRE((synth_unitary - circ_unitary).cwiseAbs().sum() < ERR_EPS); } WHEN("Synthesising pairwise") { Circuit synth = pauli_graph_to_pauli_exp_box_circuit_pairwise(pg); Transforms::decomp_boxes().apply(synth); Eigen::MatrixXcd synth_unitary = tket_sim::get_unitary(synth); REQUIRE((synth_unitary - circ_unitary).cwiseAbs().sum() < ERR_EPS); } } GIVEN("A UCCSD example") { const auto& circ = CircuitsForTesting::get().uccsd; const auto circ_unitary = tket_sim::get_unitary(circ); const PauliGraph pg = circuit_to_pauli_graph(circ); WHEN("Synthesising individually") { Circuit synth = pauli_graph_to_pauli_exp_box_circuit_individually(pg); Transforms::decomp_boxes().apply(synth); const auto synth_unitary = tket_sim::get_unitary(synth); REQUIRE((synth_unitary - circ_unitary).cwiseAbs().sum() < ERR_EPS); } WHEN("Synthesising pairwise") { Circuit synth = pauli_graph_to_pauli_exp_box_circuit_pairwise(pg); Transforms::decomp_boxes().apply(synth); const auto synth_unitary = tket_sim::get_unitary(synth); REQUIRE((synth_unitary - circ_unitary).cwiseAbs().sum() < ERR_EPS); } } } // Probably no special significance, just something repeated several times static void add_ops_to_prepend_1(Circuit& circ) { circ.add_op<unsigned>(OpType::Rx, 1.511, {2}); circ.add_op<unsigned>(OpType::Rz, 0.745, {2}); } static void add_ops_to_prepend_2(Circuit& circ) { circ.add_op<unsigned>(OpType::Rx, 0.849, {3}); circ.add_op<unsigned>(OpType::Rz, 0.102, {3}); } SCENARIO("Test mutual diagonalisation of fully commuting sets") { GIVEN("A 2 qb Identity gadget") { Circuit circ(2); PauliExpBox peb({{Pauli::I, Pauli::I}, 0.333}); circ.add_box(peb, {0, 1}); const auto& prepend = CircuitsForTesting::get().prepend_2qb_circuit; Circuit test1 = prepend >> circ; PauliGraph pg = circuit_to_pauli_graph(circ); pg.sanity_check(); Circuit out = pauli_graph_to_pauli_exp_box_circuit_sets(pg); Transforms::decomp_boxes().apply(out); pg.sanity_check(); Circuit test2 = prepend >> out; REQUIRE(test_statevector_comparison(test1, test2)); } GIVEN("2 qb 1 Pauli gadget circuit") { const auto& prepend = CircuitsForTesting::get().prepend_2qb_circuit; Circuit circ(2); PauliExpBox peb({{Pauli::Z, Pauli::X}, 0.333}); circ.add_box(peb, {0, 1}); Circuit test1 = prepend >> circ; PauliGraph pg = circuit_to_pauli_graph(circ); Circuit out = pauli_graph_to_pauli_exp_box_circuit_sets(pg); Transforms::decomp_boxes().apply(out); Circuit test2 = prepend >> out; REQUIRE(test_statevector_comparison(test1, test2)); } GIVEN("2 qb 2 Pauli gadget circuit") { const auto& prepend = CircuitsForTesting::get().prepend_2qb_circuit; Circuit circ(2); PauliExpBox peb({{Pauli::Z, Pauli::X}, 0.333}); circ.add_box(peb, {0, 1}); PauliExpBox peb2({{Pauli::Y, Pauli::Y}, 0.174}); circ.add_box(peb2, {0, 1}); Circuit test1 = prepend >> circ; PauliGraph pg = circuit_to_pauli_graph(circ); Circuit out = pauli_graph_to_pauli_exp_box_circuit_sets(pg); Transforms::decomp_boxes().apply(out); Circuit test2 = prepend >> out; REQUIRE(test_statevector_comparison(test1, test2)); } GIVEN("2 qb 3 Pauli gadget circuit with symbols") { const auto& prepend = CircuitsForTesting::get().prepend_2qb_circuit; Circuit circ(2); Sym a = SymTable::fresh_symbol("a"); Expr ea(a); Sym b = SymTable::fresh_symbol("b"); Expr eb(b); Sym c = SymTable::fresh_symbol("c"); Expr ec(c); std::map<Sym, double, SymEngine::RCPBasicKeyLess> symbol_map = { {a, 0.3112}, {b, 1.178}, {c, -0.911}}; PauliExpBox peb({{Pauli::Z, Pauli::Z}, ea}); circ.add_box(peb, {0, 1}); PauliExpBox peb2({{Pauli::X, Pauli::X}, eb}); circ.add_box(peb2, {0, 1}); PauliExpBox peb3({{Pauli::Y, Pauli::Y}, ec}); circ.add_box(peb3, {0, 1}); Circuit test1 = prepend >> circ; test1.symbol_substitution(symbol_map); PauliGraph pg = circuit_to_pauli_graph(circ); Circuit out = pauli_graph_to_pauli_exp_box_circuit_sets(pg); Transforms::decomp_boxes().apply(out); Circuit test2 = prepend >> out; test2.symbol_substitution(symbol_map); REQUIRE(test_statevector_comparison(test1, test2)); } GIVEN("2 qb 3 Pauli gadget circuit with symbols and Pauli::I present") { const auto& prepend = CircuitsForTesting::get().prepend_2qb_circuit; Circuit circ(2); Sym a = SymTable::fresh_symbol("a"); Expr ea(a); Sym b = SymTable::fresh_symbol("b"); Expr eb(b); Sym c = SymTable::fresh_symbol("c"); Expr ec(c); std::map<Sym, double, SymEngine::RCPBasicKeyLess> symbol_map = { {a, 0.3112}, {b, 1.178}, {c, -0.911}}; PauliExpBox peb({{Pauli::Z, Pauli::Z}, ea}); circ.add_box(peb, {0, 1}); PauliExpBox peb2({{Pauli::I, Pauli::X}, eb}); circ.add_box(peb2, {0, 1}); PauliExpBox peb3({{Pauli::Y, Pauli::I}, ec}); circ.add_box(peb3, {0, 1}); Circuit test1 = prepend >> circ; REQUIRE(test1.is_symbolic()); test1.symbol_substitution(symbol_map); REQUIRE(!test1.is_symbolic()); PauliGraph pg = circuit_to_pauli_graph(circ); Circuit out = pauli_graph_to_pauli_exp_box_circuit_sets(pg); Transforms::decomp_boxes().apply(out); Circuit test2 = prepend >> out; test2.symbol_substitution(symbol_map); REQUIRE(test_statevector_comparison(test1, test2)); } GIVEN("3 qb 2 Pauli Gadget circuit") { auto prepend = CircuitsForTesting::get_prepend_circuit(3); add_ops_to_prepend_1(prepend); Circuit circ(3); PauliExpBox peb({{Pauli::Z, Pauli::X, Pauli::Z}, 0.333}); circ.add_box(peb, {0, 1, 2}); PauliExpBox peb2({{Pauli::Y, Pauli::X, Pauli::X}, 0.174}); circ.add_box(peb2, {0, 1, 2}); Circuit test1 = prepend >> circ; PauliGraph pg = circuit_to_pauli_graph(circ); Circuit out = pauli_graph_to_pauli_exp_box_circuit_sets(pg); Transforms::decomp_boxes().apply(out); Circuit test2 = prepend >> out; REQUIRE(test_statevector_comparison(test1, test2)); } GIVEN("4 qb 3 Pauli Gadget circuit") { auto prepend = CircuitsForTesting::get_prepend_circuit(3); add_ops_to_prepend_1(prepend); Circuit circ(4); PauliExpBox peb({{Pauli::Z, Pauli::Z, Pauli::Z, Pauli::Z}, 0.333}); circ.add_box(peb, {0, 1, 2, 3}); PauliExpBox peb2({{Pauli::X, Pauli::Z, Pauli::X, Pauli::I}, 0.233}); circ.add_box(peb2, {0, 1, 2, 3}); PauliExpBox peb3({{Pauli::X, Pauli::X, Pauli::X, Pauli::X}, 0.174}); circ.add_box(peb3, {0, 1, 2, 3}); Circuit test1 = prepend >> circ; WHEN("Using default CX-decomposition") { PauliGraph pg = circuit_to_pauli_graph(circ); Circuit out = pauli_graph_to_pauli_exp_box_circuit_sets(pg); Transforms::decomp_boxes().apply(out); Circuit test2 = prepend >> out; REQUIRE(test_statevector_comparison(test1, test2)); } WHEN("Using XXPhase3-decomposition") { PauliGraph pg = circuit_to_pauli_graph(circ); Circuit out = pauli_graph_to_pauli_exp_box_circuit_sets( pg, CXConfigType::MultiQGate); Transforms::decomp_boxes().apply(out); REQUIRE(out.count_gates(OpType::XXPhase3) == 2); Circuit test2 = prepend >> out; REQUIRE(test_statevector_comparison(test1, test2)); } } GIVEN("3 qb 6 Pauli Gadget circuit for different strats and configs") { // add some arbitrary rotations to get away from |00> state Circuit circ(3, 3); CircuitsForTesting::add_initial_prepend_ops(circ); add_ops_to_prepend_1(circ); PauliExpBox peb({{Pauli::Z, Pauli::Y, Pauli::X}, 0.333}); circ.add_box(peb, {0, 1, 2}); PauliExpBox peb2({{Pauli::Y, Pauli::Z, Pauli::X}, 0.174}); circ.add_box(peb2, {0, 1, 2}); PauliExpBox peb3({{Pauli::Y, Pauli::Z, Pauli::I}, 0.567}); circ.add_box(peb3, {0, 1, 2}); PauliExpBox peb4({{Pauli::Z, Pauli::Y, Pauli::I}, 1.849}); circ.add_box(peb4, {0, 1, 2}); PauliExpBox peb5({{Pauli::X, Pauli::X, Pauli::X}, 1.67}); circ.add_box(peb5, {0, 1, 2}); PauliExpBox peb6({{Pauli::X, Pauli::X, Pauli::I}, 0.83}); circ.add_box(peb6, {0, 1, 2}); Circuit test1 = circ; WHEN("Different strategies and configs") { Transforms::synthesise_pauli_graph( Transforms::PauliSynthStrat::Sets, CXConfigType::Star) .apply(circ); Transforms::decomp_boxes().apply(circ); REQUIRE(test_statevector_comparison(test1, circ)); } WHEN("Different strategies and configs") { Transforms::synthesise_pauli_graph( Transforms::PauliSynthStrat::Individual, CXConfigType::Star) .apply(circ); Transforms::decomp_boxes().apply(circ); REQUIRE(test_statevector_comparison(test1, circ)); } WHEN("Different strategies and configs") { Transforms::synthesise_pauli_graph( Transforms::PauliSynthStrat::Pairwise, CXConfigType::Star) .apply(circ); Transforms::decomp_boxes().apply(circ); REQUIRE(test_statevector_comparison(test1, circ)); } WHEN("Different strategies and configs") { Transforms::synthesise_pauli_graph( Transforms::PauliSynthStrat::Sets, CXConfigType::Snake) .apply(circ); Transforms::decomp_boxes().apply(circ); REQUIRE(test_statevector_comparison(test1, circ)); } WHEN("Different strategies and configs") { Transforms::synthesise_pauli_graph( Transforms::PauliSynthStrat::Individual, CXConfigType::Snake) .apply(circ); Transforms::decomp_boxes().apply(circ); REQUIRE(test_statevector_comparison(test1, circ)); } WHEN("Different strategies and configs") { Transforms::synthesise_pauli_graph( Transforms::PauliSynthStrat::Pairwise, CXConfigType::Snake) .apply(circ); Transforms::decomp_boxes().apply(circ); REQUIRE(test_statevector_comparison(test1, circ)); } WHEN("Different strategies and configs") { Transforms::synthesise_pauli_graph( Transforms::PauliSynthStrat::Sets, CXConfigType::Tree) .apply(circ); Transforms::decomp_boxes().apply(circ); REQUIRE(test_statevector_comparison(test1, circ)); } WHEN("Different strategies and configs") { Transforms::synthesise_pauli_graph( Transforms::PauliSynthStrat::Individual, CXConfigType::Tree) .apply(circ); Transforms::decomp_boxes().apply(circ); REQUIRE(test_statevector_comparison(test1, circ)); } WHEN("Different strategies and configs") { Transforms::synthesise_pauli_graph( Transforms::PauliSynthStrat::Pairwise, CXConfigType::Tree) .apply(circ); Transforms::decomp_boxes().apply(circ); REQUIRE(test_statevector_comparison(test1, circ)); } WHEN("Pairwise strategy with CXConfigType::MultiQGate") { Transforms::synthesise_pauli_graph( Transforms::PauliSynthStrat::Pairwise, CXConfigType::MultiQGate) .apply(circ); Transforms::decomp_boxes().apply(circ); REQUIRE(test_statevector_comparison(test1, circ)); } WHEN("Sets strategy with CXConfigType::MultiQGate") { Transforms::synthesise_pauli_graph( Transforms::PauliSynthStrat::Sets, CXConfigType::MultiQGate) .apply(circ); Transforms::decomp_boxes().apply(circ); REQUIRE(test_statevector_comparison(test1, circ)); } WHEN("Individual strategy with CXConfigType::MultiQGate") { Transforms::synthesise_pauli_graph( Transforms::PauliSynthStrat::Individual, CXConfigType::MultiQGate) .apply(circ); Transforms::decomp_boxes().apply(circ); REQUIRE(circ.count_gates(OpType::XXPhase3) == 6); REQUIRE(test_statevector_comparison(test1, circ)); } } GIVEN( "4 qb 8 Pauli Gadget circuit (ie. double excitations for UCCSD " "circuits)") { // add some arbitrary rotations to get away from |00> state auto prepend = CircuitsForTesting::get_prepend_circuit(4); add_ops_to_prepend_1(prepend); add_ops_to_prepend_2(prepend); Circuit circ(4); Sym a = SymTable::fresh_symbol("a"); Expr ea(a); Sym b = SymTable::fresh_symbol("b"); Expr eb(b); Sym c = SymTable::fresh_symbol("c"); Expr ec(c); Sym d = SymTable::fresh_symbol("d"); Expr ed(d); Sym e = SymTable::fresh_symbol("e"); Expr ee(e); Sym f = SymTable::fresh_symbol("f"); Expr ef(f); Sym g = SymTable::fresh_symbol("g"); Expr eg(g); Sym h = SymTable::fresh_symbol("h"); Expr eh(h); std::map<Sym, double, SymEngine::RCPBasicKeyLess> symbol_map = { {a, 0.3112}, {b, 1.178}, {c, -0.911}, {d, 0.7122}, {e, 1.102}, {f, 0.151}, {g, 1.223}, {h, 1.666}}; PauliExpBox peb0({{Pauli::X, Pauli::X, Pauli::X, Pauli::Y}, ea}); circ.add_box(peb0, {0, 1, 2, 3}); PauliExpBox peb1({{Pauli::X, Pauli::X, Pauli::Y, Pauli::X}, eb}); circ.add_box(peb1, {0, 1, 2, 3}); PauliExpBox peb2({{Pauli::X, Pauli::Y, Pauli::X, Pauli::X}, ec}); circ.add_box(peb2, {0, 1, 2, 3}); PauliExpBox peb3({{Pauli::X, Pauli::Y, Pauli::Y, Pauli::Y}, ed}); circ.add_box(peb3, {0, 1, 2, 3}); PauliExpBox peb4({{Pauli::Y, Pauli::X, Pauli::X, Pauli::X}, ee}); circ.add_box(peb4, {0, 1, 2, 3}); PauliExpBox peb5({{Pauli::Y, Pauli::X, Pauli::Y, Pauli::Y}, ef}); circ.add_box(peb5, {0, 1, 2, 3}); PauliExpBox peb6({{Pauli::Y, Pauli::Y, Pauli::X, Pauli::Y}, eg}); circ.add_box(peb6, {0, 1, 2, 3}); PauliExpBox peb7({{Pauli::Y, Pauli::Y, Pauli::Y, Pauli::X}, eh}); circ.add_box(peb7, {0, 1, 2, 3}); Circuit test1 = prepend >> circ; CircBox circbox(circ); Circuit major_circ(4); major_circ.add_box(circbox, {0, 1, 2, 3}); Transforms::special_UCC_synthesis().apply(major_circ); Circuit test2 = prepend >> major_circ; test1.symbol_substitution(symbol_map); test2.symbol_substitution(symbol_map); REQUIRE(test_statevector_comparison(test1, test2)); } GIVEN( "4 qb 4 Pauli Gadget circuit (some single excitations for UCCSD " "circuits)") { auto prepend = CircuitsForTesting::get_prepend_circuit(4); add_ops_to_prepend_1(prepend); add_ops_to_prepend_2(prepend); Circuit circ(4); Sym a = SymTable::fresh_symbol("a"); Expr ea(a); Sym b = SymTable::fresh_symbol("b"); Expr eb(b); Sym c = SymTable::fresh_symbol("c"); Expr ec(c); Sym d = SymTable::fresh_symbol("d"); Expr ed(d); std::map<Sym, double, SymEngine::RCPBasicKeyLess> symbol_map = { {a, 0.3112}, {b, 1.178}, {c, -0.911}, {d, 0.7122}}; PauliExpBox peb0({{Pauli::Y, Pauli::Z, Pauli::X, Pauli::I}, ea}); circ.add_box(peb0, {0, 1, 2, 3}); PauliExpBox peb1({{Pauli::X, Pauli::Z, Pauli::Y, Pauli::I}, eb}); circ.add_box(peb1, {0, 1, 2, 3}); PauliExpBox peb2({{Pauli::I, Pauli::Y, Pauli::Z, Pauli::X}, ec}); circ.add_box(peb2, {0, 1, 2, 3}); PauliExpBox peb3({{Pauli::I, Pauli::X, Pauli::Y, Pauli::Z}, ed}); circ.add_box(peb3, {0, 1, 2, 3}); Circuit test1 = prepend >> circ; CircBox circbox(circ); Circuit major_circ(4); major_circ.add_box(circbox, {0, 1, 2, 3}); Transforms::special_UCC_synthesis().apply(major_circ); Circuit test2 = prepend >> major_circ; test1.symbol_substitution(symbol_map); test2.symbol_substitution(symbol_map); REQUIRE(test_statevector_comparison(test1, test2)); } GIVEN( "5 qubit 7 Pauli Gadget circuit; example from compilation strategy " "paper") { // This circuit requires greedy diagonalisation auto prepend = CircuitsForTesting::get_prepend_circuit(5); add_ops_to_prepend_1(prepend); add_ops_to_prepend_2(prepend); prepend.add_op<unsigned>(OpType::Rx, 0.466, {4}); prepend.add_op<unsigned>(OpType::Rz, 1.303, {4}); Circuit circ(5); Sym a = SymTable::fresh_symbol("a"); Expr ea(a); Sym b = SymTable::fresh_symbol("b"); Expr eb(b); Sym c = SymTable::fresh_symbol("c"); Expr ec(c); Sym d = SymTable::fresh_symbol("d"); Expr ed(d); Sym e = SymTable::fresh_symbol("e"); Expr ee(e); Sym f = SymTable::fresh_symbol("f"); Expr ef(f); Sym g = SymTable::fresh_symbol("g"); Expr eg(g); std::map<Sym, double, SymEngine::RCPBasicKeyLess> symbol_map = { {a, 0.3112}, {b, 1.178}, {c, -0.911}, {d, 0.7122}, {e, 1.102}, {f, 0.151}, {g, 1.223}}; PauliExpBox peb0({{Pauli::I, Pauli::X, Pauli::Z, Pauli::I, Pauli::Z}, ea}); circ.add_box(peb0, {0, 1, 2, 3, 4}); PauliExpBox peb1({{Pauli::I, Pauli::Y, Pauli::I, Pauli::Z, Pauli::Y}, eb}); circ.add_box(peb1, {0, 1, 2, 3, 4}); PauliExpBox peb2({{Pauli::X, Pauli::X, Pauli::I, Pauli::Y, Pauli::I}, ec}); circ.add_box(peb2, {0, 1, 2, 3, 4}); PauliExpBox peb3({{Pauli::Y, Pauli::Y, Pauli::X, Pauli::I, Pauli::I}, ed}); circ.add_box(peb3, {0, 1, 2, 3, 4}); PauliExpBox peb4({{Pauli::Z, Pauli::I, Pauli::Y, Pauli::X, Pauli::X}, ee}); circ.add_box(peb4, {0, 1, 2, 3, 4}); PauliExpBox peb5({{Pauli::Z, Pauli::X, Pauli::I, Pauli::Z, Pauli::Z}, ef}); circ.add_box(peb5, {0, 1, 2, 3, 4}); PauliExpBox peb6({{Pauli::Z, Pauli::Y, Pauli::Z, Pauli::I, Pauli::Y}, eg}); circ.add_box(peb6, {0, 1, 2, 3, 4}); Circuit test1 = prepend >> circ; CircBox circbox(circ); Circuit major_circ(5); major_circ.add_box(circbox, {0, 1, 2, 3, 4}); Transforms::special_UCC_synthesis().apply(major_circ); Circuit test2 = prepend >> major_circ; REQUIRE(test2.count_gates(OpType::CX) == 24); test1.symbol_substitution(symbol_map); test2.symbol_substitution(symbol_map); REQUIRE(test_statevector_comparison(test1, test2)); } GIVEN( "Clifford merges requires removing from start line without segfault " "(Grover circuit)") { Circuit oracle(5); oracle.add_op<unsigned>(OpType::CCX, {0, 1, 4}); oracle.add_op<unsigned>(OpType::H, {4}); oracle.add_op<unsigned>(OpType::CCX, {2, 3, 4}); oracle.add_op<unsigned>(OpType::H, {4}); oracle.add_op<unsigned>(OpType::CCX, {0, 1, 4}); Circuit reflect(2); add_1qb_gates(reflect, OpType::H, {0, 1}); add_1qb_gates(reflect, OpType::X, {0, 1}); reflect.add_op<unsigned>(OpType::CZ, {0, 1}); add_1qb_gates(reflect, OpType::X, {0, 1}); add_1qb_gates(reflect, OpType::H, {0, 1}); Circuit circ(5, 4); add_1qb_gates(circ, OpType::H, {0, 1, 2, 3}); circ.append(oracle); circ.append_qubits(reflect, {2, 3}); circ.append(oracle); circ.append_qubits(reflect, {0, 1}); circ.append(oracle); circ.append_qubits(reflect, {2, 3}); add_2qb_gates(circ, OpType::Measure, {{0, 0}, {1, 1}, {2, 2}, {3, 3}}); Transforms::rebase_pyzx().apply(circ); bool success = Transforms::synthesise_pauli_graph().apply(circ); REQUIRE(success); } } SCENARIO("Conjugating Cliffords through Pauli tensors") { GIVEN("A 3qb XYZ pauli tensor") { SpPauliStabiliser qpt(DensePauliMap{Pauli::X, Pauli::Y, Pauli::Z}); WHEN("Commuting a Hadamard through qb0") { Qubit qb0(0); conjugate_PauliTensor(qpt, OpType::H, qb0); THEN("X becomes Z") { REQUIRE(qpt.get(qb0) == Pauli::Z); REQUIRE(qpt.is_real_negative() == false); } } WHEN("Commuting a X through qb0") { Qubit qb0(0); conjugate_PauliTensor(qpt, OpType::X, qb0); THEN("X remains X") { REQUIRE(qpt.get(qb0) == Pauli::X); REQUIRE(qpt.is_real_negative() == false); } } WHEN("Commuting a X through qb1") { Qubit qb1(1); conjugate_PauliTensor(qpt, OpType::X, qb1); THEN("Y becomes -Y") { REQUIRE(qpt.get(qb1) == Pauli::Y); REQUIRE(qpt.is_real_negative() == true); } } WHEN("Commuting a CX through qb0-qb1") { Qubit qb0(0), qb1(1); conjugate_PauliTensor(qpt, OpType::CX, qb0, qb1); THEN("XY becomes YZ") { REQUIRE(qpt.get(qb0) == Pauli::Y); REQUIRE(qpt.get(qb1) == Pauli::Z); REQUIRE(qpt.is_real_negative() == false); } } WHEN("Commuting an XXPhase3 through qb0-qb1-qb2") { Qubit qb0(0), qb1(1), qb2(2); conjugate_PauliTensor(qpt, OpType::XXPhase3, qb0, qb1, qb2); THEN("XYZ becomes -XZY") { REQUIRE(qpt.get(qb0) == Pauli::X); REQUIRE(qpt.get(qb1) == Pauli::Z); REQUIRE(qpt.get(qb2) == Pauli::Y); REQUIRE(qpt.is_real_negative() == true); } } } GIVEN("A 3qb XXX pauli tensor") { SpPauliStabiliser qpt(DensePauliMap{Pauli::X, Pauli::X, Pauli::X}); WHEN("Commuting an XXPhase3 through qb0-qb1-qb2") { Qubit qb0(0), qb1(1), qb2(2); THEN("XXX remains XXX") { REQUIRE(qpt.get(qb0) == Pauli::X); REQUIRE(qpt.get(qb1) == Pauli::X); REQUIRE(qpt.get(qb2) == Pauli::X); REQUIRE(qpt.is_real_negative() == false); } } } } SCENARIO("Test greedy diagonalisation explicitly") { auto is_diagonal = [](const SpSymPauliTensor& qpt) { for (auto [qb, p] : qpt.string) { if (p != Pauli::I && p != Pauli::Z) { return false; } } return true; }; auto apply_strategy = [](std::list<SpSymPauliTensor>& gadgets, std::set<Qubit>& qubits, Circuit& cliff_circ, const CXConfigType config) { while (!qubits.empty()) { Conjugations conjugations; greedy_diagonalise(gadgets, qubits, conjugations, cliff_circ, config); for (auto& g : gadgets) { apply_conjugations(g, conjugations); } check_easy_diagonalise(gadgets, qubits, cliff_circ); } }; GIVEN("A large-ish set of PauliTensor") { unsigned n_qbs = 6; std::set<Qubit> qbs; for (unsigned i = 0; i < n_qbs; ++i) qbs.insert(Qubit(i)); std::list<SpSymPauliTensor> gadgets; Conjugations conjugations; Circuit cliff_circ(n_qbs); // commuting set gadgets.push_back(SpSymPauliTensor( {Pauli::Z, Pauli::Z, Pauli::Z, Pauli::X, Pauli::X, Pauli::X}, 1.13)); gadgets.push_back(SpSymPauliTensor( {Pauli::Z, Pauli::X, Pauli::Y, Pauli::Z, Pauli::Z, Pauli::X}, 0.226)); gadgets.push_back(SpSymPauliTensor( {Pauli::Z, Pauli::Y, Pauli::X, Pauli::Z, Pauli::Z, Pauli::X}, 0.013)); gadgets.push_back(SpSymPauliTensor( {Pauli::Z, Pauli::Y, Pauli::X, Pauli::Y, Pauli::Y, Pauli::X}, 0.952)); gadgets.push_back(SpSymPauliTensor( {Pauli::X, Pauli::Z, Pauli::Z, Pauli::Y, Pauli::Y, Pauli::Y}, 1.88)); WHEN("a single run with Snake configuration") { CXConfigType cx_config = CXConfigType::Snake; greedy_diagonalise(gadgets, qbs, conjugations, cliff_circ, cx_config); THEN("5x CX are used") { REQUIRE(cliff_circ.depth_by_type(OpType::CX) == 5); REQUIRE(cliff_circ.count_gates(OpType::CX) == 5); } } WHEN("repeated runs with Snake configuration") { CXConfigType cx_config = CXConfigType::Snake; apply_strategy(gadgets, qbs, cliff_circ, cx_config); THEN("gadgets are diagonal") { for (const auto& g : gadgets) { REQUIRE(is_diagonal(g)); } } } WHEN("a single run with Star configuration") { CXConfigType cx_config = CXConfigType::Star; greedy_diagonalise(gadgets, qbs, conjugations, cliff_circ, cx_config); THEN("5x CX are used") { REQUIRE(cliff_circ.depth_by_type(OpType::CX) == 5); REQUIRE(cliff_circ.count_gates(OpType::CX) == 5); } } WHEN("repeated runs with Star configuration") { CXConfigType cx_config = CXConfigType::Star; apply_strategy(gadgets, qbs, cliff_circ, cx_config); THEN("gadgets are diagonal") { for (const auto& g : gadgets) { REQUIRE(is_diagonal(g)); } } } WHEN("a single run with Tree configuration") { CXConfigType cx_config = CXConfigType::Tree; greedy_diagonalise(gadgets, qbs, conjugations, cliff_circ, cx_config); THEN("5x CX are used, depth 3") { REQUIRE(cliff_circ.depth_by_type(OpType::CX) == 3); REQUIRE(cliff_circ.count_gates(OpType::CX) == 5); } } WHEN("repeated runs with Tree configuration") { CXConfigType cx_config = CXConfigType::Tree; apply_strategy(gadgets, qbs, cliff_circ, cx_config); THEN("gadgets are diagonal") { for (const auto& g : gadgets) { REQUIRE(is_diagonal(g)); } } } WHEN("a single run with MultiQGate configuration") { CXConfigType cx_config = CXConfigType::MultiQGate; greedy_diagonalise(gadgets, qbs, conjugations, cliff_circ, cx_config); THEN("2x XXPhase3 are used") { REQUIRE(cliff_circ.depth_by_type(OpType::XXPhase3) == 2); REQUIRE(cliff_circ.depth_by_type(OpType::CX) == 1); } } WHEN("repeated runs with MultiQGate configuration") { CXConfigType cx_config = CXConfigType::MultiQGate; apply_strategy(gadgets, qbs, cliff_circ, cx_config); THEN("gadgets are diagonal") { for (const auto& g : gadgets) { REQUIRE(is_diagonal(g)); } } } } } SCENARIO("Diagonalise a pair of gadgets") { unsigned n_qbs = 6; std::set<Qubit> qbs; for (unsigned i = 0; i < n_qbs; ++i) qbs.insert(Qubit(i)); Conjugations conjugations; Circuit circ(n_qbs); // commuting set std::vector<SpSymPauliTensor> gadgets; gadgets.push_back(SpSymPauliTensor( {Pauli::Z, Pauli::Z, Pauli::X, Pauli::I, Pauli::I, Pauli::X}, 1.13)); gadgets.push_back(SpSymPauliTensor( {Pauli::Z, Pauli::Z, Pauli::X, Pauli::Z, Pauli::Z, Pauli::I}, 0.226)); Circuit correct; for (unsigned i = 0; i < 2; ++i) { correct.append(pauli_gadget(gadgets.at(i))); } auto u_correct = tket_sim::get_unitary(correct); GIVEN("Snake configuration") { CXConfigType config = CXConfigType::Snake; circ.append(pauli_gadget_pair(gadgets.at(0), gadgets.at(1), config)); THEN("Unitary is correct") { auto u_res = tket_sim::get_unitary(circ); REQUIRE((u_correct - u_res).cwiseAbs().sum() < ERR_EPS); } } GIVEN("Star configuration") { CXConfigType config = CXConfigType::Star; circ.append(pauli_gadget_pair(gadgets.at(0), gadgets.at(1), config)); THEN("Unitary is correct") { auto u_res = tket_sim::get_unitary(circ); REQUIRE((u_correct - u_res).cwiseAbs().sum() < ERR_EPS); } } GIVEN("Tree configuration") { CXConfigType config = CXConfigType::Tree; circ.append(pauli_gadget_pair(gadgets.at(0), gadgets.at(1), config)); THEN("Unitary is correct") { auto u_res = tket_sim::get_unitary(circ); REQUIRE((u_correct - u_res).cwiseAbs().sum() < ERR_EPS); } } GIVEN("MultiQGate configuration") { CXConfigType config = CXConfigType::MultiQGate; circ.append(pauli_gadget_pair(gadgets.at(0), gadgets.at(1), config)); circ.decompose_boxes_recursively(); THEN("XXPhase3 were used") { REQUIRE(circ.count_gates(OpType::XXPhase3) == 2); } THEN("Unitary is correct") { auto u_res = tket_sim::get_unitary(circ); REQUIRE((u_correct - u_res).cwiseAbs().sum() < ERR_EPS); } } } SCENARIO("Measure handling in PauliGraph") { GIVEN("A circuit with end-of-circuit measurements") { Circuit circ(2, 2); circ.add_op<unsigned>(OpType::S, {0}); circ.add_op<unsigned>(OpType::V, {1}); circ.add_op<unsigned>(OpType::Rz, 0.2, {0}); circ.add_op<unsigned>(OpType::Rz, 0.3, {1}); circ.add_op<unsigned>(OpType::Measure, {0, 1}); circ.add_op<unsigned>(OpType::Measure, {1, 0}); PauliGraph pg = circuit_to_pauli_graph(circ); pg.sanity_check(); std::map<Qubit, unsigned> correct_readout = {{Qubit(0), 1}, {Qubit(1), 0}}; WHEN("Synthesise individually") { Circuit circ2 = pauli_graph_to_pauli_exp_box_circuit_individually(pg); Transforms::decomp_boxes().apply(circ2); REQUIRE(circ2.qubit_readout() == correct_readout); } WHEN("Synthesise pairwise") { Circuit circ2 = pauli_graph_to_pauli_exp_box_circuit_pairwise(pg); Transforms::decomp_boxes().apply(circ2); pg.sanity_check(); REQUIRE(circ2.qubit_readout() == correct_readout); } WHEN("Synthesise in sets") { Circuit circ2 = pauli_graph_to_pauli_exp_box_circuit_sets(pg); Transforms::decomp_boxes().apply(circ2); REQUIRE(circ2.qubit_readout() == correct_readout); } } GIVEN("A circuit with mid-circuit measurements") { Circuit circ(2, 2); circ.add_op<unsigned>(OpType::S, {0}); circ.add_op<unsigned>(OpType::V, {1}); circ.add_op<unsigned>(OpType::Measure, {0, 1}); circ.add_op<unsigned>(OpType::Rz, 0.2, {0}); circ.add_op<unsigned>(OpType::Rz, 0.3, {1}); circ.add_op<unsigned>(OpType::Measure, {1, 0}); REQUIRE_THROWS_AS( circuit_to_pauli_graph(circ), MidCircuitMeasurementNotAllowed); } } } // namespace test_PauliGraph } // namespace tket
tket/tket/test/src/test_PauliGraph.cpp/0
{ "file_path": "tket/tket/test/src/test_PauliGraph.cpp", "repo_id": "tket", "token_count": 18037 }
396