├── .gitignore ├── .travis.yml ├── LICENSE ├── README.rst ├── chp_sim ├── __init__.py ├── chp_simulator.py ├── chp_simulator_test.py └── version.py ├── requirements-dev.txt ├── requirements.txt └── setup.py /.gitignore: -------------------------------------------------------------------------------- 1 | .idea/* 2 | .venv/* 3 | **/__pycache__/** 4 | dist/** 5 | *.egg-info/** 6 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: python 2 | python: "3.6" 3 | branches: 4 | only: master 5 | install: pip install -r requirements.txt -r requirements-dev.txt 6 | script: pytest 7 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | Python CHP Stabilizer Simulator 2 | ------------------------------- 3 | 4 | A simple reference python implementation of Scott Aaronson and Daniel Gottesman's CHP simulator 5 | as defined in 6 | `their 2004 paper "Improved Simulation of Stabilizer Circuits" `__. 7 | This simulator is capable of simulating quantum stabilizer circuits in polynomial time and space. 8 | Specifically, it uses ``O(q^2*m + q*c)`` time and ``O(q^2)`` space where 9 | ``q`` is the number of qubits, 10 | ``m`` is the number of measurements, 11 | and ``c`` is the number of Hadamard/CNOT/Phase gates. 12 | 13 | Installation 14 | ------------ 15 | 16 | The ``chp_sim`` package is available on pypi and can be installed using ``pip``: 17 | 18 | .. code-block:: bash 19 | 20 | python -m pip install chp_sim 21 | 22 | Alternatively, you can just copy paste the ``chp_sim`` directory of the github 23 | repository into your project. 24 | The only runtime dependency is ``numpy``. 25 | 26 | Usage 27 | ----- 28 | 29 | Here is an example of simulating 30 | `a circuit `__: 31 | 32 | .. code-block:: python 33 | 34 | import chp_sim 35 | sim = chp_sim.ChpSimulator(num_qubits=3) 36 | 37 | # Desired circuit: 38 | # 0: -------X-------S---H---M--- 39 | # | 40 | # 1: -------|---X---S---H---M--- 41 | # | | 42 | # 2: ---H---@---@-------H---M--- 43 | 44 | sim.hadamard(2) 45 | sim.cnot(2, 0) 46 | sim.cnot(2, 1) 47 | sim.phase(0) 48 | sim.phase(1) 49 | sim.hadamard(0) 50 | sim.hadamard(1) 51 | sim.hadamard(2) 52 | 53 | # Show internal simulator state. 54 | print(sim, '\n') 55 | # prints: 56 | # -Y.. 57 | # -.Y. 58 | # +..X 59 | # ---- 60 | # +X.X 61 | # +.XX 62 | # +YYZ 63 | 64 | # Perform measurements 65 | v0 = sim.measure(0) 66 | v1 = sim.measure(1) 67 | v2 = sim.measure(2) 68 | print(v0) 69 | print(v1) 70 | print(v2) 71 | # prints [note: one of four possible results for this circuit]: 72 | # True (random) 73 | # False (random) 74 | # False (determined) 75 | 76 | # Check pattern the outputs should satisfy. 77 | assert not v0.determined 78 | assert not v1.determined 79 | assert v2.determined 80 | assert bool(v0) ^ bool(v1) ^ bool(v2) 81 | 82 | 83 | Packaging 84 | --------- 85 | 86 | (Notes to self on how to release a new version.) 87 | 88 | 1. Edit the source code as needed and run tests. 89 | 90 | .. code-block:: bash 91 | 92 | pytest 93 | 94 | 2. Build the wheel. 95 | 96 | .. code-block:: bash 97 | 98 | python3 setup.py -q bdist_wheel 99 | ls dist 100 | 101 | 3. Upload to test pypi. 102 | 103 | .. code-block:: bash 104 | 105 | twine upload dist/*.whl --repository-url=https://test.pypi.org/legacy/ --username="${TEST_TWINE_USERNAME}" --password="${TEST_TWINE_PASSWORD}" 106 | 107 | 4. Verify the test package works. 108 | 109 | .. code-block:: bash 110 | 111 | mkvirtualenv test --python=/usr/bin/python3 112 | pip install numpy 113 | pip install chp_sim --index-url=https://test.pypi.org/simple/ 114 | python -c "import chp_sim; print(chp_sim.__version__); print(chp_sim.ChpSimulator(4))" 115 | 116 | 5. Upload to prod pypi. 117 | 118 | .. code-block:: bash 119 | 120 | twine upload dist/*.whl --username="${PROD_TWINE_USERNAME}" --password="${PROD_TWINE_PASSWORD}" 121 | 122 | 6. Verify the prod package works. 123 | 124 | .. code-block:: bash 125 | 126 | mkvirtualenv test --python=/usr/bin/python3 127 | pip install chp_sim 128 | python -c "import chp_sim; print(chp_sim.__version__); print(chp_sim.ChpSimulator(4))" 129 | -------------------------------------------------------------------------------- /chp_sim/__init__.py: -------------------------------------------------------------------------------- 1 | from chp_sim.version import ( 2 | __version__ 3 | ) 4 | 5 | from chp_sim.chp_simulator import ( 6 | ChpSimulator, 7 | MeasureResult, 8 | ) 9 | -------------------------------------------------------------------------------- /chp_sim/chp_simulator.py: -------------------------------------------------------------------------------- 1 | import random 2 | from typing import Union, Any 3 | 4 | import numpy as np 5 | 6 | 7 | class ChpSimulator: 8 | """The bare minimum needed for the CHP simulation. 9 | 10 | Reference: 11 | "Improved Simulation of Stabilizer Circuits" 12 | Scott Aaronson and Daniel Gottesman 13 | https://arxiv.org/abs/quant-ph/0406196 14 | """ 15 | 16 | def __init__(self, num_qubits): 17 | self._n = num_qubits 18 | self._table = np.eye(2 * num_qubits + 1, dtype=np.bool) 19 | self._x = self._table[:, :self._n] 20 | self._z = self._table[:, self._n:-1] 21 | self._r = self._table[:, -1] 22 | 23 | def cnot(self, control: int, target: int) -> None: 24 | """Applies a CNOT gate between two qubits. 25 | 26 | Args: 27 | control: The control qubit of the CNOT. 28 | target: The target qubit of the CNOT. 29 | """ 30 | self._r[:] ^= self._x[:, control] & self._z[:, target] & ( 31 | self._x[:, target] ^ self._z[:, control] ^ True) 32 | self._x[:, target] ^= self._x[:, control] 33 | self._z[:, control] ^= self._z[:, target] 34 | 35 | def hadamard(self, qubit: int) -> None: 36 | """Applies a Hadamard gate to a qubit. 37 | 38 | Args: 39 | qubit: The qubit to apply the H gate to. 40 | """ 41 | self._r[:] ^= self._x[:, qubit] & self._z[:, qubit] 42 | # Perform a XOR-swap 43 | self._x[:, qubit] ^= self._z[:, qubit] 44 | self._z[:, qubit] ^= self._x[:, qubit] 45 | self._x[:, qubit] ^= self._z[:, qubit] 46 | 47 | def phase(self, qubit: int) -> None: 48 | """Applies an S gate to a qubit. 49 | 50 | Args: 51 | qubit: The qubit to apply the S gate to. 52 | """ 53 | self._r[:] ^= self._x[:, qubit] & self._z[:, qubit] 54 | self._z[:, qubit] ^= self._x[:, qubit] 55 | 56 | def measure(self, 57 | qubit: int, 58 | *, 59 | bias: Union[float, int, bool] = 0.5) -> 'MeasureResult': 60 | """Computational basis (Z basis) measurement. 61 | 62 | Args: 63 | qubit: The index of the qubit to measure. 64 | bias: When the measurement result is random, this is the probability 65 | of getting a True result value instead of False. Mostly useful 66 | for making reproducible unit tests. 67 | 68 | Returns: 69 | A MeasurementResult instance whose `value` attribute is the outcome 70 | of the measurement and whose `determined` attribute indicates 71 | whether the outcome was deterministic or random. 72 | """ 73 | n = self._n 74 | for p in range(n): 75 | if self._x[p+n, qubit]: 76 | return self._measure_random(qubit, p, bias) 77 | return self._measure_determined(qubit) 78 | 79 | def _measure_random(self, 80 | a: int, 81 | p: int, 82 | bias: Union[float, int, bool]) -> 'MeasureResult': 83 | n = self._n 84 | assert self._x[p+n, a] 85 | self._table[p, :] = self._table[p + n, :] 86 | self._table[p + n, :] = 0 87 | self._z[p + n, a] = 1 88 | self._r[p + n] = random.random() < bias 89 | 90 | for i in range(2*n): 91 | if self._x[i, a] and i != p and i != p + n: 92 | self._row_mult(i, p) 93 | return MeasureResult(value=self._r[p + n], determined=False) 94 | 95 | def _measure_determined(self, a: int) -> 'MeasureResult': 96 | n = self._n 97 | self._table[-1, :] = 0 98 | for i in range(n): 99 | if self._x[i, a]: 100 | self._row_mult(-1, i + n) 101 | return MeasureResult(value=self._r[-1], determined=True) 102 | 103 | def _row_product_sign(self, i: int, k: int) -> bool: 104 | """Determines the sign of two rows' Pauli Products.""" 105 | pauli_phases = sum( 106 | pauli_product_phase(self._x[i, j], 107 | self._z[i, j], 108 | self._x[k, j], 109 | self._z[k, j]) 110 | for j in range(self._n) 111 | ) 112 | assert not pauli_phases & 1, ( 113 | "Expected commuting rows but got {}, {} from \n{}".format( 114 | i, k, self)) 115 | p = (pauli_phases >> 1) & 1 116 | return bool(self._r[i] ^ self._r[k] ^ p) 117 | 118 | def _row_mult(self, i: int, k: int) -> None: 119 | """Multiplies row k's Paulis into row i's Paulis.""" 120 | self._r[i] = self._row_product_sign(i, k) 121 | self._x[i, :self._n] ^= self._x[k, :self._n] 122 | self._z[i, :self._n] ^= self._z[k, :self._n] 123 | 124 | def __str__(self): 125 | """Represents the state as a list of Pauli products. 126 | 127 | Each Pauli product is what the X or Z observable of a qubit at the 128 | current time was equal to at time zero (after accounting for 129 | measurements). 130 | """ 131 | 132 | def _cell(row: int, col: int) -> str: 133 | k = int(self._x[row, col]) + 2 * int(self._z[row, col]) 134 | return ['.', 'X', 'Z', 'Y'][k] 135 | 136 | def _row(row: int) -> str: 137 | result = '-' if self._r[row] else '+' 138 | for col in range(self._n): 139 | result += str(_cell(row, col)) 140 | return result 141 | 142 | z_obs = [_row(row) for row in range(self._n)] 143 | sep = ['-' * (self._n + 1)] 144 | x_obs = [_row(row) for row in range(self._n, 2 * self._n)] 145 | return '\n'.join(z_obs + sep + x_obs) 146 | 147 | def _repr_pretty_(self, p: Any, cycle: bool) -> None: 148 | p.text(str(self)) 149 | 150 | 151 | def pauli_product_phase(x1: bool, z1: bool, x2: bool, z2: bool) -> int: 152 | """Determines the power of i in the product of two Paulis. 153 | 154 | For example, X*Y = iZ and so this method would return +1 for X and Y. 155 | 156 | The input Paulis are encoded into the following form: 157 | 158 | x z | Pauli 159 | ----+------- 160 | 0 0 | I 161 | 1 0 | X 162 | 1 1 | Y 163 | 0 1 | Z 164 | """ 165 | # Analyze by case over first gate. 166 | 167 | if x1 and z1: # Y gate. 168 | # No phase for YI = Y 169 | # -1 phase for YX = -iZ 170 | # No phase for YY = I 171 | # +1 phase for YZ = +iX 172 | return int(z2) - int(x2) 173 | 174 | if x1: # X gate. 175 | # No phase for XI = X 176 | # No phase for XX = I 177 | # +1 phase for XY = iZ 178 | # -1 phase for XZ = -iY 179 | return z2 and 2*int(x2) - 1 180 | 181 | if z1: # Z gate. 182 | # No phase for ZI = Z 183 | # +1 phase for ZX = -iY 184 | # -1 phase for ZY = iX 185 | # No phase for ZZ = I 186 | return x2 and 1 - 2*int(z2) 187 | 188 | # Identity gate. 189 | return 0 190 | 191 | 192 | class MeasureResult: 193 | """A measurement's output and whether it was random or not.""" 194 | 195 | def __init__(self, value: bool, determined: bool): 196 | self.value = bool(value) 197 | self.determined = bool(determined) 198 | 199 | def __bool__(self): 200 | return self.value 201 | 202 | def __eq__(self, other): 203 | if isinstance(other, (bool, int)): 204 | return self.value == other 205 | if isinstance(other, MeasureResult): 206 | return self.value == other.value and self.determined == other.determined 207 | return NotImplemented 208 | 209 | def __str__(self): 210 | return '{} ({})'.format(self.value, 211 | ['random', 'determined'][self.determined]) 212 | 213 | def __repr__(self): 214 | return 'MeasureResult(value={!r}, determined={!r})'.format( 215 | self.value, 216 | self.determined) 217 | -------------------------------------------------------------------------------- /chp_sim/chp_simulator_test.py: -------------------------------------------------------------------------------- 1 | import collections 2 | 3 | from typing import Set 4 | import itertools 5 | 6 | from chp_sim.chp_simulator import ( 7 | pauli_product_phase, ChpSimulator, MeasureResult, 8 | ) 9 | 10 | 11 | def test_pauli_product_phase(): 12 | paulis = [ 13 | [False, False], # I 14 | [True, False], # X 15 | [True, True], # Y 16 | [False, True], # Z 17 | ] 18 | expected = [ 19 | [0, 0, 0, 0], 20 | [0, 0, 1, -1], 21 | [0, -1, 0, 1], 22 | [0, 1, -1, 0], 23 | ] 24 | assert pauli_product_phase(x1=True, z1=False, x2=True, z2=True) == 1; 25 | for i in range(4): 26 | for j in range(4): 27 | assert pauli_product_phase(*paulis[i], *paulis[j]) == expected[i][j] 28 | 29 | 30 | def test_identity(): 31 | s = ChpSimulator(num_qubits=1) 32 | assert s.measure(0) == MeasureResult(value=False, determined=True) 33 | 34 | 35 | def test_bit_flip(): 36 | s = ChpSimulator(num_qubits=1) 37 | s.hadamard(0) 38 | s.phase(0) 39 | s.phase(0) 40 | s.hadamard(0) 41 | assert s.measure(0) == MeasureResult(value=True, determined=True) 42 | 43 | 44 | def test_identity_2(): 45 | s = ChpSimulator(num_qubits=2) 46 | assert s.measure(0) == MeasureResult(value=False, determined=True) 47 | assert s.measure(1) == MeasureResult(value=False, determined=True) 48 | 49 | 50 | def test_bit_flip_2(): 51 | s = ChpSimulator(num_qubits=2) 52 | s.hadamard(0) 53 | s.phase(0) 54 | s.phase(0) 55 | s.hadamard(0) 56 | assert s.measure(0) == MeasureResult(value=True, determined=True) 57 | assert s.measure(1) == MeasureResult(value=False, determined=True) 58 | 59 | 60 | def test_epr(): 61 | s = ChpSimulator(num_qubits=2) 62 | s.hadamard(0) 63 | s.cnot(0, 1) 64 | v1 = s.measure(0) 65 | assert not v1.determined 66 | v2 = s.measure(1) 67 | assert v2.determined 68 | assert v1.value == v2.value 69 | 70 | 71 | def test_phase_kickback_consume_s_state(): 72 | s = ChpSimulator(num_qubits=2) 73 | s.hadamard(1) 74 | s.phase(1) 75 | s.hadamard(0) 76 | s.cnot(0, 1) 77 | v1 = s.measure(1) 78 | assert not v1.determined 79 | if v1: 80 | s.phase(0) 81 | s.phase(0) 82 | s.phase(0) 83 | s.hadamard(0) 84 | assert s.measure(0) == MeasureResult(value=True, determined=True) 85 | 86 | 87 | def test_phase_kickback_preserve_s_state(): 88 | s = ChpSimulator(num_qubits=2) 89 | 90 | # Prepare S state. 91 | s.hadamard(1) 92 | s.phase(1) 93 | 94 | # Prepare test input. 95 | s.hadamard(0) 96 | 97 | # Kickback. 98 | s.cnot(0, 1) 99 | s.hadamard(1) 100 | s.cnot(0, 1) 101 | s.hadamard(1) 102 | 103 | # Check. 104 | s.phase(0) 105 | s.hadamard(0) 106 | assert s.measure(0) == MeasureResult(value=True, determined=True) 107 | s.phase(1) 108 | s.hadamard(1) 109 | assert s.measure(1) == MeasureResult(value=True, determined=True) 110 | 111 | 112 | def test_kickback_vs_stabilizer(): 113 | sim = ChpSimulator(num_qubits=3) 114 | sim.hadamard(2) 115 | sim.cnot(2, 0) 116 | sim.cnot(2, 1) 117 | sim.phase(0) 118 | sim.phase(1) 119 | sim.hadamard(0) 120 | sim.hadamard(1) 121 | sim.hadamard(2) 122 | assert str(sim).strip() == """ 123 | -YII 124 | -IYI 125 | +IIX 126 | ---- 127 | +XIX 128 | +IXX 129 | +YYZ 130 | """.strip().replace('I', '.') 131 | v0 = sim.measure(0, bias=0) 132 | assert str(sim).strip() == """ 133 | +XIX 134 | -IYI 135 | +IIX 136 | ---- 137 | +ZII 138 | +IXX 139 | +ZYY 140 | """.strip().replace('I', '.') 141 | v1 = sim.measure(1, bias=0) 142 | assert str(sim).strip() == """ 143 | +XIX 144 | +IXX 145 | +IIX 146 | ---- 147 | +ZII 148 | +IZI 149 | -ZZZ 150 | """.strip().replace('I', '.') 151 | v2 = sim.measure(2, bias=0) 152 | assert str(sim).strip() == """ 153 | +XIX 154 | +IXX 155 | +IIX 156 | ---- 157 | +ZII 158 | +IZI 159 | -ZZZ 160 | """.strip().replace('I', '.') 161 | assert v0 == MeasureResult(value=False, determined=False) 162 | assert v1 == MeasureResult(value=False, determined=False) 163 | assert v2 == MeasureResult(value=True, determined=True) 164 | 165 | 166 | def test_s_state_distillation_low_depth(): 167 | for _ in range(100): 168 | sim = ChpSimulator(num_qubits=9) 169 | 170 | stabilizers = [ 171 | (0, 1, 2, 3), 172 | (0, 1, 4, 5), 173 | (0, 2, 4, 6), 174 | (1, 2, 4, 7) 175 | ] 176 | checks = [ 177 | {'s': [0], 'q': stabilizers[0]}, 178 | {'s': [1], 'q': stabilizers[1]}, 179 | {'s': [2], 'q': stabilizers[2]}, 180 | ] 181 | 182 | stabilizer_measurements = [] 183 | anc = 8 184 | for stabilizer in stabilizers: 185 | sim.hadamard(anc) 186 | for k in stabilizer: 187 | sim.cnot(anc, k) 188 | sim.hadamard(anc) 189 | v = sim.measure(anc) 190 | assert not v.determined 191 | if v.value: 192 | sim.hadamard(anc) 193 | sim.phase(anc) 194 | sim.phase(anc) 195 | sim.hadamard(anc) 196 | stabilizer_measurements.append(v) 197 | 198 | qubit_measurements = [] 199 | for k in range(7): 200 | sim.phase(k) 201 | sim.hadamard(k) 202 | qubit_measurements.append(sim.measure(k)) 203 | 204 | if sum([int(e.value) for e in stabilizer_measurements + qubit_measurements]) & 1: 205 | sim.phase(7) 206 | sim.phase(7) 207 | 208 | sim.phase(7) 209 | sim.hadamard(7) 210 | r = sim.measure(7) 211 | 212 | assert r == MeasureResult(value=False, determined=True) 213 | 214 | for c in checks: 215 | rvs = [int(stabilizer_measurements[k].value) for k in c['s']] 216 | rms = [int(qubit_measurements[k].value) for k in c['q']] 217 | assert sum(rvs + rms) & 1 == 0 218 | 219 | 220 | def test_s_state_distillation_low_space(): 221 | for _ in range(100): 222 | sim = ChpSimulator(num_qubits=5) 223 | 224 | phasors = [ 225 | (0,), 226 | (1,), 227 | (2,), 228 | (0, 1, 2), 229 | (0, 1, 3), 230 | (0, 2, 3), 231 | (1, 2, 3), 232 | ] 233 | 234 | anc = 4 235 | for phasor in phasors: 236 | sim.hadamard(anc) 237 | for k in phasor: 238 | sim.cnot(anc, k) 239 | sim.hadamard(anc) 240 | sim.phase(anc) 241 | sim.hadamard(anc) 242 | v = sim.measure(anc) 243 | assert not v.determined 244 | if v.value: 245 | for k in phasor + (anc,): 246 | sim.hadamard(k) 247 | sim.phase(k) 248 | sim.phase(k) 249 | sim.hadamard(k) 250 | 251 | for k in range(3): 252 | assert sim.measure(k) == MeasureResult(value=False, determined=True) 253 | sim.phase(3) 254 | sim.hadamard(3) 255 | assert sim.measure(3) == MeasureResult(value=True, determined=True) 256 | 257 | 258 | def test_count_s_state_distillation_failure_cases(): 259 | def distill(errors: Set[int]) -> str: 260 | sim = ChpSimulator(num_qubits=5) 261 | 262 | phasors = [ 263 | (0,), 264 | (1,), 265 | (2,), 266 | (0, 1, 2), 267 | (0, 1, 3), 268 | (0, 2, 3), 269 | (1, 2, 3), 270 | ] 271 | 272 | anc = 4 273 | for e, phasor in enumerate(phasors): 274 | for k in phasor: 275 | sim.hadamard(anc) 276 | sim.cnot(anc, k) 277 | sim.hadamard(anc) 278 | sim.phase(anc) 279 | 280 | if e in errors: 281 | sim.phase(anc) 282 | sim.phase(anc) 283 | 284 | sim.hadamard(anc) 285 | v = sim.measure(anc) 286 | if v.value: 287 | sim.hadamard(anc) 288 | sim.phase(anc) 289 | sim.phase(anc) 290 | sim.hadamard(anc) 291 | assert not v.determined 292 | if v.value: 293 | for k in phasor: 294 | sim.hadamard(k) 295 | sim.phase(k) 296 | sim.phase(k) 297 | sim.hadamard(k) 298 | 299 | sim.phase(3) 300 | sim.phase(3) 301 | sim.phase(3) 302 | sim.hadamard(3) 303 | result = sim.measure(3) 304 | sim.hadamard(3) 305 | sim.phase(3) 306 | checks = [sim.measure(k) for k in range(3)] 307 | assert result.determined 308 | assert all(e.determined for e in checks) 309 | good_result = result.value is False 310 | checks_passed = not any(e.value for e in checks) 311 | if checks_passed: 312 | if good_result: 313 | return 'good' 314 | else: 315 | return 'ERROR' 316 | else: 317 | if good_result: 318 | return 'victim' 319 | else: 320 | return 'caught' 321 | 322 | def classify(errs) -> collections.Counter: 323 | result = collections.Counter() 324 | for err in errs: 325 | result[distill(err)] += 1 326 | return result 327 | 328 | nones = list(itertools.combinations(range(7), 0)) 329 | singles = list(itertools.combinations(range(7), 1)) 330 | doubles = list(itertools.combinations(range(7), 2)) 331 | triples = list(itertools.combinations(range(7), 3)) 332 | 333 | assert classify(nones) == {'good': 1} 334 | assert classify(singles) == {'caught': 3, 'victim': 4} 335 | assert classify(doubles) == {'caught': 12, 'victim': 9} 336 | assert classify(triples) == {'caught': 12, 'victim': 16, 'ERROR': 7} 337 | -------------------------------------------------------------------------------- /chp_sim/version.py: -------------------------------------------------------------------------------- 1 | __version__ = '0.1.1' 2 | -------------------------------------------------------------------------------- /requirements-dev.txt: -------------------------------------------------------------------------------- 1 | pytest 2 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | numpy 2 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | # Copyright 2018 The Cirq Developers 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # https://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | import io 16 | from setuptools import setup 17 | 18 | # This reads the __version__ variable from version.py 19 | __version__ = '' 20 | exec(open('chp_sim/version.py').read()) 21 | 22 | description = ("A reference implementation of Aaronson et al's CHP simulator " 23 | "for efficiently simulating quantum stabilizer circuits.") 24 | 25 | # README file as long_description. 26 | long_description = io.open('README.rst', encoding='utf-8').read() 27 | 28 | # Read in requirements 29 | requirements = open('requirements.txt').readlines() 30 | requirements = [r.strip() for r in requirements] 31 | 32 | setup(name='chp_sim', 33 | version=__version__, 34 | url='https://github.com/Strilanc/python-chp-stabilizer-simulator', 35 | author='Craig Gidney', 36 | author_email='craig.gidney@gmail.com', 37 | python_requires='>=3.6.0', 38 | install_requires=requirements, 39 | license='Apache 2', 40 | description=description, 41 | long_description=long_description, 42 | packages=['chp_sim']) 43 | --------------------------------------------------------------------------------