├── Examples.nb ├── LICENSE ├── Makefile ├── NOTICE ├── Overview.png ├── QASMConverter ├── NOTICE └── qasm_converter.py ├── README.md ├── UNSTABLE ├── CircuitParser │ ├── CircuitParser │ │ ├── CircuitParser.py │ │ └── Gates.py │ └── setup.py ├── MathematicaLink │ ├── mlinkmodule.c │ └── setup.py └── QSimplify │ ├── QSimplify │ └── Pythematica.py │ └── setup.py ├── Unit_tests.m └── UniversalQCompiler.m /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 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | unstable: qlcs mathematicalink 2 | 3 | qlcs: 4 | cd UNSTABLE;\ 5 | git clone https://github.com/Oe2tam/qlcs.git 6 | 7 | mathematicalink: 8 | cd UNSTABLE/MathematicaLink;\ 9 | python setup.py build 10 | 11 | unstable-install: 12 | echo "Installing UNSTABLE packages" 13 | pip3 install UNSTABLE/MathematicaLink/ 14 | pip3 install UNSTABLE/qlcs/ 15 | pip3 install UNSTABLE/QSimplify/ 16 | pip3 install UNSTABLE/CircuitParser/ 17 | 18 | clean: 19 | rm UNSTABLE/qlcs -rf 20 | rm UNSTABLE/MathematicaLink/build -rf 21 | 22 | remove: 23 | pip3 uninstall -y qlcs 24 | pip3 uninstall -y QSimplify 25 | pip3 uninstall -y MathematicaLink 26 | pip3 uninstall -y CircuitParser 27 | -------------------------------------------------------------------------------- /NOTICE: -------------------------------------------------------------------------------- 1 | UniversalQCompiler (https://github.com/Q-Compiler/UniversalQCompiler) 2 | 3 | The first release of UniversalQCompiler (v0.1) was developed by Raban Iten (ETH Zurich) and Roger Colbeck (University of York) from 2016-19 4 | with contributions from Luca Mondada, Oliver Reardon-Smith, Ethan Redmond and Ravjot Singh Kohli. 5 | -------------------------------------------------------------------------------- /Overview.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Q-Compiler/UniversalQCompiler/69c525d97affc4e6ed00fb9e1a67bb186a46b103/Overview.png -------------------------------------------------------------------------------- /QASMConverter/NOTICE: -------------------------------------------------------------------------------- 1 | ProjectQ (www.projectq.ch) 2 | 3 | The first release of ProjectQ (v0.1) was developed by Thomas Haener (thomas@projectq.ch) and Damian S. Steiger (damian@projectq.ch) at ETH Zurich in 2016. 4 | -------------------------------------------------------------------------------- /QASMConverter/qasm_converter.py: -------------------------------------------------------------------------------- 1 | # Copyright 2019 UniversalQCompiler (https://github.com/Q-Compiler/UniversalQCompiler) 2 | # Licensed under the Apache License, Version 2.0 (the "License"); 3 | # you may not use this file except in compliance with the License. 4 | # You may obtain a copy of the License at 5 | # http://www.apache.org/licenses/LICENSE-2.0 6 | # Unless required by applicable law or agreed to in writing, software 7 | # distributed under the License is distributed on an "AS IS" BASIS, 8 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 9 | # See the License for the specific language governing permissions and 10 | # limitations under the License. 11 | 12 | import argparse 13 | import sys 14 | import numpy as np 15 | 16 | from projectq import ops 17 | from projectq.setups import ibm, default 18 | from projectq.cengines import BasicEngine, MainEngine 19 | from projectq.backends import IBMBackend 20 | from projectq.meta import get_control_count, LogicalQubitIDTag 21 | 22 | from parsimonious.grammar import Grammar 23 | from parsimonious.nodes import NodeVisitor, RegexNode, Node 24 | from parsimonious.exceptions import VisitationError 25 | 26 | from sys import stderr 27 | 28 | def warning(s): 29 | print('Warning:', s, file=stderr) 30 | 31 | # ==== Parser code ==== 32 | 33 | # grammar defining acceptable Mathematica input 34 | # according to manual 35 | # int = float, but different in parsing 36 | grammar = Grammar(r""" 37 | circuit = open gates close 38 | gates = (gate komma gates) / gate 39 | gate = open (DIAG / CZ / CNOT / R / MST / TROUT / ANC / PS) close 40 | qubits = (qubit komma qubits) / qubit 41 | qubit = int 42 | floats = (float komma floats) / float 43 | float = ~"\s*([+-]?(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?)\s*" 44 | int = ~"\s*([+-]?(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?)\s*" 45 | open = ~"\s*{\s*" 46 | close = ~"\s*}\s*" 47 | komma = ~"\s*,\s*" 48 | 49 | DIAG = ~"\s*(-2(\.\d*)?)" komma open floats close komma open qubits close 50 | CZ = ~"\s*(-1(\.\d*)?)" komma qubit komma qubit 51 | CNOT = ~"\s*(0(\.\d*)?)" komma qubit komma qubit 52 | R = ~"\s*([1-3](\.\d*)?)" komma float komma qubit 53 | MST = ~"\s*(4(\.\d*)?)" komma "1" komma qubit 54 | TROUT = ~"\s*(4(\.\d*)?)" komma "0" komma qubit 55 | ANC = ~"\s*(5(\.\d*)?)" komma ~"([0-1])" komma qubit 56 | PS = ~"\s*(6(\.\d*)?)" komma ~"([0-1])" komma qubit 57 | """) 58 | 59 | # some helper functions 60 | 61 | # Having a nested list of the form [(),(),()...] flattens the tupels if they contain sub-tupels 62 | def flatten_touples(list_in): 63 | lst = [] 64 | for i in range(len(list_in)): 65 | if (type(list_in[i][0]) != tuple): 66 | lst.append(list_in[i]) 67 | else: 68 | for j in range(len(list_in[i])): 69 | lst.append(list_in[i][j]) 70 | return lst 71 | 72 | 73 | 74 | def max_qubit(gate_list): 75 | # look at qubit numbers in gate_list to find largest qubit 76 | return max(y for x in map( 77 | lambda x: x[1], 78 | gate_list) 79 | for y in x 80 | ) 81 | 82 | def build_circuit(gate_list, eng): 83 | # creates circuit for tuple list of gates 84 | # cannot be done earlier, as the number of qubits must be 85 | # known a priori 86 | nb_qubits = max_qubit(gate_list) + 1 87 | 88 | qubits = eng.allocate_qureg(nb_qubits) 89 | 90 | for (gate, qs) in gate_list: 91 | qs = tuple(map(lambda q: qubits[q], qs)) 92 | gate | qs 93 | 94 | return nb_qubits 95 | 96 | def get_qasm(eng, nb_qubits): 97 | # returns qasm code from engine 98 | 99 | # flush 100 | eng.flush() 101 | 102 | qasm = eng.backend.qasm 103 | 104 | # adds cosmetic line at the beginning (necessary for IBM) 105 | qasm = ("\ninclude \"qelib1.inc\";\nqreg q[{nq}];\ncreg c[{nq}];{qasm}\n").format( 106 | nq=nb_qubits, qasm=qasm) 107 | return qasm 108 | 109 | # helper function for all grammar rules that are sequences of type xs = (x '+' xs) / x 110 | def visit_list(xs): 111 | # remove parenthesese 112 | xs = xs[0] 113 | # hack to differentiate between one-el list and multi-el 114 | if type(xs) != list: 115 | return [xs] 116 | else: 117 | return [xs[0]] + xs[2] 118 | 119 | class InvalidRotationGateError(ValueError): 120 | pass 121 | 122 | # transforms parsed tree into a gate list 123 | class ToGateListVisitor(NodeVisitor): 124 | 125 | # for every type of node, run one of these parsers: 126 | def visit_circuit(self, node, circuit): 127 | return circuit[1] 128 | 129 | def visit_gates(self, node, gs): 130 | return visit_list(gs) 131 | 132 | def visit_gate(self, node, g): 133 | # remove parentheses 134 | g = g[1] 135 | return g[0] 136 | 137 | def visit_qubit(self, node, q): 138 | # doesnt seem to be used (== int) 139 | return q[0] 140 | 141 | def visit_qubits(self, node, qs): 142 | return visit_list(qs) 143 | 144 | def visit_float(self, node, f): 145 | return float(node.match.group(1)) 146 | 147 | def visit_floats(self, node, fs): 148 | return visit_list(fs) 149 | 150 | def visit_int(self, node, i): 151 | return round(float(node.match.group(1))) 152 | 153 | def visit_DIAG(self, node, params): 154 | warning("Diagonal gates cannot be translated. Please decompose it using UniversalQCompiler with the method DecDiagGate") 155 | return ("DIAG", (-1,)) 156 | 157 | def visit_CZ(self, node, params): 158 | ctr,targ = params[2], params[4] 159 | return (ops.CZ, (ctr,targ)) 160 | 161 | def visit_CNOT(self, node, params): 162 | ctr,targ = params[2], params[4] 163 | return (ops.CNOT, (ctr,targ)) 164 | 165 | def visit_R(self, node, params): 166 | # type parameter 167 | t = params[0] 168 | typ = round(float(t)) 169 | # other params 170 | angle = params[2] 171 | q = params[4] 172 | 173 | # different angle convention 174 | angle = -angle 175 | 176 | # differentiate with type 177 | if typ == 1: 178 | return (ops.Rx(angle), (q,)) 179 | elif typ == 2: 180 | return (ops.Ry(angle), (q,)) 181 | elif typ == 3: 182 | return (ops.Rz(angle), (q,)) 183 | else: 184 | raise InvalidRotationGateError 185 | 186 | def visit_MST(self, node, params): 187 | return (ops.Measure, (params[4],)) 188 | 189 | def visit_TROUT(self, node, params): 190 | warning("Trace out operations were replaced by measurement operations.") 191 | return (ops.Measure, (params[4],)) 192 | 193 | def visit_ANC(self, node, params): 194 | warning("Marking ancilla qubits is not supported at the moment. Please remove the ancillas from your input gate sequence.") 195 | return ('ANC',(-1,)) 196 | 197 | def visit_PS(self, node, params): 198 | warning('Post selection operations in the gate list are not supported.') 199 | return ('PS',(-1,)) 200 | 201 | # dummies for debuging 202 | def visit_open(self, node, params): return "SHOULDNT BE USED" 203 | def visit_close(self, node, params): return "SHOULDNT BE USED" 204 | def visit_komma(self, node, params): return "SHOULDNT BE USED" 205 | 206 | # fall through for parenthesised and regex nodes 207 | def generic_visit(self, node, params): 208 | # differentiate parenthesised from regex 209 | if type(node) == RegexNode: 210 | # regex: return matched el 211 | return node.match.group(1) 212 | else: 213 | # parenthesised: return children 214 | return params 215 | 216 | # ==== MAIN script code ==== 217 | 218 | # The following class is inspired by the IBMBackend of ProjectQ, which is released under the Apache License, Version 2 219 | # (The NOTICE file of ProjectQ is provided in the folder QASMConverter) 220 | 221 | # Copyright 2017 ProjectQ-Framework (www.projectq.ch) 222 | # Licensed under the Apache License, Version 2.0 (the "License"); 223 | # you may not use this file except in compliance with the License. 224 | # You may obtain a copy of the License at 225 | # http://www.apache.org/licenses/LICENSE-2.0 226 | # Unless required by applicable law or agreed to in writing, software 227 | # distributed under the License is distributed on an "AS IS" BASIS, 228 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 229 | # See the License for the specific language governing permissions and 230 | # limitations under the License. 231 | 232 | # Note that the following code of ProjectQ was adapted by Luca Mondada 233 | 234 | class GetQASMBackend(BasicEngine): 235 | def __init__(self, *args, **kwargs): 236 | BasicEngine.__init__(self, *args, **kwargs) 237 | 238 | self._reset() 239 | 240 | def is_available(self, cmd): 241 | g = cmd.gate 242 | if g == ops.NOT and get_control_count(cmd) <= 1: 243 | return True 244 | if get_control_count(cmd) == 0: 245 | if g in (ops.T, ops.Tdag, ops.S, ops.Sdag, ops.H, ops.Y, ops.Z): 246 | return True 247 | if isinstance(g, (ops.Rx, ops.Ry, ops.Rz)): 248 | return True 249 | if g in (ops.Measure, ops.Allocate, ops.Deallocate, ops.Barrier): 250 | return True 251 | return False 252 | 253 | def _store(self, cmd): 254 | 255 | if self._clear: 256 | self._clear = False 257 | self.qasm = "" 258 | self._allocated_qubits = set() 259 | 260 | gate = cmd.gate 261 | 262 | if gate == ops.Allocate: 263 | self._allocated_qubits.add(cmd.qubits[0][0].id) 264 | return 265 | 266 | if gate == ops.Deallocate: 267 | return 268 | 269 | if gate == ops.Measure: 270 | assert len(cmd.qubits) == 1 and len(cmd.qubits[0]) == 1 271 | qb_id = cmd.qubits[0][0].id 272 | logical_id = None 273 | for t in cmd.tags: 274 | if isinstance(t, LogicalQubitIDTag): 275 | logical_id = t.logical_qubit_id 276 | break 277 | assert logical_id is not None 278 | self._measured_ids += [logical_id] 279 | elif gate == ops.NOT and get_control_count(cmd) == 1: 280 | ctrl_pos = cmd.control_qubits[0].id 281 | qb_pos = cmd.qubits[0][0].id 282 | self.qasm += "\ncx q[{}], q[{}];".format(ctrl_pos, qb_pos) 283 | elif gate == ops.Barrier: 284 | qb_pos = [qb.id for qr in cmd.qubits for qb in qr] 285 | self.qasm += "\nbarrier " 286 | qb_str = "" 287 | for pos in qb_pos: 288 | qb_str += "q[{}], ".format(pos) 289 | self.qasm += qb_str[:-2] + ";" 290 | elif isinstance(gate, (ops.Rx, ops.Ry, ops.Rz)): 291 | assert get_control_count(cmd) == 0 292 | qb_pos = cmd.qubits[0][0].id 293 | u_strs = {'Rx': 'u3({}, -pi/2, pi/2)', 'Ry': 'u3({}, 0, 0)', 294 | 'Rz': 'u1({})'} 295 | gate = u_strs[str(gate)[0:2]].format(gate.angle) 296 | self.qasm += "\n{} q[{}];".format(gate, qb_pos) 297 | else: 298 | assert get_control_count(cmd) == 0 299 | if str(gate) in self._gate_names: 300 | gate_str = self._gate_names[str(gate)] 301 | else: 302 | gate_str = str(gate).lower() 303 | 304 | qb_pos = cmd.qubits[0][0].id 305 | self.qasm += "\n{} q[{}];".format(gate_str, qb_pos) 306 | 307 | def _run(self): 308 | if self.qasm == "": 309 | return 310 | # finally: add measurements (no intermediate measurements are allowed) 311 | for measured_id in self._measured_ids: 312 | qb_loc = self.main_engine.mapper.current_mapping[measured_id] 313 | self.qasm += "\nmeasure q[{}] -> c[{}];".format(qb_loc, 314 | qb_loc) 315 | 316 | def _reset(self): 317 | self._measured_ids = [] 318 | self._clear = True 319 | 320 | def receive(self, command_list): 321 | for cmd in command_list: 322 | if not cmd.gate == ops.FlushGate(): 323 | self._store(cmd) 324 | else: 325 | self._run() 326 | self._reset() 327 | 328 | """ 329 | Mapping of gate names from our gate objects to the IBM QASM representation. 330 | """ 331 | _gate_names = {str(ops.Tdag): "tdg", str(ops.Sdag): "sdg"} 332 | 333 | def _ask(msg, default=None): 334 | ans = input(msg) 335 | while True: 336 | ans = ans if ans != '' else default 337 | 338 | if ans.lower().startswith('y'): 339 | return True 340 | elif ans.lower().startswith('n'): 341 | return False 342 | else: 343 | print('Please answer with yes or no: ') 344 | 345 | def _define_args(): 346 | args = argparse.ArgumentParser( 347 | description='A converter for quantum circuits from Mathematica format to OpenQASM code.' 348 | ) 349 | args.add_argument( 350 | '--ibm', 351 | '-q', 352 | default=None, 353 | const='ibmq_qasm_simulator', 354 | metavar='dev', 355 | nargs='?', 356 | help='additionally convert to OpenQASM code that is compatible with the IBM Q Computer `dev` (default: ibmq_qasm_simulator)' 357 | ) 358 | args.add_argument( 359 | '--use-hardware', 360 | '-w', 361 | dest='on_hardware', 362 | action='store_true', 363 | help='directly send code to IBM QE and run code on real hardware (default: false)' 364 | ) 365 | args.add_argument( 366 | '--number-iterations', 367 | '-n', 368 | metavar='N', 369 | dest='n', 370 | default=1024, 371 | help='number of iterations that are run on the IBM Q Computer to obtain output measurements. Only with option `--use-hardware (-w) or --simulator (-s)` (default: 1024)', 372 | type=int 373 | ) 374 | args.add_argument( 375 | '--simulator', 376 | '-s', 377 | dest='s', 378 | action='store_true', 379 | help='run code on IBM simulator (instead of real IBM hardware)`' 380 | ) 381 | args.add_argument( 382 | 'infile', 383 | metavar='input file', 384 | type=argparse.FileType('r'), 385 | nargs='?', 386 | default=sys.stdin, 387 | help='Name of input file in Mathematica format' 388 | ) 389 | args.add_argument( 390 | 'outfile', 391 | metavar='output file', 392 | type=argparse.FileType('w'), 393 | nargs='?', 394 | default=sys.stdout, 395 | help='Name of output file in OpenQASM format' 396 | ) 397 | 398 | return args 399 | 400 | def _check(args): 401 | if args.on_hardware and args.s: 402 | print('You cannot use flags --use-hardware (-w) and --simulator (-s) at the same time') 403 | msg = 'For faster results, you can run your code on the IBM simulator. Do you still want to run the code on real hardware? (y/N): ' 404 | if _ask(msg, default='n'): 405 | args.s = False 406 | else: 407 | args.on_hardware = False 408 | 409 | if (args.on_hardware or args.s) and not args.ibm: 410 | print('You cannot send your code onto IBM hardware without converting your code into IBM compatible code.') 411 | msg = 'Do you want to convert your code into IBM compatible code? (Y/n): ' 412 | if _ask(msg, default='y'): 413 | args.ibm = True 414 | return True 415 | else: 416 | sys.exit(1) 417 | 418 | def main(): 419 | 420 | args = _define_args() 421 | 422 | args = args.parse_args() 423 | 424 | _check(args) 425 | 426 | fin = args.infile 427 | fout = args.outfile 428 | 429 | # by default use IBMQ simulator to generate engines 430 | dev = 'ibmq_qasm_simulator' 431 | 432 | # remove the CNot flipper 433 | if not args.ibm: 434 | engines = engines[:-2] + engines[-1:] 435 | print('Converting...') 436 | else: 437 | print('Converting for IBM Q Experience...') 438 | dev = ibm.args 439 | 440 | engines = ibm.get_engine_list(device=dev) 441 | 442 | if args.on_hardware: 443 | print('We will run the converted code on the IBM device {}\n.'.format(args.ibm)) 444 | backend = IBMBackend(use_hardware=True, device=args.ibm, num_runs=args.n) 445 | elif args.s: 446 | print('We will run the converted code on the IBM simulator\n.') 447 | backend = IBMBackend(use_hardware=False, device=args.ibm, num_runs=args.n) 448 | else: 449 | # backend similar to IBMBackend creating qasm code but without running it 450 | backend = GetQASMBackend() 451 | 452 | eng = MainEngine(backend=backend, engine_list=engines) 453 | 454 | s = fin.read() 455 | fin.close() 456 | 457 | # parse input 458 | root = grammar.parse(s) 459 | # create visitor that transforms tree into gate list 460 | visitor = ToGateListVisitor() 461 | # pass root of parsed tree to visitor 462 | gate_list = visitor.visit(root) 463 | #gate_list=flatten_touples(gate_list) 464 | 465 | # create circuit from gate_list 466 | nb_qubits = build_circuit(gate_list, eng) 467 | # create qasm code 468 | qasm = get_qasm(eng, nb_qubits) 469 | 470 | if fout == sys.stdout: 471 | print(5*'=' + ' OpenQASM code ' + 5*'=') 472 | 473 | fout.write(qasm) 474 | 475 | if fout != sys.stdout: 476 | print('OpenQASM output saved to {}'.format(fout.name)) 477 | print() 478 | 479 | if hasattr(backend, 'get_probabilities'): 480 | print(5*'=' + ' Results from {} run on hardware '.format(args.n) + 5*'=') 481 | for k,v in sorted(backend.get_probabilities(qureg).items()): 482 | print('Probability for state |{}>: {}'.format(k,v)) 483 | 484 | if __name__ == "__main__": 485 | 486 | main() 487 | 488 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # UniversalQCompiler - An opensource software package for decomposing generic quantum computations 2 | 3 | UniversalQCompiler provides a Mathematica package that allows to decompose generic quantum computations into sequences of C-NOT gates and arbitrary single-qubit rotations. In particular, the package allows for the following: 4 | 5 | * Decomposing isometries from *m* to *n* qubits, and hence, in particular decomposing arbitrary unitaries on *m* qubits and to do state preparation 6 | * Decomposing quantum channels from *m* to *n* qubits 7 | * Decomposing POVMs on *m* qubits 8 | * Simplifying gate sequences 9 | * Drawing quantum circuits within Mathematica 10 | * Exporting quantum circuits to LATEX 11 | * Running quantum circuits on the IBM Q Experience (using the OpenQASM converter) 12 | * Compilation for trapped ions, i.e., converting between gate sequences using CNOT (and single-qubit rotation) to those that use Molmer-Sorensen gates 13 | 14 | A detailed documentation of the Mathematica package can be found on our [webpage](http://www-users.york.ac.uk/~rc973/UniversalQCompiler.html). The notebook Examples.nb helps the user to get started quickly and provides a short overview over the methods provided by UniversalQCompiler. 15 | 16 | This project also contains a converter (based on [ProjectQ](https://github.com/ProjectQ-Framework/ProjectQ)) to translate gate sequences from the Mathematica package UniversalQCompiler to [OpenQASM](https://arxiv.org/abs/1707.03429), the quantum assembly language used, for instance, by the IBM Q Experience. 17 | 18 | Moreover, we provide bindings to directly link Python to Mathematica. This is however provided without any guarantees or support in the directory `UNSTABLE` 19 | 20 | ## Overview 21 | 22 | The diagram below indicates how the Mathematica packages [QI](https://github.com/rogercolbeck/QI) and UniversalQCompiler can be used to analyse quantum information protocols for running on some quantum hardware: 23 | 24 | ![alt text](Overview.png) 25 | 26 | ## Getting started 27 | 28 | To use our Mathematica package UniversalQCompiler.m, you need to have installed Wolfram Mathematica (we tested the package for Mathematica 11.1 and 11.3). The code relies on the package QI.m which can be downloaded from https://github.com/rogercolbeck/QI. The package can then be loaded in any Mathematica notebook (see our [documentation](https://docs.google.com/forms/d/e/1FAIpQLSc_QmF_qFwp25f8fsrVWiMKGkKbtPZeSNbOWLFU357tLpKNVw/viewform) for more details). 29 | 30 | Note that the Makefile is only used for the unstable bindings to Python. You do not need any Makefile for the Mathematica package or the QASM converter. 31 | 32 | ## Feedback 33 | We would be very happy for any feedback about UniversalQCompiler. Please do not hesitate to write us a mail (itenr@itp.phys.ethz.ch or roger.colbeck@york.ac.uk) if you have any suggestions for improvements or comments. 34 | 35 | ## Please cite 36 | An overview over the package UniversalQCompiler and some theoretical background about the decomposition methods that it uses can be found on [arXiv:1904.01072](https://arxiv.org/pdf/1904.01072.pdf). 37 | 38 | ## References 39 | 40 | The code is mainly based on the following papers: 41 | 42 | * Raban Iten, Roger Colbeck, Ivan Kukuljan, Jonathan Home, and Matthias Christandl, Phys. Rev. A 93, 032318 (2016). 43 | * Emanuel Malvetti, Raban Iten, and Roger Colbeck, arXiv:2006.00016 (2020). 44 | * M. Plesch and Č. Brukner, Phys. Rev. A 83, 032302 (2011). 45 | * O. Giraud, M. Žnidarič, and B. Georgeot, Phys. Rev. A 80, 042309 (2009). 46 | * V. V. Shende, S. S. Bullock, and I. L. Markov, IEEE Transactions on Computer-Aided Design of Integrated Circuits and Systems 25, 1000 (2006). 47 | * V. Bergholm, J. J. Vartiainen, M. Möttönen, and M. M.Salomaa, Phys. Rev. A 71, 052330 (2005). 48 | * V. V. Shende, S. S. Bullock, and I. L. Markov, Phys. Rev. A 70, 012310 (2004). 49 | * E. Knill, LANL report LAUR-95-2225, arXiv:quant-ph/9508006 (1995). 50 | 51 | ## Authors 52 | 53 | The first release of UniversalQCompiler (v0.1) was developed by Raban Iten (ETH Zurich) and Roger Colbeck (University of York) from 2016-19 with contributions from Emanuel Malvetti, Luca Mondada, Gabrielle Pauvert, Oliver Reardon-Smith, Ethan Redmond and Ravjot Singh Kohli: 54 | 55 | * Luca Mondada added the Python interface for converting the circuits to QASM. 56 | * Oliver Reardon-Smith added functionality to cope with small cases, wrote the first version of the visualisation code and implemented several bug fixes. 57 | * Ethan Redmond added functionality to compute the Knill decomposition and do state preparation. 58 | * Ravjot Singh Kohli wrote the first version of the code for decomposing isometries with the Column-by-Column decomposition. 59 | * Gabrielle Pauvert added functionality to decompose instruments. 60 | * Emanuel Malvetti developed code for the decomposition of (sparse) isometries using the Householder decomposition. 61 | 62 | Emanuel Malvetti and Luca Mondada worked on the code as semester students at the Institute for Theoretical Physics at ETH Zürich under supervision of Raban Iten. 63 | 64 | Ravjot Singh Kohli, Ethan Redmond and Gabrielle Pauvert worked on the code while summer students in the Department of Mathematics at the University of York under supervision of Roger Colbeck. 65 | 66 | ## Mathematica to OpenQASM converter 67 | A simple-to-use python script converts the Mathematica output gate sequences in list format (not containing diagonal gates, ancilla markers or post selection operations) into OpenQASM, the Quantum Assembly Language used among others by the IBM Q Experience. The converted outputs can be used directly as input for the IBM quantum computers. Note that this script requires Python version 3 and the projectq package. 68 | 69 | The converter is composed of a single file, `qasm_converter.py` that can be found 70 | in the `QASMConverter` folder. 71 | 72 | ### Installation 73 | The script requires Python 3 to be installed as well as the packages ``numpy``, ``projectq`` and ``parsimonious`` for parsing. 74 | If you are using pip, you can install any of these packages with the command 75 | ```shell 76 | pip3 install PKG_NAME 77 | ``` 78 | 79 | ### Usage 80 | First make sure the Mathematica output is numerical. Then save it to the file "data" 81 | ```shell 82 | out = PrepareForQASM[gateList]; 83 | strm = OpenWrite["data"]; 84 | Write[strm, out]; 85 | Close[strm]; 86 | ``` 87 | 88 | This file can then be transformed into QASM using the qasm\_converter.py script: 89 | ``` 90 | python qasm_converter.py data OUTPUT.qasm 91 | ``` 92 | The QASM code will be found in OUTPUT.qasm. 93 | 94 | The script can also convert Mathematica code into assembly code (OpenQASM) that can be direclty uploaded into the IBM Quantum Experience. 95 | To convert Mathematica code into OpenQASM code compatible with the IBM Quantum computers, use the option ``--ibm``, or ``-q``. 96 | You can also send the code direclty to the IBM Quantum computers using the option ``--simulator`` (``-s``) to run on the IBM simulator or ``--use-hardware`` (``-w``) to run on real hardware. See the help for more information. 97 | ```shell 98 | python qasm_converter.py -h 99 | ``` 100 | 101 | ## Unstable Mathematica-Python bindings [not supported] 102 | These bindings give the user a python interface to the methods that are written in Mathematica. This allows to seamleesly use the Mathematica code within any Python project. The code worked well for us, but we do not support any issues with it. 103 | 104 | Please note that you need to have Mathematica installed on your machine, together with a valid license. 105 | 106 | ### Installation 107 | Everything can be compiled easily using the Makefile. It is highly recommended to use virtualenv to keep the installed packages on this project only. 108 | 109 | ```shell 110 | virtualenv SOME_ENV 111 | source SOME_ENV/bin/activate 112 | ``` 113 | 114 | To link Mathematica to this code, you need to open the file MathematicaLink/setup.py and change the parameters at the top of the file (your system architecture and the version of Mathematica you are using. Double check the mathematica\_folder to make sure it corresponds to your actual path). 115 | 116 | Once this is done, you can install the package easily with the following commands. 117 | Note: this Makefile uses pip as python package management system. You can also install everything manually if you are not using pip. 118 | ``` 119 | make unstable 120 | make unstable-install 121 | ``` 122 | 123 | ## License 124 | UniversalQCompiler is released under the Apache 2 license. 125 | -------------------------------------------------------------------------------- /UNSTABLE/CircuitParser/CircuitParser/CircuitParser.py: -------------------------------------------------------------------------------- 1 | # Copyright 2019 UniversalQCompiler (https://github.com/Q-Compiler/UniversalQCompiler) 2 | # Licensed under the Apache License, Version 2.0 (the "License"); 3 | # you may not use this file except in compliance with the License. 4 | # You may obtain a copy of the License at 5 | # http://www.apache.org/licenses/LICENSE-2.0 6 | # Unless required by applicable law or agreed to in writing, software 7 | # distributed under the License is distributed on an "AS IS" BASIS, 8 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 9 | # See the License for the specific language governing permissions and 10 | # limitations under the License. 11 | 12 | from projectq import ops 13 | from projectq.cengines import MainEngine 14 | 15 | from CircuitParser.Gates import OneQubitGate, Rx, Ry, Rz, CNot, ComposedGate 16 | 17 | def mathematica_to_python(s): 18 | 19 | def _parser(ls): 20 | gate = [Rx, Ry, Rz] 21 | a,b,c = round(ls[0].real), float(ls[1].real), float(ls[2].real) 22 | if a == 0: 23 | return CNot(control=int(b-1), target=int(c-1)) 24 | elif a > 0: 25 | return gate[a-1](channel=int(c-1), angle=float(-b)) 26 | else: 27 | raise KeyError 28 | 29 | def _string_to_array(s): 30 | s = s.replace(' ', '') 31 | s = s.replace('\n', '') 32 | s = s.replace('*I', 'j') 33 | s = s.replace('*^', 'e') 34 | assert s.find('^') < 0 35 | assert s.find('*') < 0 36 | fst, empty = _parse_array(s) 37 | assert empty == '' 38 | return fst 39 | 40 | assert len(s.split('=')) <= 2, 'The Mathematica output should only contain one variable' 41 | 42 | # ignore what precedes the = symbol 43 | s = s.split('=')[-1] 44 | return list(map(_parser, _string_to_array(s))) 45 | 46 | def python_to_projectq(gates, eng = MainEngine()): 47 | gates = gates.copy() 48 | gates.reverse() 49 | 50 | qubits = gates.max_channel() + 1 51 | 52 | circuit = eng.allocate_qureg(qubits) 53 | 54 | own2projectq = {Rx: ops.Rx, Ry: ops.Ry, Rz: ops.Rz, CNot: ops.CNOT} 55 | 56 | for g in gates: 57 | for gate_own, gate_projq in own2projectq.items(): 58 | if isinstance(g, gate_own): 59 | if isinstance(g, OneQubitGate): 60 | gate_projq(g.angle) | circuit[g.channel] 61 | else: 62 | gate_projq | (circuit[g.channel2], circuit[g.channel1]) 63 | break 64 | else: 65 | raise KeyError 66 | 67 | for q in range(qubits): 68 | ops.Measure | circuit[q] 69 | 70 | eng.flush() 71 | 72 | qasm = eng.backend.qasm 73 | qasm = ("\ninclude \"qelib1.inc\";\nqreg q[{nq}];\ncreg c[{nq}];{qasm}\n").format( 74 | nq=qubits, qasm=qasm) 75 | 76 | return qasm, circuit 77 | 78 | def mathematica_to_qasm(s, eng=None): 79 | if not eng: 80 | eng = MainEngine() 81 | 82 | gates = ComposedGate(mathematica_to_python(s)) 83 | qubits = gates.max_channel() + 1 84 | qasm, qureg = python_to_projectq(gates, eng) 85 | 86 | return qasm, qureg 87 | 88 | def _parse_array(s): 89 | if s[0] == '{': 90 | s = s[1:] 91 | ret = [] 92 | i = 1 93 | while s[0] != '}': 94 | fst, s = _parse_array(s) 95 | ret.append(fst) 96 | s = s[1:].lstrip(',') 97 | return ret, s 98 | else: 99 | fst, rst = _splitAt(',}', s) 100 | rst = rst.lstrip(',') 101 | fst = fst.strip('"') 102 | 103 | try: 104 | return complex(fst), rst 105 | except ValueError: 106 | raise ValueError("Mathematica return value not understood: "+fst) 107 | 108 | def _splitAt(sep, s): 109 | i = 0 110 | while i < len(s) and s[i] not in sep: i += 1 111 | return s[:i], s[i:] 112 | -------------------------------------------------------------------------------- /UNSTABLE/CircuitParser/CircuitParser/Gates.py: -------------------------------------------------------------------------------- 1 | # Copyright 2019 UniversalQCompiler (https://github.com/Q-Compiler/UniversalQCompiler) 2 | # Licensed under the Apache License, Version 2.0 (the "License"); 3 | # you may not use this file except in compliance with the License. 4 | # You may obtain a copy of the License at 5 | # http://www.apache.org/licenses/LICENSE-2.0 6 | # Unless required by applicable law or agreed to in writing, software 7 | # distributed under the License is distributed on an "AS IS" BASIS, 8 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 9 | # See the License for the specific language governing permissions and 10 | # limitations under the License. 11 | 12 | import numpy as np 13 | from numpy import sin,cos 14 | from functools import reduce 15 | from copy import copy 16 | 17 | def single_qubitify(mat, channel, n): 18 | """ given a unitary 2x2 matrix and the channel to apply it on 19 | returns the associated 2**n x 2**n matrix""" 20 | 21 | assert mat.shape == (2,2) 22 | return reduce(np.kron, [ 23 | np.identity(2**(n-channel-1)), 24 | mat, 25 | np.identity(2**channel) 26 | ]) 27 | 28 | def change_channel_order(mat, frm,to): 29 | """returns the matrix corresponding to mat when the tensored basis is reordered: frm <-> to""" 30 | 31 | def swap_bits(n,i,j): 32 | """swaps i-th and j-th bit in n""" 33 | bits_are_different = int((n >> i) % 2 != (n >> j) % 2) 34 | return n ^ ((bits_are_different << i) | (bits_are_different << j)) 35 | 36 | n,m = mat.shape 37 | return np.array( 38 | [[mat[swap_bits(i,frm,to), swap_bits(j,frm,to)] for j in range(m)] for i in range(n)] 39 | ) 40 | 41 | class Gate: 42 | def compute(self, vec): 43 | raise NotImplementedError("compute() for "+type(self)+' not defined') 44 | 45 | def get_matrix(self, dim): 46 | raise TypeError("Matrix of "+type(self)+' not defined') 47 | 48 | def inverse(self): 49 | raise TypeError('Inverse of '+type(self)+' not defined') 50 | 51 | class SimpleGate(Gate): 52 | # uses the representation defined in the concrete gates 53 | def __repr__(self, fmt=''): 54 | cpy = copy(self) 55 | for attr in [k for k,v in self.parameters.items() if v is float]: 56 | if type(getattr(cpy, attr)) is not float: 57 | # parametrised template 58 | continue 59 | setattr(cpy, attr, round(getattr(cpy,attr), self.str_digit_rounding)) 60 | return self.representation.replace('{', '{0.').format(cpy) 61 | 62 | def __init__(self, channel_offset=0, **kwargs): 63 | self.str_digit_rounding = 2 64 | 65 | for k,v in kwargs.items(): 66 | try: 67 | # handle synonyms 68 | if hasattr(self, 'synonyms') and k in self.synonyms: 69 | k = self.synonyms[k] 70 | # this is for one-off channel count in Mathematica 71 | if self.parameters[k] is int: 72 | setattr(self, k, self.parameters[k](v) - channel_offset) 73 | else: 74 | setattr(self, k, self.parameters[k](v)) 75 | except KeyError: 76 | raise TypeError("'" + k + "' is an invalid keyword argument for this function") 77 | 78 | def compute(self, vec): 79 | n = int(np.log2(len(vec))) 80 | return np.dot(self.get_matrix(n), vec) 81 | 82 | @property 83 | def channels(self): 84 | try: 85 | return [self.channel] 86 | except AttributeError: 87 | return [self.channel1, self.channel2] 88 | 89 | def max_channel(self): 90 | return max(self.channels) 91 | 92 | # always keep the angle between 0 and 2pi 93 | @property 94 | def angle(self): 95 | return self.__angle 96 | 97 | @angle.setter 98 | def angle(self, angle): 99 | try: 100 | self.__angle = angle % (2 * np.pi) 101 | except TypeError: 102 | # parametrised angles 103 | self.__angle = angle 104 | pass 105 | 106 | class ComposedGate(Gate, list): 107 | def compute(self, vec): 108 | for g in reversed(self): 109 | vec = g.compute(vec) 110 | return vec 111 | 112 | def get_matrix(self, dim): 113 | ret = np.identity(2**dim) 114 | for g in self: 115 | ret = np.dot(ret, g.get_matrix(dim)) 116 | return ret 117 | 118 | def inverse(self): 119 | return list(map(lambda gate: gate.inverse(), reversed(self))) 120 | 121 | def copy(self): 122 | return ComposedGate(super(ComposedGate, self).copy()) 123 | def of_qubit(self, qubit): 124 | """ 125 | iterator only through gates concerning qubit `qubit` 126 | """ 127 | for g in self: 128 | if isinstance(g, OneQubitGate): 129 | if g.channel == qubit: 130 | yield g 131 | elif isinstance(g, TwoQubitGate): 132 | if g.channel1 == qubit or g.channel2 == qubit: 133 | yield g 134 | else: 135 | raise NotImplementedError 136 | 137 | def max_channel(self): 138 | return max(map(SimpleGate.max_channel, self)) 139 | 140 | class OneQubitGate(SimpleGate): 141 | def get_matrix(self, dim=1): 142 | if dim == 1: 143 | return self.__matrix__() 144 | else: 145 | return single_qubitify(self.__matrix__(), self.channel, dim) 146 | 147 | class TwoQubitGate(SimpleGate): 148 | def get_matrix(self, dim=2): 149 | """applies kronecker product to gate matrix for the n-spin situation""" 150 | if dim == 2: 151 | ret = self.__matrix__() 152 | else: 153 | ret = np.kron(np.identity(2**(dim-2)), self.__matrix__()) 154 | # you need to be careful not to swap order twice 155 | if self.channel1 == 1 and self.channel2 == 0: 156 | ret = change_channel_order(ret, 0, 1) 157 | elif self.channel1 == 1: 158 | ret = change_channel_order(ret, 1, self.channel2) 159 | ret = change_channel_order(ret, 0, self.channel1) 160 | elif self.channel2 == 0: 161 | ret = change_channel_order(ret, 0, self.channel1) 162 | ret = change_channel_order(ret, 1, self.channel2) 163 | elif self.channel1 == 0 and self.channel2 == 1: 164 | pass 165 | else: 166 | ret = change_channel_order(ret, 0, self.channel1) 167 | ret = change_channel_order(ret, 1, self.channel2) 168 | return ret 169 | 170 | class Rx(OneQubitGate): 171 | representation = 'Rx({channel})({angle})' 172 | parameters = {'channel': int, 'angle': float} 173 | 174 | def inverse(self): 175 | return Rx(channel=self.channel, angle=-self.angle) 176 | 177 | def __matrix__(self): 178 | return np.array( 179 | [[cos(self.angle/2), -1j*sin(self.angle/2)], 180 | [-1j*sin(self.angle/2), cos(self.angle/2)]]) 181 | 182 | class Ry(OneQubitGate): 183 | representation = 'Ry({channel})({angle})' 184 | parameters = {'channel':int, 'angle':float} 185 | 186 | def inverse(self): 187 | return Ry(channel=self.channel, angle=-self.angle) 188 | 189 | def __matrix__(self): 190 | return np.array( 191 | [[cos(self.angle/2), -sin(self.angle/2)], 192 | [sin(self.angle/2), cos(self.angle/2)]]) 193 | 194 | class Rz(OneQubitGate): 195 | representation = 'Rz({channel})({angle})' 196 | parameters = {'channel':int, 'angle':float} 197 | 198 | def inverse(self): 199 | return Rz(channel=self.channel, angle=-self.angle) 200 | 201 | def __matrix__(self): 202 | return np.array( 203 | [[np.exp(-1j*self.angle/2), 0], 204 | [0, np.exp(1j*self.angle/2)]]) 205 | 206 | class R(OneQubitGate): 207 | representation = 'R({channel})({theta},{phi})' 208 | parameters = {'channel':int, 'theta':float, 'phi':float} 209 | 210 | def __matrix__(self): 211 | return np.array( 212 | [[np.cos(self.theta/2), -1j * np.exp(-1j*self.phi)*np.sin(self.theta/2)], 213 | [-1j*np.exp(1j*self.phi)*np.sin(self.theta/2), np.cos(self.theta/2)]]) 214 | 215 | class CNot(TwoQubitGate): 216 | representation = 'C({channel2})({channel1})' 217 | parameters = {'channel1':int, 'channel2':int} 218 | synonyms = {'control': 'channel2', 'target': 'channel1'} 219 | 220 | def inverse(self): 221 | return CNot(channel1=self.channel1, channel2=self.channel2) 222 | 223 | def __matrix__(self): 224 | return np.array( 225 | [[1,0,0,0], 226 | [0,1,0,0], 227 | [0,0,0,1], 228 | [0,0,1,0]]) 229 | 230 | class Swap(TwoQubitGate): 231 | """ 232 | This gate swaps the two qubits. 233 | 234 | This is useful for some template identity. All instances of Swap are removed during CNot_simplify 235 | """ 236 | representation = 'S({channel1})({channel2})' 237 | parameters = {'channel1': int, 'channel2':int} 238 | 239 | def inverse(self): 240 | return Swap(channel1=self.channel1, channel2=self.channel2) 241 | 242 | def __matrix__(self): 243 | return np.array( 244 | [[1,0,0,0], 245 | [0,0,1,0], 246 | [0,1,0,0], 247 | [0,0,0,1]]) 248 | 249 | class XX(TwoQubitGate): 250 | representation = 'XX({channel1})({channel2})({angle})' 251 | parameters = {'channel1': int, 'channel2': int, 'angle': float} 252 | 253 | def __matrix__(self): 254 | return np.array( 255 | [[cos(self.angle), 0, 0, -1j*sin(self.angle)], 256 | [0, cos(self.angle), -1j*sin(self.angle), 0], 257 | [0, -1j*sin(self.angle), cos(self.angle), 0], 258 | [-1j*sin(self.angle), 0, 0, cos(self.angle)]]) 259 | -------------------------------------------------------------------------------- /UNSTABLE/CircuitParser/setup.py: -------------------------------------------------------------------------------- 1 | # Copyright 2019 UniversalQCompiler (https://github.com/Q-Compiler/UniversalQCompiler) 2 | # Licensed under the Apache License, Version 2.0 (the "License"); 3 | # you may not use this file except in compliance with the License. 4 | # You may obtain a copy of the License at 5 | # http://www.apache.org/licenses/LICENSE-2.0 6 | # Unless required by applicable law or agreed to in writing, software 7 | # distributed under the License is distributed on an "AS IS" BASIS, 8 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 9 | # See the License for the specific language governing permissions and 10 | # limitations under the License. 11 | 12 | from setuptools import setup 13 | 14 | setup(name='CircuitParser', 15 | version='0.1', 16 | packages=['CircuitParser'], 17 | install_requires = ['numpy', 'projectq'] 18 | ) 19 | -------------------------------------------------------------------------------- /UNSTABLE/MathematicaLink/mlinkmodule.c: -------------------------------------------------------------------------------- 1 | # Copyright 2019 UniversalQCompiler (https://github.com/Q-Compiler/UniversalQCompiler) 2 | # Licensed under the Apache License, Version 2.0 (the "License"); 3 | # you may not use this file except in compliance with the License. 4 | # You may obtain a copy of the License at 5 | # http://www.apache.org/licenses/LICENSE-2.0 6 | # Unless required by applicable law or agreed to in writing, software 7 | # distributed under the License is distributed on an "AS IS" BASIS, 8 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 9 | # See the License for the specific language governing permissions and 10 | # limitations under the License. 11 | 12 | #include 13 | #include "wstp.h" 14 | 15 | // package MathematicaLink 16 | 17 | // global variables 18 | static WSENV mlink_env; 19 | static WSLINK mlink_link; 20 | 21 | // helper function to initialize mathematica connection 22 | static int initialize(void) { 23 | int errn; 24 | 25 | printf("Initializing... "); 26 | if ((mlink_env = WSInitialize(0)) 27 | == NULL) { 28 | printf("failed\n"); 29 | // PyErr_SetString() 30 | return 1; 31 | } 32 | printf("OK\n"); 33 | printf("Opening link... "); 34 | 35 | if ((mlink_link = WSOpenString(mlink_env, "-linklaunch -linkname math", &errn)) 36 | == NULL) { 37 | // PyErr_SetString() 38 | printf("failed\n"); 39 | return 1; 40 | } 41 | printf("OK\n"); 42 | return 0; 43 | } 44 | 45 | // helper function to import mathematica packages 46 | static int import(const char* str) { 47 | WSPutFunction(mlink_link, "EvaluatePacket", 1); 48 | WSPutFunction(mlink_link, "Import", 1); 49 | WSPutString(mlink_link, str); 50 | WSEndPacket(mlink_link); 51 | 52 | int pkt; 53 | while ((pkt = WSNextPacket(mlink_link))) { 54 | switch (pkt) { 55 | case MESSAGEPKT: 56 | printf("Got a warning!\n"); 57 | WSNewPacket(mlink_link); 58 | return 1; 59 | case RETURNPKT: 60 | printf("Got answer\n"); 61 | WSNewPacket(mlink_link); 62 | return 0; 63 | default: 64 | printf("Unknown packet %d\n", pkt); 65 | WSNewPacket(mlink_link); 66 | } 67 | } 68 | // dummy 69 | return -1; 70 | } 71 | 72 | // function accessed from python 73 | static PyObject * 74 | mlink_import_package(PyObject * self, PyObject *args) 75 | { 76 | // unpack argument (string!) 77 | const char * filepath; 78 | if (!PyArg_ParseTuple(args, "s", &filepath)) 79 | return NULL; 80 | 81 | // import mathematica package 82 | if (import(filepath) == 1) { 83 | printf("import failed\n"); 84 | return NULL; 85 | } 86 | Py_INCREF(Py_None); 87 | return Py_None; 88 | } 89 | 90 | static PyObject * 91 | mlink_evaluate(PyObject * self, PyObject * args) 92 | { 93 | // unpack argument (string!) 94 | const char * str; 95 | if (!PyArg_ParseTuple(args, "s", &str)) 96 | return NULL; 97 | 98 | // Evaluate argument 99 | WSPutFunction(mlink_link, "EvaluatePacket", 1); 100 | WSPutFunction(mlink_link, "ToString", 2); 101 | WSPutFunction(mlink_link, "ToExpression", 1); 102 | WSPutFunction(mlink_link, "N", 1); 103 | WSPutString(mlink_link, str); 104 | WSPutFunction(mlink_link, "ToExpression", 1); 105 | WSPutString(mlink_link, "InputForm"); 106 | WSEndPacket(mlink_link); 107 | 108 | int pkt; 109 | while ((pkt = (WSNextPacket(mlink_link) != RETURNPKT))) { 110 | WSNewPacket(mlink_link); 111 | } 112 | const char * ans; 113 | WSGetString(mlink_link, &ans); 114 | WSNewPacket(mlink_link); 115 | 116 | return PyUnicode_FromString(ans); 117 | } 118 | 119 | static PyObject * 120 | mlink_open(PyObject * self, PyObject * args) 121 | { 122 | // initialize connection to mathematica 123 | if (initialize() == 1) return NULL; 124 | 125 | printf("Activating... "); 126 | WSActivate(mlink_link); 127 | printf("OK\n"); 128 | 129 | Py_INCREF(Py_None); 130 | return Py_None; 131 | } 132 | 133 | static PyObject * 134 | mlink_close(PyObject * self, PyObject * args) 135 | { 136 | // closing 137 | WSClose(mlink_link); 138 | Py_INCREF(Py_None); 139 | return Py_None; 140 | } 141 | 142 | /*static PyObject * 143 | mlink_atest(PyObject * self, PyObject * args) {*/ 144 | 145 | 146 | // necessary Python stuff, irrelevant feature-wise 147 | // details can be found at https://docs.python.org/3.6/extending/extending.html 148 | 149 | // method table = functions to export 150 | static PyMethodDef mlink_Methods[] = { 151 | {"import_package", mlink_import_package, METH_VARARGS, "Import Mathematica packages"}, 152 | {"eval", mlink_evaluate, METH_VARARGS, "Evaluate mathematica expression"}, 153 | {"open", mlink_open, METH_VARARGS, "Open Mathematica link"}, 154 | {"close", mlink_close, METH_VARARGS, "Close Mathematica link"}, 155 | {NULL, NULL, 0, NULL} 156 | }; 157 | 158 | // module definition 159 | static struct PyModuleDef mlinkmodule = { 160 | PyModuleDef_HEAD_INIT, 161 | "MathematicaLink", 162 | NULL, 163 | -1, 164 | mlink_Methods 165 | }; 166 | 167 | // initialisation function (only non-static) 168 | PyMODINIT_FUNC PyInit_MathematicaLink(void) { 169 | 170 | return PyModule_Create(&mlinkmodule); 171 | } 172 | -------------------------------------------------------------------------------- /UNSTABLE/MathematicaLink/setup.py: -------------------------------------------------------------------------------- 1 | # Copyright 2019 UniversalQCompiler (https://github.com/Q-Compiler/UniversalQCompiler) 2 | # Licensed under the Apache License, Version 2.0 (the "License"); 3 | # you may not use this file except in compliance with the License. 4 | # You may obtain a copy of the License at 5 | # http://www.apache.org/licenses/LICENSE-2.0 6 | # Unless required by applicable law or agreed to in writing, software 7 | # distributed under the License is distributed on an "AS IS" BASIS, 8 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 9 | # See the License for the specific language governing permissions and 10 | # limitations under the License. 11 | 12 | from distutils.core import setup, Extension 13 | 14 | # change these 15 | sys = 'Linux-x86-64' 16 | arch_bit = '64' # replace with 32 if you have a 32bit architecture 17 | version = '11.0' 18 | 19 | # this should be working for you 20 | mathematica_folder = '/usr/local/Wolfram/Mathematica/' + version \ 21 | + '/SystemFiles/Links/WSTP/DeveloperKit/' + sys \ 22 | + '/CompilerAdditions' 23 | 24 | module1 = Extension('MathematicaLink', 25 | include_dirs = [mathematica_folder], 26 | library_dirs = [mathematica_folder], 27 | libraries = [ 28 | 'WSTP' + arch_bit + 'i4', 29 | 'm', 'pthread', 'rt', 'stdc++', 'dl', 'uuid' 30 | ], 31 | sources = ['mlinkmodule.c']) 32 | 33 | setup (name = 'MathematicaLink', 34 | version = '1.0', 35 | description = 'This is a package to call Mathematica functions', 36 | ext_modules = [module1]) 37 | -------------------------------------------------------------------------------- /UNSTABLE/QSimplify/QSimplify/Pythematica.py: -------------------------------------------------------------------------------- 1 | # Copyright 2019 UniversalQCompiler (https://github.com/Q-Compiler/UniversalQCompiler) 2 | # Licensed under the Apache License, Version 2.0 (the "License"); 3 | # you may not use this file except in compliance with the License. 4 | # You may obtain a copy of the License at 5 | # http://www.apache.org/licenses/LICENSE-2.0 6 | # Unless required by applicable law or agreed to in writing, software 7 | # distributed under the License is distributed on an "AS IS" BASIS, 8 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 9 | # See the License for the specific language governing permissions and 10 | # limitations under the License. 11 | 12 | from MathematicaLink import open, close, eval, import_package 13 | from CircuitParser import Gates 14 | from CircuitParser.CircuitParser import mathematica_to_python 15 | 16 | from os.path import join, isfile 17 | from os import getcwd 18 | from numpy import ndarray 19 | 20 | def fulldecomp(mat): 21 | # FIX HERE !!!! only take the numbers and dont parse the gates 22 | 23 | def mathematica_setup(): 24 | path_to_package = join(getcwd(), 'QDecomposition/Decompositions.m') 25 | if not isfile(path_to_package): 26 | raise FileNotFoundError 27 | 28 | # connect to Mathematica 29 | open() 30 | 31 | # import Decompositions.m 32 | import_package(path_to_package) 33 | 34 | try: 35 | mathematica_setup() 36 | gates = mathematica_to_python(query('QSD', mat)) 37 | finally: 38 | close() 39 | print('Connection closed') 40 | return gates 41 | 42 | def query(func, *args, suffix=''): 43 | """ 44 | builds a string from list-type arguments to send to Mathematica, 45 | which will interpret it as an expression. 46 | 47 | Returns the result from Mathematica, formatted as list 48 | """ 49 | command = func + '[' 50 | 51 | # `first` serves to know when to add commas in the expression 52 | first = True 53 | for x in args: 54 | if not first: command += ',' 55 | if type(x) is ndarray: x = x.tolist() 56 | command += array_to_string(x) 57 | first = False 58 | command += ']' 59 | command += suffix 60 | cmd = eval(command) 61 | print(cmd) 62 | return mathematica_to_python(cmd) 63 | 64 | def array_to_string(xs): 65 | s = str(xs) 66 | s = s.replace('[', '{') 67 | s = s.replace(']', '}') 68 | 69 | s = s.replace('j', '*I') 70 | s = s.replace('e', '*^') 71 | return s 72 | -------------------------------------------------------------------------------- /UNSTABLE/QSimplify/setup.py: -------------------------------------------------------------------------------- 1 | # Copyright 2019 UniversalQCompiler (https://github.com/Q-Compiler/UniversalQCompiler) 2 | # Licensed under the Apache License, Version 2.0 (the "License"); 3 | # you may not use this file except in compliance with the License. 4 | # You may obtain a copy of the License at 5 | # http://www.apache.org/licenses/LICENSE-2.0 6 | # Unless required by applicable law or agreed to in writing, software 7 | # distributed under the License is distributed on an "AS IS" BASIS, 8 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 9 | # See the License for the specific language governing permissions and 10 | # limitations under the License. 11 | 12 | from setuptools import setup 13 | 14 | setup(name='QSimplify', 15 | version='0.1', 16 | packages=['QSimplify'], 17 | install_requires = ['numpy'] 18 | ) 19 | -------------------------------------------------------------------------------- /Unit_tests.m: -------------------------------------------------------------------------------- 1 | (* ::Package:: *) 2 | 3 | (* 4 | Copyright 2019 UniversalQCompiler (https://github.com/Q-Compiler/UniversalQCompiler) 5 | Licensed under the Apache License, Version 2.0 (the "License"); 6 | you may not use this file except in compliance with the License. 7 | You may obtain a copy of the License at 8 | http://www.apache.org/licenses/LICENSE-2.0 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 | 16 | (*Switch off precision warnings*) 17 | Off[N::meprec] 18 | Off[Floor::meprec] 19 | Off[Eigensystem::eivec0] 20 | (*Helper methods for tests for tests*) 21 | isZero[x_]:=Chop[x]==0; 22 | isZeroMatrix[mat_]:=Tr[Abs[Flatten[Chop[mat]]]]==0; 23 | isDiagonal[m_]:=Norm[Chop[DiagonalMatrix[Diagonal[m]]-m]]==0; 24 | isIdentity[m_]:=Norm[Chop[m-IdentityMatrix[Length[m]]]]==0; 25 | isIdentityUpToPhase[m_]:=If[Chop[FullSimplify[Norm[m[[1,1]]]]]==0,False, 26 | If[Chop[FullSimplify[Norm[m[[1,1]]]-1]]==0, 27 | Chop[FullSimplify[Norm[m/(m[[1,1]])-IdentityMatrix[Length[m]]]]]==0, 28 | False 29 | ] 30 | ]; 31 | IsEqualUptoPhaseForUnitaries[a_,b_]:=Module[{}, 32 | If[Dimensions[a]==Dimensions[b], ,Return[False]]; 33 | Return[isIdentityUpToPhase[a . ConjugateTranspose[b]]] 34 | ] 35 | (*Create a random n\[Times]m permutation matrix*) 36 | randPermutMat[m_,n_]:=Module[{perm},( 37 | perm=IdentityMatrix[n][[All,RandomSample[Range[m]]]]; 38 | perm=perm[[;;,1;;m]]; 39 | perm 40 | )] 41 | (*Input dimension instead of the number of qubits*) 42 | CreateIsometryFromListDim[st_,M_]:=CreateOperationFromGateList[st,Log2[M]] 43 | NCreateIsometryFromListDim[st_,M_]:=NCreateOperationFromGateList[st,Log2[M]] 44 | (*Multiply the gates in the list representation st to get the matrix representaiton of the operator represented by st. 45 | Note that n denotes the total number of qubits. 46 | *) 47 | MultiplyGates[st_,n_]:=CreateOperationFromGateList[st,n]; 48 | (*Numerically multiply the gates in the list representation st to get the matrix 49 | representaiton of the operator represented by st. New version is faster than previous 50 | *) 51 | NMultiplyGates[st_,n_]:=NCreateOperationFromGateList[st,n] 52 | 53 | (*Some functions for random numbers and matrices. 54 | RR\[Rule]Random Real Number; 55 | RC\[Rule]Random Complex Number; 56 | RG[n]\[Rule]Random Complex Matrix of size n x n; 57 | RU[n]\[Rule]Random Unitary Matrix of size n x n; 58 | *) 59 | RR:=RandomReal[NormalDistribution[0,1]]; 60 | RC:=RR+I*RR; 61 | RG[n_]:=Table[RC,{n},{n}]; 62 | RU[n_]:=Orthogonalize[RG[n]]; 63 | 64 | 65 | (*Helpers for checking mathematical decompositions*) 66 | 67 | 68 | checkIsoToUnitary[iso_]:=Module[{u},( 69 | u=IsoToUnitary[iso]; 70 | isIdentity[u . ConjugateTranspose[u]]&&isZero[Norm[iso-u[[All,1;;Dimensions[iso][[2]]]]]] 71 | )] 72 | 73 | 74 | (*Tests for single methods for mathematical decompositions*) 75 | 76 | 77 | testAppendColums:=Module[{},( 78 | checkIsoToUnitary[PickRandomIsometry[2,4]]&& 79 | checkIsoToUnitary[randPermutMat[2,4]] 80 | )] 81 | 82 | 83 | (*Unit tests for some basic methods*) 84 | 85 | 86 | (*Helpers for checking basic methods*) 87 | 88 | 89 | checkSimplifyGateLists[st_]:=Module[{u,stNew},( 90 | stNew=SimplifyGateList[st]; 91 | isIdentityUpToPhase[ConjugateTranspose[CreateOperationFromGateList[st]] . CreateOperationFromGateList[stNew]] 92 | )] 93 | 94 | 95 | checkRzAngle[angle_]:=isIdentityUpToPhase[RzM[RzAngle[RzM[angle,1]],1] . ConjugateTranspose[RzM[angle,1]]] 96 | 97 | 98 | checkRxAngle[angle_]:=isIdentityUpToPhase[RxM[RxAngle[RxM[angle,1]],1] . ConjugateTranspose[RxM[angle,1]]] 99 | 100 | 101 | checkRyAngle[angle_]:=isIdentityUpToPhase[RyM[RyAngle[RyM[angle,1]],1] . ConjugateTranspose[RyM[angle,1]]] 102 | 103 | 104 | (*Tests for checking basic methods*) 105 | 106 | 107 | testSimplifyGateLists:=Module[{},( 108 | If[ 109 | checkSimplifyGateLists[DecIsometry[PickRandomIsometry[2,4]]]&& 110 | checkSimplifyGateLists[ColumnByColumnDec[N[randPermutMat[4,16]]]], 111 | True 112 | , 113 | Print["Error in SimplifyGateLists"]; 114 | ] 115 | )] 116 | 117 | 118 | testRzAngle:=Module[{},( 119 | If[ 120 | checkRzAngle[0]&&checkRzAngle[0.]&&checkRzAngle[Pi/2]&&checkRzAngle[Pi/2.]&& 121 | checkRzAngle[3Pi]&&checkRzAngle[3.Pi]&&checkRzAngle[0.456]&&checkRzAngle[4] 122 | , 123 | True 124 | , 125 | Print["Error in RzAngle"]; 126 | ] 127 | )] 128 | 129 | 130 | testRxAngle:=Module[{},( 131 | If[ 132 | checkRxAngle[0]&&checkRxAngle[0.]&&checkRxAngle[Pi/2]&&checkRxAngle[Pi/2.]&& 133 | checkRxAngle[3Pi]&&checkRxAngle[3.Pi]&&checkRxAngle[0.456]&&checkRxAngle[4] 134 | , 135 | True 136 | , 137 | Print["Error in RxAngle"]; 138 | ] 139 | )] 140 | 141 | 142 | testRyAngle:=Module[{},( 143 | If[ 144 | checkRyAngle[0]&&checkRyAngle[0.]&&checkRyAngle[Pi/2]&&checkRyAngle[Pi/2.]&& 145 | checkRyAngle[3Pi]&&checkRyAngle[3.Pi]&&checkRyAngle[0.456]&&checkRyAngle[4] 146 | , 147 | True 148 | , 149 | Print["Error in RyAngle"]; 150 | ] 151 | )] 152 | 153 | 154 | (*All tests for basic methods*) 155 | 156 | 157 | testAllBasicMethods:=Module[{},( If[ 158 | testSimplifyGateLists&& 159 | testRzAngle&& 160 | testRxAngle&& 161 | testRyAngle 162 | ,Print["All tests for the basic methods pass."],, 163 | Print["testAllBasicMethods neither returned True nor False"] 164 | ] 165 | ) 166 | ] 167 | 168 | 169 | (*Tests for (uniformly) multi controlled gates*) 170 | 171 | 172 | (*Unit tests for MCGs*) 173 | 174 | 175 | (*Helpers for checking the Decomposition of MCGs*) 176 | 177 | 178 | (*Note: the matrix mat is required to be a unitary for this test.*) 179 | checkApplyMCG[MCG_,mat_]:=Module[{mcg,invertMat,i,gates}, 180 | mcg=CreateMCG[MCG[[1]],Join[MCG[[2]],MCG[[3]]],MCG[[4]],MCG[[5]]]; 181 | (*Account for zero controls*) 182 | gates={}; 183 | For[i=1,i<=MCG[[5]],i++, 184 | If[MemberQ[MCG[[3]],i], 185 | AppendTo[gates,RxM[Pi]], 186 | AppendTo[gates,IdentityMatrix[2]]; 187 | ]; 188 | ]; 189 | invertMat=KroneckerProduct@@gates; 190 | mcg=invertMat . mcg . invertMat; 191 | isIdentityUpToPhase[mcg . mat . ConjugateTranspose[ApplyMCG[MCG,mat]]] 192 | ] 193 | 194 | 195 | checkDecToffoliMultiControlUpToDiagonal[control_,target_,n_]:=Module[{i,st,mat},( 196 | st=DecToffoliMultiControlUpToDiagonal[control,target,n]; 197 | mat=NMultiplyGates[st,n]; 198 | isDiagonal[mat . ConjugateTranspose[CreateMCToffoli[control,target,n]]] 199 | )] 200 | 201 | 202 | checkDecToffoliMultiControl[control_,target_,n_]:=Module[{i,st,mat},( 203 | st=DecToffoliMultiControl[control,target,n]; 204 | mat=NMultiplyGates[st,n]; 205 | isIdentityUpToPhase[mat . ConjugateTranspose[CreateMCToffoli[control,target,n]] 206 | ] 207 | )] 208 | 209 | 210 | checkDecMCSpecialUnitary[su_,control_,target_,n_]:=Module[{i,st,mat},( 211 | st=DecMCSpecialUnitary[su,control,target,n]; 212 | mat=NMultiplyGates[st,n]; 213 | isIdentityUpToPhase[mat . ConjugateTranspose[CreateMCG[su,control,target,n]]] 214 | )] 215 | 216 | 217 | checkDecMCG[u_,control_,target_,n_]:=Module[{i,st,mat},( 218 | st=DecMCG[u,control,target,n]; 219 | mat=NMultiplyGates[st,n]; 220 | isIdentityUpToPhase[mat . ConjugateTranspose[CreateMCG[u,control,target,n]]] 221 | )] 222 | 223 | 224 | checkDecMCSpecialUnitaryUpToDiagonalWithDiagonal[u_,control_,target_,n_]:=Module[{i,st,mat},( 225 | st=DecMCSpecialUnitaryUpToDiagonal[u,control,target,n,ReturnDiagonal->True]; 226 | mat=NMultiplyGates[st,n]; 227 | FullSimplify[isIdentityUpToPhase[mat . ConjugateTranspose[CreateMCG[u,control,target,n]]]] 228 | )] 229 | 230 | 231 | checkDecMCSpecialUnitaryUpToDiagonal[u_,control_,target_,n_]:=Module[{i,st,mat},( 232 | st=DecMCSpecialUnitaryUpToDiagonal[u,control,target,n]; 233 | mat=NMultiplyGates[st,n]; 234 | FullSimplify[isDiagonal[mat . ConjugateTranspose[CreateMCG[u,control,target,n]]]] 235 | )] 236 | 237 | 238 | (*Tests for single methods for MGGs*) 239 | 240 | 241 | testApplyMCG:=Module[{error},( 242 | error=0; 243 | If[Quiet[Check[checkApplyMCG[{RU[2],{1,2,4},{},3,5},RU[2^5]],error=1;False]] && 244 | Quiet[Check[checkApplyMCG[{RU[2],{2},{3,5},1,5},RU[2^5]],error=2;False]],True, 245 | Print["Error in ApplyMCG[] with error message code ",error];False 246 | ] 247 | )] 248 | 249 | 250 | testDecToffoliMultiControlUpToDiagonal:=Module[{error},( 251 | error=0; 252 | If[Quiet[Check[checkDecToffoliMultiControlUpToDiagonal[{1,2,4},3,5],error=1;False]] && 253 | Quiet[Check[checkDecToffoliMultiControlUpToDiagonal[{1,2,4,5},3,7],error=2;False]],True, 254 | Print["Error in DecToffoliMultiControlUpToDiagonal[] with error message code ",error];False 255 | ] 256 | )] 257 | 258 | 259 | testDecToffoliMultiControl:=Module[{error},( 260 | error=0; 261 | If[Quiet[Check[checkDecToffoliMultiControl[{1,3},2,3],error=1;False]] && 262 | Quiet[Check[checkDecToffoliMultiControl[{1,2,5},3,5],error=2;False]]&& 263 | Quiet[Check[checkDecToffoliMultiControl[{1,2,3,4},5,6],error=3;False]],True, 264 | Print["Error in DecToffoliMultiControl[] with error message code ",error];False 265 | ] 266 | )] 267 | 268 | 269 | testDecMCSpecialUnitary:=Module[{M,error},( 270 | error=0; 271 | M=RU[2]; 272 | M=M/Det[M]^(1/2);(*M is a random special unitary matrix*) 273 | If[(*Quiet[Check[checkDecMCSpecialUnitary[N[-IdentityMatrix[2]],{1,2,3,4,5,6,8},7,8],error=1;False]] &&*) 274 | Quiet[Check[checkDecMCSpecialUnitary[M,{1,2,3,4,5,6,7},8,8],error=2;False]],True, 275 | Print["Error in DecMCSpecialUnitary[] with error message code ",error];False 276 | ] 277 | )] 278 | 279 | 280 | testDecMCG:=Module[{M,error},( 281 | error=0; 282 | M=RU[2]; 283 | If[Quiet[Check[checkDecMCG[-IdentityMatrix[2],{1,2,3,4},6,6],error=1;False]] && 284 | Quiet[Check[checkDecMCG[M,{1,2,5},4,5],error=2;False]] && 285 | Quiet[Check[checkDecMCG[M,{3},1,3],error=3;False]]&& 286 | Quiet[Check[checkDecMCG[M,{3,1},2,3],error=4;False]],True, 287 | Print["Error in DecMCG[] with error message code ",error];False 288 | ] 289 | )] 290 | 291 | 292 | (*Here it is enough to test for less than 8 controls, since otherwise we use the method DecMCSpecialUnitary[], 293 | which is already tested above.*) 294 | testDecMCSpecialUnitaryUpToDiagonalWithDiagonal:=Module[{M,error},( 295 | error=0; 296 | M=RU[2]; 297 | M=M/Det[M]^(1/2);(*M is a random special unitary matrix*) 298 | If[Quiet[Check[checkDecMCSpecialUnitaryUpToDiagonalWithDiagonal[N[-IdentityMatrix[2]],{1,2,3,4},5,5],error=1;False]] && 299 | Quiet[Check[checkDecMCSpecialUnitaryUpToDiagonalWithDiagonal[M,{1,2,5},4,5],error=2;False]] && 300 | Quiet[Check[checkDecMCSpecialUnitaryUpToDiagonalWithDiagonal[M,{3},1,3],error=3;False]]&& 301 | Quiet[Check[checkDecMCSpecialUnitaryUpToDiagonalWithDiagonal[M,{},1,3],error=4;False]]&& 302 | Quiet[Check[checkDecMCSpecialUnitaryUpToDiagonalWithDiagonal[M,{3,1},2,3],error=5;False]]&& 303 | (*Also check the method for analytic calculations:*) 304 | Quiet[Check[checkDecMCSpecialUnitaryUpToDiagonalWithDiagonal[IdentityMatrix[2],{1,2,3},4,4],error=6;False]], 305 | True, 306 | Print["Error in DecMCGspecialUnitaryUpToDiagonal[] (with option returning the diagonal gate) with error message code ",error];False 307 | ] 308 | )] 309 | 310 | 311 | (*Here it is enough to test for less than 8 controls, since otherwise we use the method DecMCSpecialUnitary[], 312 | which is already tested above.*) 313 | testDecMCGspecialUnitaryUpToDiagonal:=Module[{M,error},( 314 | error=0; 315 | M=RU[2]; 316 | M=M/Det[M]^(1/2);(*M is a random special unitary matrix*) 317 | If[Quiet[Check[checkDecMCSpecialUnitaryUpToDiagonal[N[-IdentityMatrix[2]],{1,2,3,4},5,5],error=1;False]] && 318 | Quiet[Check[checkDecMCSpecialUnitaryUpToDiagonal[M,{1,2,5},4,5],error=2;False]] && 319 | Quiet[Check[checkDecMCSpecialUnitaryUpToDiagonal[M,{3},1,3],error=3;False]]&& 320 | Quiet[Check[checkDecMCSpecialUnitaryUpToDiagonal[M,{},1,3],error=4;False]]&& 321 | Quiet[Check[checkDecMCSpecialUnitaryUpToDiagonal[M,{3,1},2,3],error=5;False]]&& 322 | (*Also check the method for analytic calculations:*) 323 | Quiet[Check[checkDecMCSpecialUnitaryUpToDiagonal[N[IdentityMatrix[2]],{1,2,3},4,4],error=6;False]], 324 | True, 325 | Print["Error in DecMCGspecialUnitaryUpToDiagonal[] with error message code ",error];False 326 | ] 327 | )] 328 | 329 | 330 | (*Test all Methods for MCG*) 331 | 332 | 333 | testAllMCGMethods:=Module[{},( If[ 334 | testApplyMCG&& 335 | testDecToffoliMultiControlUpToDiagonal&& 336 | testDecToffoliMultiControl&& 337 | testDecMCG && 338 | testDecMCSpecialUnitary&& 339 | testDecMCSpecialUnitaryUpToDiagonalWithDiagonal&& 340 | testDecMCGspecialUnitaryUpToDiagonal 341 | ,Print["All tests for MCGs pass."],, 342 | Print["testAllMCGMethods neither returned True nor False"] 343 | ] 344 | ) 345 | ] 346 | 347 | 348 | (*Unit tests for UCGs*) 349 | 350 | 351 | checkApplyUCG[UCG_,mat_]:=Module[{ucg},( 352 | ucg=CreateUCG[UCG[[1]],UCG[[2]],UCG[[3]],UCG[[4]]]; 353 | Chop[Norm[ucg . mat-ApplyUCG[UCG,mat]]]==0 354 | )] 355 | 356 | 357 | (*Helpers for checking the Decomposition of UCGs*) 358 | 359 | 360 | checkDecUCGUpToDiagonalWithDiagonal[u_,control_,target_,n_]:=Module[{i,st,mat,dia},( 361 | st=DecUCGUpToDiagonal[u,control,target,n,ReturnDiagonal->True]; 362 | dia=st[[-1]]; 363 | mat=ApplyDiag[{dia[[2]],dia[[3]],n},MultiplyGates[Drop[st,-1],n]]; 364 | FullSimplify[isIdentityUpToPhase[mat . ConjugateTranspose[CreateUCG[u,control,target,n]]]] 365 | )] 366 | 367 | 368 | checkDecUCGUpToDiagonal[u_,control_,target_,n_]:=Module[{i,st,mat},( 369 | st=DecUCGUpToDiagonal[u,control,target,n]; 370 | mat=MultiplyGates[st,n]; 371 | FullSimplify[isDiagonal[mat . ConjugateTranspose[CreateUCG[u,control,target,n]]]] 372 | )] 373 | 374 | 375 | (*checks UC Z-rotations (set rotAxis=3) and Y-rotations (set rotAxis=2)*) 376 | 377 | 378 | RotGate[\[Alpha]_,i_]:= 379 | MatrixExp[I \[Alpha]/2 PauliMatrix[i]] 380 | Options[checkDecUCZY] = {DecUCYWithCZ -> False}; 381 | checkDecUCZY[angles_,control_,target_,n_,rotAxis_,OptionsPattern[]]:=Module[{i,st,mat,op,str,m},( 382 | If[rotAxis==3, 383 | st=DecUCZ[angles,control,target,n], 384 | If[OptionValue[DecUCYWithCZ], 385 | st=DecUCY[angles,control,target,n,TwoQubitGate->"Cz"], 386 | st=DecUCY[angles,control,target,n] 387 | ]; 388 | ]; 389 | mat=MultiplyGates[st,n]; 390 | m={}; 391 | For[i=1,i<= Length[angles],i++,AppendTo[m,RotGate[angles[[i]],rotAxis]]]; 392 | isIdentityUpToPhase[mat . ConjugateTranspose[CreateUCG[m,control,target,n]]] 393 | )] 394 | 395 | 396 | (*Tests for methods for UGGs*) 397 | 398 | 399 | testApplyUCG:=Module[{i,m0,m1,m2,m3,error},( 400 | error=0; 401 | (*generate set with unitaries*) 402 | m0={}; 403 | For[i=1,i<= 2^3,i++,AppendTo[m0,IdentityMatrix[2]]]; 404 | m1={}; 405 | For[i=1,i<= 2^4,i++,AppendTo[m1,N[IdentityMatrix[2]]]]; 406 | m2={{{0,1},{1,0}}}; 407 | For[i=1,i<= 2^3-1,i++,AppendTo[m2,RU[2]]]; 408 | If[Quiet[Check[checkApplyUCG[{m0,{1,2,3},4,4},RU[2^4]],error=1;False]] && 409 | Quiet[Check[checkApplyUCG[{m1,{1,2,3,5},4,5},RU[2^5]],error=2;False]] && 410 | Quiet[Check[checkApplyUCG[{m1,{1,2,5},4,5},RU[2^5]],error=3;False]]&& 411 | Quiet[Check[checkApplyUCG[{m1,{1,5,2},4,5},RU[2^5]],error=4;False]]&& 412 | Quiet[Check[checkApplyUCG[{m1,{5,1,2},4,6},RU[2^6]],error=5;False]]&& 413 | Quiet[Check[checkApplyUCG[{m2,{2,3,4},1,6},RU[2^6]],error=6;False]], 414 | True, 415 | Print["Error in ApplyUCG[] with error message code ",error];False 416 | ] 417 | )] 418 | 419 | 420 | testDecUCG:=Module[{i,m0,m1,m2,m3,error},( 421 | error=0; 422 | (*generate set with unitaries*) 423 | m0={}; 424 | For[i=1,i<= 2^2,i++,AppendTo[m0,IdentityMatrix[2]]]; 425 | m1={}; 426 | For[i=1,i<= 2^4,i++,AppendTo[m1,N[IdentityMatrix[2]]]]; 427 | m2={{{0,1},{1,0}}}; 428 | For[i=1,i<= 2^3-1,i++,AppendTo[m2,RU[2]]]; 429 | (* 430 | m3={}; 431 | For[i=1,i<= 2^7,i++,AppendTo[m3,RU[2]]]; 432 | *) 433 | If[Quiet[Check[checkDecUCGUpToDiagonalWithDiagonal[m0,{1,3},2,3],error=1;False]] && 434 | Quiet[Check[checkDecUCGUpToDiagonalWithDiagonal[m1,{1,2,3,5},4,5],error=2;False]] && 435 | Quiet[Check[checkDecUCGUpToDiagonalWithDiagonal[m2,{2,4,3},1,6],error=3;False]] (*&& 436 | Quiet[Check[checkDecUCGUpToDiagonalWithDiagonal[m3,{1,2,3,5,6,7,8},4,8],error=4;False]] 437 | *), 438 | True, 439 | Print["Error in DecUCG[] with error message code ",error];False 440 | ] 441 | )] 442 | 443 | 444 | testDecUCGUpToDiagonal:=Module[{i,m0,m1,m2,m3,error},( 445 | error=0; 446 | (*generate set with unitaries*) 447 | m0={}; 448 | For[i=1,i<= 2^2,i++,AppendTo[m0,IdentityMatrix[2]]]; 449 | m1={}; 450 | For[i=1,i<= 2^4,i++,AppendTo[m1,N[IdentityMatrix[2]]]]; 451 | m2={{{0,1},{1,0}}}; 452 | For[i=1,i<= 2^3-1,i++,AppendTo[m2,RU[2]]]; 453 | (* 454 | m3={}; 455 | For[i=1,i<= 2^7,i++,AppendTo[m3,RU[2]]]; 456 | *) 457 | If[Quiet[Check[checkDecUCGUpToDiagonal[m0,{1,2},3,3],error=1;False]] && 458 | Quiet[Check[checkDecUCGUpToDiagonal[m1,{1,2,3,5},4,5],error=2;False]] && 459 | Quiet[Check[checkDecUCGUpToDiagonal[m2,{4,2,3},1,6],error=3;False]] (*&& 460 | Quiet[Check[checkDecUCGUpToDiagonal[m3,{1,2,3,5,6,7,8},4,8],error=4;False]] 461 | *), 462 | True, 463 | Print["Error in DecUCGUpToDiagonal[] with error message code ",error];False 464 | ] 465 | )] 466 | 467 | 468 | testDecUCZY:=Module[{i,m1,m2,error},( 469 | error=0; 470 | (*generate angles for UCZ*) 471 | m1={}; 472 | For[i=1,i<= 2^4,i++,AppendTo[m1,0]]; 473 | m2={}; 474 | For[i=1,i<= 2^4,i++,AppendTo[m2,RandomReal[]]]; 475 | If[Quiet[Check[checkDecUCZY[m1,{1,3,5,6},2,6,3],error=1;False]] && 476 | Quiet[Check[checkDecUCZY[m1,{1,3,5,6},2,6,2],error=2;False]]&& 477 | Quiet[Check[checkDecUCZY[m1,{6,3,5,1},2,6,2,DecUCYWithCZ -> True],error=3;False]]&& 478 | Quiet[Check[checkDecUCZY[m2,{1,2,4,5},3,6,3],error=4;False]]&& 479 | Quiet[Check[checkDecUCZY[m2,{1,2,4,5},3,6,2],error=5;False]]&& 480 | Quiet[Check[checkDecUCZY[m2,{1,4,2,5},3,6,2,DecUCYWithCZ -> True],error=6;False]], 481 | True, 482 | Print["Error in DecUCGZ[] with error message code ",error];False 483 | ] 484 | )] 485 | 486 | 487 | (*Test UGGs*) 488 | 489 | 490 | testUCGs:=If[testApplyUCG&&testDecUCG &&testDecUCGUpToDiagonal&& testDecUCZY,Print["All tests for UCGs pass."],,Print["testUCGs neither returned True nor False"]] 491 | 492 | 493 | (*Unit tests for diagonal gates*) 494 | 495 | 496 | checkApplyDiag[diagGate_,mat_]:=Module[{diag},( 497 | diag=DiagMat[diagGate[[1]],diagGate[[2]],diagGate[[3]]]; 498 | Chop[Norm[diag . mat-ApplyDiag[diagGate,mat]]]==0 499 | ) 500 | ] 501 | 502 | 503 | (*Helpers for checking decomposition of diagonal gates*) 504 | 505 | 506 | checkDecDiagGate[dia_]:=Module[{st,m},( 507 | st=DecDiagGate[dia]; 508 | m=MultiplyGates[st,Log2[Length[dia]]]; 509 | isIdentityUpToPhase[ConjugateTranspose[DiagonalMatrix[dia]] . m] 510 | ) 511 | ] 512 | 513 | 514 | (*Test for Diagonal gates*) 515 | 516 | 517 | testApplyDiag:=Module[{error},( 518 | error=0; 519 | If[Quiet[Check[checkApplyDiag[{Exp[I RandomReal[{0,2Pi},2^1]],{2},2},RU[2^2]],error=1;False]]&& 520 | Quiet[Check[checkApplyDiag[{Exp[I RandomReal[{0,2Pi},2^2]],{1,3},3},RU[2^3]],error=2;False]]&& 521 | Quiet[Check[checkApplyDiag[{Exp[I RandomReal[{0,2Pi},2^3]],{3,1,4},5},IdentityMatrix[2^5]],error=3;False]] 522 | , 523 | True, 524 | Print["Error in ApplyDiag[] with error message code ",error];False 525 | ] 526 | )] 527 | 528 | 529 | testDecDiagGate:=Module[{error},( 530 | error=0; 531 | If[Quiet[Check[checkDecDiagGate[Exp[I RandomReal[{0,2Pi},2^1]]],error=1;False]]&& 532 | Quiet[Check[checkDecDiagGate[Exp[I RandomReal[{0,2Pi},2^2]]],error=2;False]]&& 533 | Quiet[Check[checkDecDiagGate[Exp[I RandomReal[{0,2Pi},2^3]]],error=3;False]]&& 534 | Quiet[Check[checkDecDiagGate[ConstantArray[1,2^3]],error=4;False]], 535 | True, 536 | Print["Error in DecDiagGate[] with error message code ",error];False 537 | ] 538 | )] 539 | 540 | 541 | (*Test all methods for diagonal gates*) 542 | 543 | 544 | testAllDiagGateMethods:=Module[{},( 545 | If[testDecDiagGate && testApplyDiag,Print["All tests for diagonal gates pass."],, 546 | Print["testAllDiagGateMethods neither returned True nor False"] 547 | ] 548 | ) 549 | ] 550 | 551 | 552 | (*Unit tests for column-by-column decomposition*) 553 | 554 | 555 | (*Helpers for checking the CC-decomposition*) 556 | 557 | 558 | checkColumnByColumnDec[v_]:=Module[{i,st,iso,st2,iso2},( 559 | st=ColumnByColumnDec[v]; 560 | iso=NCreateIsometryFromListDim[st,Dimensions[v][[1]]]; 561 | st2=ColumnByColumnDec[v,FirstColumn->"StatePreparation"]; 562 | iso2=NCreateIsometryFromListDim[st2,Dimensions[v][[1]]]; 563 | isIdentityUpToPhase[ConjugateTranspose[v] . iso]&&isIdentityUpToPhase[ConjugateTranspose[v] . iso2] 564 | ) 565 | ] 566 | 567 | 568 | checkColumnByColumnDecExact[v_]:=Module[{i,st,iso},( 569 | st=ColumnByColumnDec[v,Simp->False]; 570 | iso=NCreateIsometryFromListDim[st,Dimensions[v][[1]]]; 571 | isIdentityUpToPhase[ConjugateTranspose[v] . iso] 572 | ) 573 | ] 574 | 575 | 576 | (*Test methods for CC-decomposition*) 577 | 578 | 579 | testColumnByColumnDec:=Module[{error,v1,v2,v3,vExact1},( 580 | error=0; 581 | v1=CreateOperationFromGateList[{Ancilla[0,1],Rx[1,2],CNOT[1,2],Rz[1,1],Rz[1,1]}]; 582 | v2=CreateOperationFromGateList[NGateList[{Ancilla[0,1],Rx[1,3],CNOT[3,1],Rz[1,3],Rz[1,1],CNOT[2,3],Ry[1,1]}]]; 583 | v3=CreateOperationFromGateList[NGateList[{Ancilla[0,1],Ancilla[0,4],Rx[1,3],CNOT[3,1],Rz[2.5,3],Rz[0.7,1],CNOT[2,3],Ry[0.4,1],Rz[0.4,1],Ry[\[Pi]/2,2],Rz[\[Pi],2],CNOT[2,4]}]]; 584 | vExact1=CreateOperationFromGateList[{Ancilla[0,1],Rx[Pi/4,2],Rx[Pi/4,1],CNOT[1,2],CNOT[3,2],CNOT[2,3],CNOT[3,1]}]; 585 | If[Quiet[Check[checkColumnByColumnDec[PickRandomIsometry[2^2,2^4]],error=1;False]]&& 586 | Quiet[Check[checkColumnByColumnDec[PickRandomIsometry[2^3,2^3]],error=2;False]]&& 587 | Quiet[Check[checkColumnByColumnDec[randPermutMat[2^1,2^2]],error=3;False]]&& 588 | Quiet[Check[checkColumnByColumnDec[N[randPermutMat[2^2,2^3]]],error=4;False]]&& 589 | Quiet[Check[checkColumnByColumnDec[PickRandomIsometry[1,2^2]],error=5;False]]&& 590 | Quiet[Check[checkColumnByColumnDec[v1],error=6;False]]&& 591 | Quiet[Check[checkColumnByColumnDec[v2],error=7;False]]&& 592 | Quiet[Check[checkColumnByColumnDec[v3],error=8;False]]&& 593 | Quiet[Check[checkColumnByColumnDecExact[vExact1],error=9;False]]&& 594 | Quiet[Check[checkColumnByColumnDecExact[randPermutMat[8,8]],error=10;False]] 595 | (*&& 596 | Quiet[Check[checkColumnByColumnDec[PickRandomIsometry[2^3,2^3]],error=6;False]]&& 597 | Quiet[Check[checkColumnByColumnDec[PickRandomIsometry[2^4,2^4]],error=7;False]]*), 598 | True, 599 | Print["Error in ColumnByColumnDec[] with error message code ",error];False 600 | ] 601 | )] 602 | 603 | 604 | (*Test CC-decomposition*) 605 | 606 | 607 | testCCDec:=If[testDecUCGUpToDiagonal&&testColumnByColumnDec,Print["All tests for the column-by-column decomposition pass."],, 608 | Print["ttestCCDec neither returned True nor False"]] 609 | 610 | 611 | (*Unit tests for DecIsometry*) 612 | 613 | 614 | (*Helpers for testing DecIsometry*) 615 | 616 | 617 | checkDecIsometry[v_]:=Module[{i,st,iso,st2,iso2},( 618 | st=DecIsometry[v]; 619 | iso=NCreateIsometryFromListDim[st,Dimensions[v][[1]]]; 620 | isIdentityUpToPhase[ConjugateTranspose[v] . iso] 621 | ) 622 | ] 623 | 624 | 625 | (*Tests for DecIsometry*) 626 | 627 | 628 | testDecIsometry:=Module[{error,v1,v2,v3},( 629 | error=0; 630 | v1=CreateOperationFromGateList[{Ancilla[0,1],Rx[Pi,2],CNOT[1,2],Rz[Pi,1],Rz[Pi,1]}]; 631 | v2=CreateOperationFromGateList[NGateList[{Ancilla[0,1],Rx[1,3],CNOT[3,1],Rz[1,3],Rz[1,1],CNOT[2,3],Ry[1,1]}]]; 632 | v3=CreateOperationFromGateList[NGateList[{Ancilla[0,1],Ancilla[0,4],Rx[1,3],CNOT[3,1],Rz[2.5,3],Rz[0.7,1],CNOT[2,3],Ry[0.4,1],Rz[0.4,1],Ry[\[Pi]/2,2],Rz[\[Pi],2],CNOT[2,4]}]]; 633 | If[Quiet[Check[checkDecIsometry[PickRandomIsometry[2^2,2^4]],error=1;False]]&& 634 | Quiet[Check[checkDecIsometry[PickRandomIsometry[2^1,2^2]],error=2;False]]&& 635 | Quiet[Check[checkDecIsometry[randPermutMat[2^1,2^2]],error=3;False]]&& 636 | Quiet[Check[checkDecIsometry[N[randPermutMat[2^2,2^3]]],error=4;False]]&& 637 | Quiet[Check[checkDecIsometry[PickRandomIsometry[1,2^2]],error=5;False]]&& 638 | Quiet[Check[checkDecIsometry[PickRandomIsometry[2^4,2^4]],error=6;False]]&& 639 | Quiet[Check[checkDecIsometry[v1],error=7;False]]&& 640 | Quiet[Check[checkDecIsometry[v2],error=8;False]]&& 641 | Quiet[Check[checkDecIsometry[v3],error=9;False]] 642 | , 643 | True, 644 | Print["Error in DecIsometry[] with error message code ",error];False 645 | ] 646 | )] 647 | 648 | 649 | testIsometryDecompositions:=If[testDecIsometry,Print["All tests for DecIsometry pass."],, 650 | Print["testIsometryDecompositions neither returned True nor False"]] 651 | 652 | 653 | (*Unit tests for Isometries on a small number of qubits*) 654 | 655 | 656 | (*Helpers for checking the methods for isoemtries on a small number of qubits*) 657 | 658 | 659 | checkStatePrep1Qubit[s_]:=Module[{i,st,iso},( 660 | st=StatePrep1Qubit[s]; 661 | iso=NCreateIsometryFromListDim[st,Dimensions[s][[1]]]; 662 | isIdentityUpToPhase[ConjugateTranspose[s] . iso] 663 | ) 664 | ] 665 | 666 | 667 | checkStatePrep2Qubits[s_]:=Module[{i,st,iso},( 668 | st=StatePrep2Qubits[s]; 669 | iso=NCreateIsometryFromListDim[st,Dimensions[s][[1]]]; 670 | isIdentityUpToPhase[ConjugateTranspose[s] . iso] 671 | ) 672 | ] 673 | 674 | 675 | checkStatePrep3Qubits[s_,class_]:=Module[{i,st,iso},( 676 | st=StatePrep3Qubits[s]; 677 | iso=NCreateIsometryFromListDim[st,Dimensions[s][[1]]]; 678 | isIdentityUpToPhase[ConjugateTranspose[s] . iso] && 679 | (CNOTCount[st]==class) 680 | ) 681 | ] 682 | 683 | 684 | checkDecIso12[v_,analytic_:False]:=Module[{i,st,iso},( 685 | st=DecIso12[v]; 686 | If[analytic, 687 | iso=CreateIsometryFromListDim[st,Dimensions[v][[1]]]; 688 | isIdentityUpToPhase[ConjugateTranspose[v] . N[iso]] 689 | , 690 | iso=NCreateIsometryFromListDim[st,Dimensions[v][[1]]]; 691 | isIdentityUpToPhase[ConjugateTranspose[v] . iso] 692 | ] 693 | ) 694 | ] 695 | 696 | 697 | (*Test methods for isometries on a small number of qubits*) 698 | 699 | 700 | testStatePrep1Qubit:=Module[{error},( 701 | error=0; 702 | If[Quiet[Check[checkStatePrep1Qubit[PickRandomPsi[2]],error=1;False]]&& 703 | Quiet[Check[checkStatePrep1Qubit[FPickRandomPsi[2,4]],error=2;False]]&& 704 | Quiet[Check[checkStatePrep1Qubit[I*{{0},{1}}],error=3;False]]&& 705 | Quiet[Check[checkStatePrep1Qubit[{{1},{0}}],error=4;False]]&& 706 | Quiet[Check[checkStatePrep1Qubit[CreateOperationFromGateList[{Ancilla[0,1],Rz[1/3,1],Rz[1/3,1]}]],error=5;False]] 707 | , 708 | True, 709 | Print["Error in statePrep1Qubit[] with error message code ",error];False 710 | ] 711 | )] 712 | 713 | 714 | testStatePrep2Qubits:=Module[{error,psi},( 715 | error=0; 716 | If[Quiet[Check[checkStatePrep2Qubits[PickRandomPsi[4]],error=1;False]]&& 717 | Quiet[Check[checkStatePrep2Qubits[FPickRandomPsi[4,4]],error=2;False]]&& 718 | (psi = {\!\(\* 719 | TagBox[ 720 | RowBox[{"(", 721 | TagBox[GridBox[{ 722 | { 723 | FractionBox["1", 724 | SqrtBox["2"]]} 725 | }, 726 | GridBoxAlignment->{"Columns" -> {{Center}}, "ColumnsIndexed" -> {}, "Rows" -> {{Baseline}}, "RowsIndexed" -> {}, "Items" -> {}, "ItemsIndexed" -> {}}, 727 | GridBoxSpacings->{"Columns" -> {Offset[0.27999999999999997`], {Offset[0.5599999999999999]}, Offset[0.27999999999999997`]}, "ColumnsIndexed" -> {}, "Rows" -> {Offset[0.2], {Offset[0.4]}, Offset[0.2]}, "RowsIndexed" -> {}, "Items" -> {}, "ItemsIndexed" -> {}}], 728 | Column], ")"}], 729 | Function[BoxForm`e$, MatrixForm[BoxForm`e$]]]\),\!\(\* 730 | TagBox[ 731 | RowBox[{"(", 732 | TagBox[GridBox[{ 733 | {"0"} 734 | }, 735 | GridBoxAlignment->{"Columns" -> {{Center}}, "ColumnsIndexed" -> {}, "Rows" -> {{Baseline}}, "RowsIndexed" -> {}, "Items" -> {}, "ItemsIndexed" -> {}}, 736 | GridBoxSpacings->{"Columns" -> {Offset[0.27999999999999997`], {Offset[0.5599999999999999]}, Offset[0.27999999999999997`]}, "ColumnsIndexed" -> {}, "Rows" -> {Offset[0.2], {Offset[0.4]}, Offset[0.2]}, "RowsIndexed" -> {}, "Items" -> {}, "ItemsIndexed" -> {}}], 737 | Column], ")"}], 738 | Function[BoxForm`e$, MatrixForm[BoxForm`e$]]]\),\!\(\* 739 | TagBox[ 740 | RowBox[{"(", 741 | TagBox[GridBox[{ 742 | {"0"} 743 | }, 744 | GridBoxAlignment->{"Columns" -> {{Center}}, "ColumnsIndexed" -> {}, "Rows" -> {{Baseline}}, "RowsIndexed" -> {}, "Items" -> {}, "ItemsIndexed" -> {}}, 745 | GridBoxSpacings->{"Columns" -> {Offset[0.27999999999999997`], {Offset[0.5599999999999999]}, Offset[0.27999999999999997`]}, "ColumnsIndexed" -> {}, "Rows" -> {Offset[0.2], {Offset[0.4]}, Offset[0.2]}, "RowsIndexed" -> {}, "Items" -> {}, "ItemsIndexed" -> {}}], 746 | Column], ")"}], 747 | Function[BoxForm`e$, MatrixForm[BoxForm`e$]]]\),\!\(\* 748 | TagBox[ 749 | RowBox[{"(", 750 | TagBox[GridBox[{ 751 | { 752 | FractionBox["1", 753 | SqrtBox["2"]]} 754 | }, 755 | GridBoxAlignment->{"Columns" -> {{Center}}, "ColumnsIndexed" -> {}, "Rows" -> {{Baseline}}, "RowsIndexed" -> {}, "Items" -> {}, "ItemsIndexed" -> {}}, 756 | GridBoxSpacings->{"Columns" -> {Offset[0.27999999999999997`], {Offset[0.5599999999999999]}, Offset[0.27999999999999997`]}, "ColumnsIndexed" -> {}, "Rows" -> {Offset[0.2], {Offset[0.4]}, Offset[0.2]}, "RowsIndexed" -> {}, "Items" -> {}, "ItemsIndexed" -> {}}], 757 | Column], ")"}], 758 | Function[BoxForm`e$, MatrixForm[BoxForm`e$]]]\)}; 759 | Quiet[Check[checkStatePrep2Qubits[psi],error=3;False]])&& 760 | Quiet[Check[checkStatePrep2Qubits[CreateOperationFromGateList[{Ancilla[0,1],Ancilla[0,2],Rz[1/3,1],Rz[1/3,1],CNOT[2,1],Rz[1/3,1],Rz[1/3,2]}]],error=4;False]] 761 | , 762 | True, 763 | Print["Error in statePrep2Qubits[] with error message code ",error];False 764 | ] 765 | )] 766 | 767 | 768 | testStatePrep3Qubits := Module[{state,TestBoolean, theta, ru}, 769 | TestBoolean = True; 770 | 771 | (*class 0*) 772 | state = Transpose[{Flatten[KroneckerProduct[PickRandomPsi[2],PickRandomPsi[2], PickRandomPsi[2]]]}]; 773 | If[checkStatePrep3Qubits[state,0], ,Print["3 qubit state preparation failed on a Class 0 state"]; TestBoolean = False]; 774 | 775 | state = NCreateIsometryFromListDim[{Ancilla[0,3],Ancilla[0,2],Ancilla[0,1],Rz[0.8,1],Rx[0.1,2],Rx[0.8,3],Rx[0.4,1],Ry[0.4, 3]}, 8]; 776 | If[checkStatePrep3Qubits[state,0], ,Print["3 qubit state preparation failed on a Class 0 state"]; TestBoolean = False]; 777 | 778 | (*class 1*) 779 | state = Transpose[{Flatten[KroneckerProduct[PickRandomPsi[2],PickRandomPsi[4]]]}]; 780 | If[checkStatePrep3Qubits[state,1], ,Print["3 qubit state preparation failed on a Class 1 state"]; TestBoolean = False]; 781 | 782 | state = NCreateIsometryFromListDim[{Ancilla[0,3],Ancilla[0,2],Ancilla[0,1],Rz[0.8,1],Rx[0.1,2],Rx[0.8,3],Ry[0.8,1],Rz[0.1,2],CNOT[1, 2],Rx[0.4,1],Ry[0.4,3],Ry[0.8,1],Rx[0.1,2],Rx[0.8,3]},8]; 783 | If[checkStatePrep3Qubits[state,1], ,Print["3 qubit state preparation failed on a Class 1 state"]; TestBoolean = False]; 784 | 785 | (*class 2*) 786 | theta = RandomVariate[UniformDistribution[{0, \[Pi]/2}]];ru = RU[2]; state = Transpose[{Cos[theta] *Flatten[KroneckerProduct[ru[[All,1]],PickRandomPsi[2], PickRandomPsi[2]]]+ Sin[theta]*Flatten[KroneckerProduct[ru[[All,2]],PickRandomPsi[2], PickRandomPsi[2]]]}]; 787 | If[checkStatePrep3Qubits[state,2], ,Print["3 qubit state preparation failed on a Class 2 state, with the orthogonal factors on the first qubit"]; TestBoolean = False]; 788 | 789 | theta = RandomVariate[UniformDistribution[{0, \[Pi]/2}]];ru = RU[2]; state = Transpose[{Cos[theta] *Flatten[KroneckerProduct[PickRandomPsi[2],ru[[All,1]], PickRandomPsi[2]]]+ Sin[theta]*Flatten[KroneckerProduct[PickRandomPsi[2],ru[[All,2]], PickRandomPsi[2]]]}]; 790 | If[checkStatePrep3Qubits[state,2], ,Print["3 qubit state preparation failed on a Class 2 state, with the orthogonal factors on the second qubit"]; TestBoolean = False]; 791 | 792 | theta = RandomVariate[UniformDistribution[{0, \[Pi]/2}]];ru = RU[2]; state = Transpose[{Cos[theta] *Flatten[KroneckerProduct[PickRandomPsi[2], PickRandomPsi[2],ru[[All,1]]]]+ Sin[theta]*Flatten[KroneckerProduct[PickRandomPsi[2], PickRandomPsi[2],ru[[All,2]]]]}]; 793 | If[checkStatePrep3Qubits[state,2], ,Print["3 qubit state preparation failed on a Class 2 state, with the orthogonal factors on the third qubit"]; TestBoolean = False]; 794 | 795 | state = NCreateIsometryFromListDim[{Ancilla[0,3],Ancilla[0,2],Ancilla[0,1],Rz[0.8,1],Rx[0.1,2],Rx[0.8,3],Ry[0.8,1],Rz[0.1,2],CNOT[1,2],Rx[0.4,2],Ry[0.4,3],CNOT[2,3],Ry[0.9,3],Ry[0.8,1],Rx[0.1,2],Rx[0.8,3]},8]; 796 | If[checkStatePrep3Qubits[state,2], ,Print["3 qubit state preparation failed on a Class 2 state"]; TestBoolean = False]; 797 | 798 | state = NCreateIsometryFromListDim[{Ancilla[0,3],Ancilla[0,2],Ancilla[0,1],Rz[0.8,1],Rx[0.1,2],Rx[0.8,3],Ry[0.8,1],Rz[0.1,2],CNOT[1, 2],Rx[0.4,1],Ry[0.4,3],CNOT[3,1],Ry[0.8,1],Rx[0.1,2],Rx[0.8,3]},8]; 799 | If[checkStatePrep3Qubits[state,2], ,Print["3 qubit state preparation failed on a Class 2 state"]; TestBoolean = False]; 800 | 801 | (*class 3*) 802 | state = PickRandomPsi[8]; 803 | If[checkStatePrep3Qubits[state,3], ,Print["3 qubit state preparation failed on a random 3 qubit state (assumed to be class 3)"]; TestBoolean = False]; 804 | 805 | TestBoolean 806 | ] 807 | 808 | 809 | testDecIso12:=Module[{error,v1}, 810 | error=0; 811 | v1=CreateOperationFromGateList[{Ancilla[0,1],Rx[1,2],CNOT[1,2],Rz[1,1],Rz[1,1]}]; 812 | If[Quiet[Check[checkDecIso12[PickRandomIsometry[2,4]],error=1;False]]&& 813 | Quiet[Check[checkDecIso12[v1,True],error=2;False]] 814 | , 815 | True, 816 | Print["Error in DecIso12[] with error message code ",error];False 817 | ] 818 | ] 819 | 820 | 821 | (*Test Isometries on a small number of qubits*) 822 | 823 | 824 | testIsoSmall:=If[testStatePrep1Qubit && testStatePrep2Qubits && testStatePrep3Qubits && testDecIso12 ,Print["All tests for the isometries on a small number of qubits pass."],, 825 | Print["testIsoSmall neither returned True nor False"]] 826 | 827 | 828 | (*Unit tests for decomposition of single-qubit unitaries*) 829 | 830 | 831 | (*Unit tests for decomposition of two-qubit unitaries*) 832 | 833 | 834 | (*Helpers for testing ZYZDec, XYXDec, ZXZDec, XZXDec, YXYDec,YZYDec*) 835 | 836 | 837 | checkZYZDec[u_] := Module[{st}, 838 | st = ZYZDec[u,1]; 839 | If[isIdentityUpToPhase[MultiplyGates[st,1] . ConjugateTranspose[u]], 840 | Return[True], 841 | Print["ZYZDec failed on input\n", MatrixFormOp[u]]; 842 | Return[False] 843 | ]; 844 | ] 845 | 846 | 847 | checkXYXDec[u_] := Module[{st}, 848 | st = XYXDec[u,1]; 849 | If[isIdentityUpToPhase[MultiplyGates[st,1] . ConjugateTranspose[u]], 850 | Return[True], 851 | Print["ZYZDec failed on input\n", MatrixFormOp[u]]; 852 | Return[False] 853 | ]; 854 | ] 855 | 856 | 857 | checkZXZDec[u_] := Module[{st}, 858 | st = ZXZDec[u,1]; 859 | If[isIdentityUpToPhase[MultiplyGates[st,1] . ConjugateTranspose[u]], 860 | Return[True], 861 | Print["ZXZDec failed on input\n", MatrixFormOp[u]]; 862 | Return[False] 863 | ]; 864 | ] 865 | 866 | 867 | checkXZXDec[u_] := Module[{st}, 868 | st = XZXDec[u,1]; 869 | If[isIdentityUpToPhase[MultiplyGates[st,1] . ConjugateTranspose[u]], 870 | Return[True], 871 | Print["XZXDec failed on input\n", MatrixFormOp[u]]; 872 | Return[False] 873 | ]; 874 | ] 875 | 876 | 877 | checkYXYDec[u_] := Module[{st}, 878 | st = YXYDec[u,1]; 879 | If[isIdentityUpToPhase[MultiplyGates[st,1] . ConjugateTranspose[u]], 880 | Return[True], 881 | Print["YXYDec failed on input\n", MatrixFormOp[u]]; 882 | Return[False] 883 | ]; 884 | ] 885 | 886 | 887 | checkYZYDec[u_] := Module[{st}, 888 | st = YZYDec[u,1]; 889 | If[isIdentityUpToPhase[MultiplyGates[st,1] . ConjugateTranspose[u]], 890 | Return[True], 891 | Print["YZYDec failed on input\n", MatrixFormOp[u]]; 892 | Return[False] 893 | ]; 894 | ] 895 | 896 | 897 | (*Tests for ZYZDec and XYXDec*) 898 | 899 | 900 | testZYZDec := Module[{isWorking}, 901 | isWorking=checkZYZDec[PickRandomIsometry[2,2]]&&checkZYZDec[{{0,1},{1,0}}]&&checkZYZDec[N[{{0,1},{1,0}}]]&&checkZYZDec[CreateOperationFromGateList[{Rz[Pi/2,1]}]]&& 902 | checkZYZDec[CreateOperationFromGateList[{Ry[Pi/3,1]}]]&&checkZYZDec[CreateOperationFromGateList[{Ry[Pi/3,1]}]]; 903 | If[Not[isWorking], 904 | Print["ZYZDec failed"]]; 905 | isWorking 906 | ]; 907 | 908 | 909 | testXYXDec := Module[{isWorking}, 910 | isWorking=checkXYXDec[PickRandomIsometry[2,2]]&&checkXYXDec[{{0,1},{1,0}}]&&checkXYXDec[N[{{0,1},{1,0}}]] 911 | &&checkXYXDec[CreateOperationFromGateList[{Rz[Pi/3,1]}]]&& 912 | checkXYXDec[CreateOperationFromGateList[{Ry[Pi/3,1]}]]&&checkXYXDec[CreateOperationFromGateList[{Ry[Pi/3,1]}]]; 913 | If[Not[isWorking], 914 | Print["ZYZDec failed"]]; 915 | isWorking 916 | ]; 917 | 918 | 919 | testZXZDec := Module[{isWorking}, 920 | isWorking=checkZXZDec[PickRandomIsometry[2,2]]&&checkZXZDec[{{0,1},{1,0}}]&&checkZXZDec[N[{{0,1},{1,0}}]] 921 | &&checkZXZDec[CreateOperationFromGateList[{Rz[Pi/3,1]}]]&& 922 | checkZXZDec[CreateOperationFromGateList[{Ry[Pi/3,1]}]]&&checkZXZDec[CreateOperationFromGateList[{Ry[Pi/3,1]}]]; 923 | If[Not[isWorking], 924 | Print["ZXZDec failed"]]; 925 | isWorking 926 | ]; 927 | 928 | 929 | testXZXDec := Module[{isWorking}, 930 | isWorking=checkXZXDec[PickRandomIsometry[2,2]]&&checkXZXDec[{{0,1},{1,0}}]&&checkXZXDec[N[{{0,1},{1,0}}]] 931 | &&checkXZXDec[CreateOperationFromGateList[{Rz[Pi/3,1]}]]&& 932 | checkXZXDec[CreateOperationFromGateList[{Ry[Pi/3,1]}]]&&checkXZXDec[CreateOperationFromGateList[{Ry[Pi/3,1]}]]; 933 | If[Not[isWorking], 934 | Print["XZXDec failed"]]; 935 | isWorking 936 | ]; 937 | 938 | 939 | testYXYDec := Module[{isWorking}, 940 | isWorking=checkYXYDec[PickRandomIsometry[2,2]]&&checkYXYDec[{{0,1},{1,0}}]&&checkYXYDec[N[{{0,1},{1,0}}]] 941 | &&checkYXYDec[CreateOperationFromGateList[{Rz[Pi/3,1]}]]&& 942 | checkYXYDec[CreateOperationFromGateList[{Ry[Pi/3,1]}]]&&checkYXYDec[CreateOperationFromGateList[{Ry[Pi/3,1]}]]; 943 | If[Not[isWorking], 944 | Print["XZXDec failed"]]; 945 | isWorking 946 | ]; 947 | 948 | 949 | testYZYDec := Module[{isWorking}, 950 | isWorking=checkYZYDec[PickRandomIsometry[2,2]]&&checkYZYDec[{{0,1},{1,0}}]&&checkYZYDec[N[{{0,1},{1,0}}]] 951 | &&checkYZYDec[CreateOperationFromGateList[{Rz[Pi/3,1]}]]&& 952 | checkYZYDec[CreateOperationFromGateList[{Ry[Pi/3,1]}]]&&checkYZYDec[CreateOperationFromGateList[{Ry[Pi/3,1]}]]; 953 | If[Not[isWorking], 954 | Print["XZXDec failed"]]; 955 | isWorking 956 | ]; 957 | 958 | 959 | (*All tests for single-qubit unitaries*) 960 | 961 | 962 | testDecSingleQubit := Module[{out}, 963 | If[testZYZDec && testXYXDec&& testZXZDec && testXZXDec&& testYXYDec&& testYZYDec 964 | , 965 | Print["All tests for ZYZDec, XYXDec, ZXZDec, XZXDec, YXYDec and YZYDec pass."]; 966 | out=True; 967 | , 968 | Print["Error(s) in ZYZDec, XYXDec, ZXZDec, XZXDec, YXYDec or YZYDec"]; 969 | out=False; 970 | , 971 | Print["testDecSingleQubit neither returned True nor False"] 972 | ]; 973 | out 974 | ] 975 | 976 | 977 | 978 | (*Helpers for testing Dec2Qubit *) 979 | 980 | 981 | checkDec2QubitGateUpToDiagonal[u_] := Module[{diag, st}, 982 | st = DecUnitary2Qubits[u,{1,2}, UpToDiagonal-> True]; 983 | If[isIdentityUpToPhase[NMultiplyGates[st,2] . ConjugateTranspose[u]], 984 | Return[True], 985 | Print["Dec2Qubit with option UpToDiagonal->True failed on input\n", MatrixFormOp[u]]; 986 | Return[False] 987 | ]; 988 | ] 989 | 990 | (*Helpers for testing Dec2Qubit *not* up to a diagonal *) 991 | checkDecUnitary2Qubits[u_,numCNOT_:Null] := Module[{diag, st,out,isCNOTCOUNTCorrect}, 992 | st = DecUnitary2Qubits[u,{1,2}, UpToDiagonal->False]; 993 | isCNOTCOUNTCorrect=If[numCNOT===Null,True,CNOTCount[st]==numCNOT]; 994 | If[isIdentityUpToPhase[NMultiplyGates[st,2] . ConjugateTranspose[u]]&&isCNOTCOUNTCorrect, 995 | out=True, 996 | If[isIdentityUpToPhase[NMultiplyGates[st,2] . ConjugateTranspose[u]],,Print["Dec2Qubit failed on input\n", MatrixForm[u]]]; 997 | If[isCNOTCOUNTCorrect,,Print["Dec2Qubit outputs wrong number of C-NOT gates on input\n", MatrixForm[u]]]; 998 | out=False 999 | ]; 1000 | out 1001 | ] 1002 | 1003 | 1004 | (*Tests for the Method Dec2Qubit *) 1005 | 1006 | 1007 | testDec2QubitGateUpToDiagonalNoCnots := Module[{productGate1,productGate2,testResult1,testResult2}, 1008 | productGate1 = KroneckerProduct[RU[2], RU[2]]; 1009 | productGate2=KroneckerProduct[randPermutMat[2,2],randPermutMat[2,2]]; 1010 | testResult1 = checkDec2QubitGateUpToDiagonal[productGate1]; 1011 | testResult2 = checkDec2QubitGateUpToDiagonal[productGate2]; 1012 | If[Not[testResult1&&testResult2], 1013 | Print["Dec2Qubit with option UpToDiagonal->True failed on an input requiring no cnot gates"]]; 1014 | testResult1&&testResult2 1015 | ]; 1016 | 1017 | 1018 | testDec2QubitGateUpToDiagonalOneCnot := Module[{oneCnotGate1,oneCnotGate2,testResult1,testResult2}, 1019 | oneCnotGate1 = KroneckerProduct[RU[2], RU[2]] . CNOTM[1,2,2] . KroneckerProduct[RU[2], RU[2]]; 1020 | oneCnotGate2= KroneckerProduct[randPermutMat[2,2], randPermutMat[2,2]] . CNOTM[1,2,2] . KroneckerProduct[randPermutMat[2,2], randPermutMat[2,2]]; 1021 | testResult1 = checkDec2QubitGateUpToDiagonal[oneCnotGate1]; 1022 | testResult2= checkDec2QubitGateUpToDiagonal[oneCnotGate2]; 1023 | If[Not[testResult1&&testResult2], 1024 | Print["Dec2Qubit with option UpToDiagonal->True failed on an input requiring one cnot gate"] 1025 | ]; 1026 | testResult1&&testResult2 1027 | ]; 1028 | 1029 | 1030 | testDec2QubitGateUpToDiagonalGeneric := Module[{genericGate,permGate,testResult1,testResult2}, 1031 | genericGate = RU[4]; 1032 | permGate=randPermutMat[4,4]; 1033 | testResult1 = checkDec2QubitGateUpToDiagonal[genericGate]; 1034 | testResult2=checkDec2QubitGateUpToDiagonal[permGate]; 1035 | If[Not[testResult1&&testResult2], 1036 | Print["Dec2Qubit with option UpToDiagonal->True failed on a generic input gate"]; 1037 | ]; 1038 | testResult1&&testResult2 1039 | ]; 1040 | 1041 | 1042 | testDec2QubitNoCnots := Module[{productGate,testResult,v1,v2}, 1043 | productGate = KroneckerProduct[RU[2], RU[2]]; 1044 | v1=CreateOperationFromGateList[NGateList[{Rx[Pi,2],Rz[Pi/4,1],Rz[Pi/3,2],Ry[Pi/6,2]}]]; 1045 | v2=CreateOperationFromGateList[{Rx[Pi,2],Rz[Pi/4,1],Rz[Pi/3,2],Ry[Pi/6,2]}]; 1046 | testResult = checkDecUnitary2Qubits[productGate,0]&&checkDecUnitary2Qubits[v1,0]&&checkDecUnitary2Qubits[v2,0]; 1047 | If[Not[testResult], 1048 | Print["Dec2Qubit failed on an input requiring no cnot gates"]; 1049 | ]; 1050 | testResult 1051 | ]; 1052 | 1053 | 1054 | testDec2QubitOneCnot := Module[{oneCnotGate,testResult,v1,v2}, 1055 | oneCnotGate = KroneckerProduct[RU[2], RU[2]] . CNOTM[1,2,2] . KroneckerProduct[RU[2], RU[2]]; 1056 | v1=CreateOperationFromGateList[NGateList[{Rx[Pi,2],CNOT[1,2],Rz[Pi/4,1],Rz[Pi/3,2],Ry[Pi/6,2]}]]; 1057 | v2=CreateOperationFromGateList[{Ry[Pi/3,1],Ry[Pi,2],CNOT[2,1]}]; 1058 | testResult = checkDecUnitary2Qubits[oneCnotGate,1]&&checkDecUnitary2Qubits[v1,1]&&checkDecUnitary2Qubits[v2,1]; 1059 | If[Not[testResult], 1060 | Print["Dec2Qubit failed on an input requiring one cnot gate"]; 1061 | ]; 1062 | testResult 1063 | ]; 1064 | 1065 | 1066 | testDec2QubitTwoCnot := Module[{oneCnotGate,testResult,v1,v2,v3,v3Prime}, 1067 | v1=CreateOperationFromGateList[NGateList[{Rx[Pi,2],CNOT[1,2],Rz[Pi/4,1],Rz[Pi/3,2],CNOT[2,1],Ry[Pi/6,2]}]]; 1068 | v2=CreateOperationFromGateList[NGateList[{Rx[Pi,2],CNOT[1,2],Rz[Pi/4,1],Rz[Pi/3,2],CNOT[1,2],Ry[Pi/6,2],Rz[Pi/2,2],Ry[Pi/3,1]}]]; 1069 | v3Prime=CreateOperationFromGateList[{Ancilla[0,1],Ry[Pi/3,1],Ry[Pi,2],CNOT[2,1]}]; 1070 | v3=AppendCols[v3Prime]; 1071 | testResult = checkDecUnitary2Qubits[v1,2]&&checkDecUnitary2Qubits[v2,2]&&checkDecUnitary2Qubits[v3,2]; 1072 | If[Not[testResult], 1073 | Print["Dec2Qubit failed on an input requiring two cnot gates"]; 1074 | ]; 1075 | testResult 1076 | ]; 1077 | 1078 | 1079 | testDec2QubitGeneric := Module[{genericGate,testResult,v1,v2}, 1080 | genericGate = RU[4]; 1081 | v1=CreateOperationFromGateList[NGateList[{Rx[Pi,2],CNOT[1,2],Rz[Pi/4,1],Rz[Pi/3,2],CNOT[2,1],Ry[Pi/6,2],Ry[Pi/5,1],CNOT[2,1]}]]; 1082 | v2=CreateOperationFromGateList[{CNOT[1,2],CNOT[2,1],CNOT[1,2]}]; 1083 | testResult = checkDecUnitary2Qubits[genericGate,3]&&checkDecUnitary2Qubits[v1,3]&&checkDecUnitary2Qubits[v2,3]; 1084 | If[Not[testResult], 1085 | Print["Dec2Qubit failed on a generic input gate"]; 1086 | ]; 1087 | testResult 1088 | ]; 1089 | 1090 | 1091 | (*All tests for Dec2Qubit*) 1092 | 1093 | 1094 | testDec2Qubit := Module[{out}, 1095 | If[testDec2QubitGateUpToDiagonalNoCnots && testDec2QubitGateUpToDiagonalOneCnot && testDec2QubitGateUpToDiagonalGeneric && 1096 | testDec2QubitNoCnots && testDec2QubitOneCnot &&testDec2QubitTwoCnot && testDec2QubitGeneric 1097 | , 1098 | Print["All tests for Dec2Qubit pass."]; 1099 | out=True; 1100 | , 1101 | Print["Error(s) in Dec2Qubit"]; 1102 | out=False, 1103 | Print["testDec2Qubit neither returned True nor False"] 1104 | ]; 1105 | out 1106 | ] 1107 | 1108 | 1109 | 1110 | (*Unit tests for the Quantum Shannon Decompostion*) 1111 | 1112 | 1113 | (*Helpers for testing the Quantum Shannon Decompostion*) 1114 | 1115 | 1116 | checkQSD[testUnitary_,simp_:True]:= Module[{n,op, str,st,opV,opVCorrect,stV,stVCorrect}, 1117 | st = QSD[testUnitary,Simp->simp]; 1118 | stV =ConjugateTranspose[testUnitary] . NCreateIsometryFromListDim[st,Dimensions[testUnitary][[1]]]; 1119 | stVCorrect = isIdentityUpToPhase[stV]; 1120 | If[Not[stVCorrect], 1121 | Print["QSD (st) failed on input\n", MatrixForm[testUnitary]]; 1122 | ]; 1123 | Return[stVCorrect]; 1124 | ] 1125 | 1126 | 1127 | (*Tests for Methods for the Quantum Shannon Decomposition*) 1128 | 1129 | 1130 | (*Test QSC*) 1131 | testQSD := Module[{vExact1,n,passedAllTestsSoFar,stV,stVCorrect,opV,opVCorrect,st,m}, 1132 | passedAllTestsSoFar = True; 1133 | For[n=1, n < 4, n++, 1134 | If[Not[checkQSD[RU[2^n]]], 1135 | passedAllTestsSoFar = False; 1136 | Print["QSD failed on ", n, " qubit input"]; 1137 | ]; 1138 | ]; 1139 | (*In the past the 8x8 identity matrix caused problems, so we check that it works*) 1140 | If[Not[checkQSD[N[IdentityMatrix[8]]]], Print["QSD (st) failed on input: N[IdentityMatrix[8]]"]; passedAllTestsSoFar = False;]; 1141 | (*CheckQSD for exact input*) 1142 | vExact1=CreateOperationFromGateList[{Ancilla[0,1],Rx[Pi/4,2],Rx[Pi/2,1],CNOT[1,2],CNOT[3,2],CNOT[2,3],CNOT[3,1]}]; 1143 | If[checkQSD[vExact1,False],,Print["QSD (st) failed on exact input v= ",vExact1]; passedAllTestsSoFar = False;]; 1144 | (*In the past the 8x8 identity matrix caused problems, so we check that it works*) 1145 | If[FullSimplify[Not[checkQSD[IdentityMatrix[8]]]], Print["QSD (st) failed on input: IdentityMatrix[8]"]; passedAllTestsSoFar = False;]; 1146 | (*Tests for isometries*) 1147 | For[n=2, n < 4, n++, 1148 | For[m=1, m False}; 1173 | checkStinespring[chan_,OptionsPattern[]] := 1174 | Module[{u, anc,uc,ancc,i, out = True,ch}, 1175 | {u, anc} = StinespringQubit[chan,TryToCompress->False]; 1176 | For[i = 1, i <= Dimensions[chan][[1]], i++, 1177 | out = And[out, 1178 | isZeroMatrix[KroneckerProduct[BraV[i - 1, 2^anc],IdentityMatrix[ 1179 | Dimensions[chan][[2]]]] . u - chan[[i]]]]]; 1180 | out=And[out,isIdentity[ConjugateTranspose[u] . u]]; 1181 | If[Not[OptionValue[Exact]],ch=MinimizeKrausRank[chan]; 1182 | {uc, ancc} = StinespringQubit[chan]; 1183 | For[i = 1, i <= Dimensions[ch][[1]], i++, 1184 | out = And[out, 1185 | isZeroMatrix[KroneckerProduct[BraV[i - 1, 2^ancc],IdentityMatrix[ 1186 | Dimensions[ch][[2]]]] . uc - ch[[i]]]]];out= 1187 | And[out,isIdentity[ConjugateTranspose[uc] . uc]]];out] 1188 | 1189 | 1190 | (*Test of Stinespring*) 1191 | 1192 | 1193 | (* Note that for a channel from m to n qubits, the number of Kraus 1194 | operators must be at least 2^(m-n) *) 1195 | testStinespring := 1196 | Module[{n, m, p, passedAllTestsSoFar, stV, stVCorrect, opV, 1197 | opVCorrect,chan}, 1198 | passedAllTestsSoFar = True; 1199 | For[m=2,m<6,m++, 1200 | For[n=2,n<6,n++,For[p=Ceiling[2^(m-n)],p<5+Ceiling[2^(m-n)],p++, 1201 | If[Not[checkStinespring[PickRandomChannel[2^m, 2^n, p]]], 1202 | passedAllTestsSoFar = False; 1203 | Print["StinespringQubit failed on a generic channel from ", m, 1204 | " qubits to ", n, " qubits with ", p, " Kraus operators"]]]]]; If[passedAllTestsSoFar, 1205 | Print["All tests for StinespringQubit on generic inputs pass."]]; 1206 | For[p=2,p<6,p++, 1207 | chan=FPickRandomChannel[2,2,p,2];If[Not[checkStinespring[chan,Exact->True]], 1208 | passedAllTestsSoFar = False;Print["StinespringQubit failed on an exact 1209 | channel from 1 qubit to 1 qubits with ", p, " Kraus operators"]]]; 1210 | If[passedAllTestsSoFar, 1211 | Print["All tests for StinespringQubit pass."],, 1212 | Print["testStinespring neither returned True nor False"]]] 1213 | 1214 | 1215 | (*Unit tests for POVMs*) 1216 | 1217 | 1218 | (*Helper method for checking POVMs*) 1219 | 1220 | 1221 | checkPOVM[POVM_] := 1222 | Module[{r,i,u,anc, out = True}, {u, anc} = POVMToIsometry[POVM]; 1223 | r=PickRandomRho[Dimensions[POVM][[2]]]; 1224 | For[i = 1, i <= Dimensions[POVM][[1]], i++, 1225 | out = And[out, 1226 | isZeroMatrix[MatrixPower[KroneckerProduct[BraV[i - 1, 2^anc],IdentityMatrix[ 1227 | Dimensions[POVM][[2]]]] . u ,2]- POVM[[i]]]]; 1228 | out=And[out,isZero[Tr[KroneckerProduct[BraV[i - 1, 2^anc],IdentityMatrix[ 1229 | Dimensions[POVM][[2]]]] . u . r . CT[u] . KroneckerProduct[KetV[i - 1, 2^anc],IdentityMatrix[ 1230 | Dimensions[POVM][[2]]]]]-Tr[POVM[[i]] . r]]]]; 1231 | And[out,isIdentity[ConjugateTranspose[u] . u]]] 1232 | 1233 | 1234 | (*Test POVMs*) 1235 | 1236 | 1237 | testPOVM := 1238 | Module[{n, m, p, passedAllTestsSoFar, stV, stVCorrect, opV, 1239 | opVCorrect,chan}, 1240 | passedAllTestsSoFar = True; 1241 | For[m=2,m<6,m++, 1242 | For[p=Ceiling[2^(m-n)],p<5+Ceiling[2^(m-n)],p++, 1243 | If[Not[checkPOVM[PickRandomPOVM[2^m, p]]], 1244 | passedAllTestsSoFar = False; 1245 | Print["POVMToIsometry failed on a generic POVM on ", m, 1246 | " qubits with ", p, " elements"]]]]; If[passedAllTestsSoFar, 1247 | Print["All tests for POVMToIsometry on generic inputs pass."]]; 1248 | For[p=2,p<10,p++, 1249 | If[Not[checkPOVM[Table[IdentityMatrix[4]/p,{i,1,p}]]], 1250 | passedAllTestsSoFar = False; 1251 | Print["POVMToIsometry failed on an exact POVM with ", p, " elements"]]]; 1252 | If[passedAllTestsSoFar, 1253 | Print["All tests for POVMToIsometry pass."],, 1254 | Print["testPOVM neither returned True nor False"]]] 1255 | 1256 | 1257 | (*Unit tests for Knill decomposition*) 1258 | 1259 | 1260 | (*Check Methods used in Knill's decomposition*) 1261 | 1262 | 1263 | CheckXToY[x_,y_]:=Module[{q}, 1264 | q = XToYTransform[x,y]; 1265 | isIdentity[N[CT[q] . q]]&&isZeroMatrix[N[q . x-y]] 1266 | ] 1267 | 1268 | 1269 | CheckIsoToUnitarySpecial[v_]:=Module[{u,n,m}, 1270 | {n,m}=Dimensions[v]; 1271 | u = IsoToUnitarySpecial[v]; 1272 | Return[isIdentity[CT[u] . u]&&isZeroMatrix[u[[All,1;;m]]-v]&&(Count[Chop[Eigenvalues[u]-1],0]>=n-m)] 1273 | ] 1274 | 1275 | 1276 | CheckUED[u_]:=Module[{angles,anglemats,vecs,length,q,p,n,i}, 1277 | (*check vector output*) 1278 | n = Dimensions[u][[1]]; 1279 | {angles,vecs} = UnitaryEigenvalueDecomp[u]; 1280 | length = Dimensions[angles][[1]]; 1281 | p= IdentityMatrix[n]; 1282 | For[i=1,i<=length,i++,p=p . IsoToUnitary[vecs[[i]]] . ( 1283 | SparseArray[{1,1}->(Exp[I*angles[[i]]]-1),{n,n}]+IdentityMatrix[n] 1284 | ) . CT[IsoToUnitary[vecs[[i]]]]]; 1285 | Return[isZeroMatrix[p-u]] 1286 | ] 1287 | 1288 | 1289 | Options[checkKnillDec] = {UseDec -> "QSD"}; 1290 | checkKnillDec[v_,OptionsPattern[]]:=Module[{i,st,iso},( 1291 | st=KnillDec[v,UseDec->OptionValue[UseDec]]; 1292 | iso=NCreateIsometryFromListDim[st,Dimensions[v][[1]]]; 1293 | isIdentityUpToPhase[N[ConjugateTranspose[v] . iso]] 1294 | ) 1295 | ] 1296 | 1297 | 1298 | (*Test Methods used in Knill's decomposition*) 1299 | 1300 | 1301 | TestXToY := Module[{x,y,q,error,u}, 1302 | (*Define fractional x and y:*) 1303 | x = {\!\(\* 1304 | TagBox[ 1305 | RowBox[{"(", 1306 | TagBox[GridBox[{ 1307 | { 1308 | RowBox[{ 1309 | RowBox[{"2", " ", 1310 | SqrtBox[ 1311 | FractionBox["2", "2821"]]}], "+", 1312 | SqrtBox[ 1313 | FractionBox["2", "13"]]}]}, 1314 | { 1315 | RowBox[{ 1316 | RowBox[{ 1317 | RowBox[{"-", "2"}], " ", 1318 | SqrtBox[ 1319 | FractionBox["2", "2821"]]}], "+", 1320 | SqrtBox[ 1321 | FractionBox["2", "13"]]}]} 1322 | }, 1323 | GridBoxAlignment->{"Columns" -> {{Center}}, "ColumnsIndexed" -> {}, "Rows" -> {{Baseline}}, "RowsIndexed" -> {}, "Items" -> {}, "ItemsIndexed" -> {}}, 1324 | GridBoxSpacings->{"Columns" -> {Offset[0.27999999999999997`], {Offset[0.5599999999999999]}, Offset[0.27999999999999997`]}, "ColumnsIndexed" -> {}, "Rows" -> {Offset[0.2], {Offset[0.4]}, Offset[0.2]}, "RowsIndexed" -> {}, "Items" -> {}, "ItemsIndexed" -> {}}], 1325 | Column], ")"}], 1326 | Function[BoxForm`e$, MatrixForm[BoxForm`e$]]]\),\!\(\* 1327 | TagBox[ 1328 | RowBox[{"(", 1329 | TagBox[GridBox[{ 1330 | { 1331 | RowBox[{ 1332 | RowBox[{"2", " ", 1333 | SqrtBox[ 1334 | FractionBox["2", "2821"]]}], "+", 1335 | SqrtBox[ 1336 | FractionBox["2", "13"]]}]}, 1337 | { 1338 | RowBox[{ 1339 | RowBox[{ 1340 | RowBox[{"-", "2"}], " ", 1341 | SqrtBox[ 1342 | FractionBox["2", "2821"]]}], "+", 1343 | SqrtBox[ 1344 | FractionBox["2", "13"]]}]} 1345 | }, 1346 | GridBoxAlignment->{"Columns" -> {{Center}}, "ColumnsIndexed" -> {}, "Rows" -> {{Baseline}}, "RowsIndexed" -> {}, "Items" -> {}, "ItemsIndexed" -> {}}, 1347 | GridBoxSpacings->{"Columns" -> {Offset[0.27999999999999997`], {Offset[0.5599999999999999]}, Offset[0.27999999999999997`]}, "ColumnsIndexed" -> {}, "Rows" -> {Offset[0.2], {Offset[0.4]}, Offset[0.2]}, "RowsIndexed" -> {}, "Items" -> {}, "ItemsIndexed" -> {}}], 1348 | Column], ")"}], 1349 | Function[BoxForm`e$, MatrixForm[BoxForm`e$]]]\),\!\(\* 1350 | TagBox[ 1351 | RowBox[{"(", 1352 | TagBox[GridBox[{ 1353 | { 1354 | RowBox[{ 1355 | RowBox[{ 1356 | RowBox[{"-", "25"}], " ", 1357 | SqrtBox[ 1358 | FractionBox["2", "2821"]]}], "+", 1359 | FractionBox["1", 1360 | SqrtBox["26"]]}]}, 1361 | { 1362 | RowBox[{ 1363 | RowBox[{"25", " ", 1364 | SqrtBox[ 1365 | FractionBox["2", "2821"]]}], "+", 1366 | FractionBox["1", 1367 | SqrtBox["26"]]}]} 1368 | }, 1369 | GridBoxAlignment->{"Columns" -> {{Center}}, "ColumnsIndexed" -> {}, "Rows" -> {{Baseline}}, "RowsIndexed" -> {}, "Items" -> {}, "ItemsIndexed" -> {}}, 1370 | GridBoxSpacings->{"Columns" -> {Offset[0.27999999999999997`], {Offset[0.5599999999999999]}, Offset[0.27999999999999997`]}, "ColumnsIndexed" -> {}, "Rows" -> {Offset[0.2], {Offset[0.4]}, Offset[0.2]}, "RowsIndexed" -> {}, "Items" -> {}, "ItemsIndexed" -> {}}], 1371 | Column], ")"}], 1372 | Function[BoxForm`e$, MatrixForm[BoxForm`e$]]]\),\!\(\* 1373 | TagBox[ 1374 | RowBox[{"(", 1375 | TagBox[GridBox[{ 1376 | { 1377 | RowBox[{ 1378 | SqrtBox[ 1379 | FractionBox["2", "13"]], "+", 1380 | FractionBox["17", 1381 | SqrtBox["5642"]]}]}, 1382 | { 1383 | RowBox[{ 1384 | SqrtBox[ 1385 | FractionBox["2", "13"]], "-", 1386 | FractionBox["17", 1387 | SqrtBox["5642"]]}]} 1388 | }, 1389 | GridBoxAlignment->{"Columns" -> {{Center}}, "ColumnsIndexed" -> {}, "Rows" -> {{Baseline}}, "RowsIndexed" -> {}, "Items" -> {}, "ItemsIndexed" -> {}}, 1390 | GridBoxSpacings->{"Columns" -> {Offset[0.27999999999999997`], {Offset[0.5599999999999999]}, Offset[0.27999999999999997`]}, "ColumnsIndexed" -> {}, "Rows" -> {Offset[0.2], {Offset[0.4]}, Offset[0.2]}, "RowsIndexed" -> {}, "Items" -> {}, "ItemsIndexed" -> {}}], 1391 | Column], ")"}], 1392 | Function[BoxForm`e$, MatrixForm[BoxForm`e$]]]\)}; 1393 | y = {\!\(\* 1394 | TagBox[ 1395 | RowBox[{"(", 1396 | TagBox[GridBox[{ 1397 | { 1398 | RowBox[{ 1399 | RowBox[{"7", " ", 1400 | SqrtBox[ 1401 | FractionBox["5", "598"]]}], "-", 1402 | FractionBox["47", 1403 | SqrtBox["648830"]]}]}, 1404 | { 1405 | RowBox[{ 1406 | RowBox[{"7", " ", 1407 | SqrtBox[ 1408 | FractionBox["5", "598"]]}], "+", 1409 | FractionBox["47", 1410 | SqrtBox["648830"]]}]} 1411 | }, 1412 | GridBoxAlignment->{"Columns" -> {{Center}}, "ColumnsIndexed" -> {}, "Rows" -> {{Baseline}}, "RowsIndexed" -> {}, "Items" -> {}, "ItemsIndexed" -> {}}, 1413 | GridBoxSpacings->{"Columns" -> {Offset[0.27999999999999997`], {Offset[0.5599999999999999]}, Offset[0.27999999999999997`]}, "ColumnsIndexed" -> {}, "Rows" -> {Offset[0.2], {Offset[0.4]}, Offset[0.2]}, "RowsIndexed" -> {}, "Items" -> {}, "ItemsIndexed" -> {}}], 1414 | Column], ")"}], 1415 | Function[BoxForm`e$, MatrixForm[BoxForm`e$]]]\),\!\(\* 1416 | TagBox[ 1417 | RowBox[{"(", 1418 | TagBox[GridBox[{ 1419 | { 1420 | FractionBox[ 1421 | RowBox[{"4960", "-", 1422 | RowBox[{"647", " ", 1423 | SqrtBox["217"]}]}], 1424 | RowBox[{"31", " ", 1425 | SqrtBox["1019590"]}]]}, 1426 | { 1427 | FractionBox[ 1428 | RowBox[{"4960", "+", 1429 | RowBox[{"647", " ", 1430 | SqrtBox["217"]}]}], 1431 | RowBox[{"31", " ", 1432 | SqrtBox["1019590"]}]]} 1433 | }, 1434 | GridBoxAlignment->{"Columns" -> {{Center}}, "ColumnsIndexed" -> {}, "Rows" -> {{Baseline}}, "RowsIndexed" -> {}, "Items" -> {}, "ItemsIndexed" -> {}}, 1435 | GridBoxSpacings->{"Columns" -> {Offset[0.27999999999999997`], {Offset[0.5599999999999999]}, Offset[0.27999999999999997`]}, "ColumnsIndexed" -> {}, "Rows" -> {Offset[0.2], {Offset[0.4]}, Offset[0.2]}, "RowsIndexed" -> {}, "Items" -> {}, "ItemsIndexed" -> {}}], 1436 | Column], ")"}], 1437 | Function[BoxForm`e$, MatrixForm[BoxForm`e$]]]\),\!\(\* 1438 | TagBox[ 1439 | RowBox[{"(", 1440 | TagBox[GridBox[{ 1441 | { 1442 | FractionBox[ 1443 | RowBox[{"808", "+", 1444 | RowBox[{"131", " ", 1445 | SqrtBox["217"]}]}], 1446 | RowBox[{"217", " ", 1447 | SqrtBox["1430"]}]]}, 1448 | { 1449 | FractionBox[ 1450 | RowBox[{ 1451 | RowBox[{"-", "808"}], "+", 1452 | RowBox[{"131", " ", 1453 | SqrtBox["217"]}]}], 1454 | RowBox[{"217", " ", 1455 | SqrtBox["1430"]}]]} 1456 | }, 1457 | GridBoxAlignment->{"Columns" -> {{Center}}, "ColumnsIndexed" -> {}, "Rows" -> {{Baseline}}, "RowsIndexed" -> {}, "Items" -> {}, "ItemsIndexed" -> {}}, 1458 | GridBoxSpacings->{"Columns" -> {Offset[0.27999999999999997`], {Offset[0.5599999999999999]}, Offset[0.27999999999999997`]}, "ColumnsIndexed" -> {}, "Rows" -> {Offset[0.2], {Offset[0.4]}, Offset[0.2]}, "RowsIndexed" -> {}, "Items" -> {}, "ItemsIndexed" -> {}}], 1459 | Column], ")"}], 1460 | Function[BoxForm`e$, MatrixForm[BoxForm`e$]]]\),\!\(\* 1461 | TagBox[ 1462 | RowBox[{"(", 1463 | TagBox[GridBox[{ 1464 | { 1465 | FractionBox[ 1466 | RowBox[{"3", " ", 1467 | RowBox[{"(", 1468 | RowBox[{"7", "+", 1469 | RowBox[{"3", " ", 1470 | SqrtBox["217"]}]}], ")"}]}], 1471 | RowBox[{"7", " ", 1472 | SqrtBox["910"]}]]}, 1473 | { 1474 | FractionBox[ 1475 | RowBox[{"3", " ", 1476 | RowBox[{"(", 1477 | RowBox[{"7", "-", 1478 | RowBox[{"3", " ", 1479 | SqrtBox["217"]}]}], ")"}]}], 1480 | RowBox[{"7", " ", 1481 | SqrtBox["910"]}]]} 1482 | }, 1483 | GridBoxAlignment->{"Columns" -> {{Center}}, "ColumnsIndexed" -> {}, "Rows" -> {{Baseline}}, "RowsIndexed" -> {}, "Items" -> {}, "ItemsIndexed" -> {}}, 1484 | GridBoxSpacings->{"Columns" -> {Offset[0.27999999999999997`], {Offset[0.5599999999999999]}, Offset[0.27999999999999997`]}, "ColumnsIndexed" -> {}, "Rows" -> {Offset[0.2], {Offset[0.4]}, Offset[0.2]}, "RowsIndexed" -> {}, "Items" -> {}, "ItemsIndexed" -> {}}], 1485 | Column], ")"}], 1486 | Function[BoxForm`e$, MatrixForm[BoxForm`e$]]]\)}; 1487 | If[Quiet[Check[CheckXToY[x,y],error=1;False]]&& 1488 | (x=PickRandomIsometry[16,64];u = PickRandomUnitary[Dimensions[x][[1]]];y=u . x; 1489 | Quiet[Check[CheckXToY[x,y],error=2;False]])&& 1490 | (x=PickRandomIsometry[25,50];u = PickRandomUnitary[Dimensions[x][[1]]];y=u . x; 1491 | Quiet[Check[CheckXToY[x,y],error=3;False]]) 1492 | , 1493 | True, 1494 | Print["Error in XToY with error message code ",error];False 1495 | ] 1496 | ] 1497 | 1498 | 1499 | TestIsoToUnitarySpecial:=Module[{error},( 1500 | error=0; 1501 | If[Quiet[Check[CheckIsoToUnitarySpecial[PickRandomIsometry[16,64]],error=1;False]]&& 1502 | Quiet[Check[CheckIsoToUnitarySpecial[PickRandomIsometry[25,50]],error=1;False]] 1503 | , 1504 | True, 1505 | Print["Error in IsoToUnitarySpecial with error message code ",error];False 1506 | ] 1507 | )] 1508 | 1509 | 1510 | TestUnitaryEigenvalueDecomp:=Module[{error},( 1511 | error=0; 1512 | If[Quiet[Check[CheckUED[IsoToUnitarySpecial[PickRandomIsometry[16,64]]],error=1;False]]&& 1513 | Quiet[Check[CheckUED[IsoToUnitarySpecial[PickRandomIsometry[25,50]]],error=1;False]] 1514 | , 1515 | True, 1516 | Print["Error in UnitaryEigenvalueDecomp with error message code ",error];False 1517 | ] 1518 | )] 1519 | 1520 | 1521 | TestKnillDec1:=Module[{error},( 1522 | error=0; 1523 | If[Quiet[Check[checkKnillDec[PickRandomIsometry[2,2^4]],error=1;False]]&& 1524 | Quiet[Check[checkKnillDec[PickRandomIsometry[1,2^3]],error=2;False]]&& 1525 | Quiet[Check[checkKnillDec[randPermutMat[2^1,2^2]],error=3;False]]&& 1526 | Quiet[Check[checkKnillDec[N[randPermutMat[2^2,2^4]]],error=4;False]]&& 1527 | Quiet[Check[checkKnillDec[PickRandomIsometry[1,2^2]],error=5;False]]&& 1528 | Quiet[Check[checkKnillDec[PickRandomIsometry[2^3,2^3]],error=6;False]], 1529 | True, 1530 | Print["Error in KnillDec[] (using the QSD for decomposing the unitaries) with error message code ",error];False 1531 | ] 1532 | )] 1533 | 1534 | 1535 | TestKnillDec2:=Module[{error,wrongDecomposition},( 1536 | error=0; 1537 | If[Quiet[Check[checkKnillDec[PickRandomIsometry[2,8],UseDec->"KnillDec"],error=1;False]]&& 1538 | Quiet[Check[checkKnillDec[PickRandomIsometry[8,8],UseDec->"KnillDec"],error=2;False]]&& 1539 | Quiet[Check[checkKnillDec[randPermutMat[2^1,2^2],UseDec->"KnillDec"],error=3;False]]&& 1540 | Quiet[Check[checkKnillDec[N[randPermutMat[2^2,2^3]],UseDec->"KnillDec"],error=4;False]]&& 1541 | Quiet[Check[checkKnillDec[PickRandomIsometry[1,2^2],UseDec->"KnillDec"],error=5;False]]&& 1542 | Quiet[Check[checkKnillDec[PickRandomIsometry[2^3,2^3],UseDec->"KnillDec"],error=6;False]], 1543 | True, 1544 | Print["Error in KnillDec[] (using the Knill decomposition for decomposing the unitaries) with error message code ",error];False 1545 | ] 1546 | )] 1547 | 1548 | 1549 | TestKnillDec3:=Module[{error,wrongDecomposition},( 1550 | error=0; 1551 | If[Quiet[Check[checkKnillDec[PickRandomIsometry[2,8],UseDec->"ColumnByColumnDec"],error=1;False]]&& 1552 | Quiet[Check[checkKnillDec[PickRandomIsometry[8,8],UseDec->"ColumnByColumnDec"],error=2;False]]&& 1553 | Quiet[Check[checkKnillDec[randPermutMat[2^1,2^2],UseDec->"ColumnByColumnDec"],error=3;False]]&& 1554 | Quiet[Check[checkKnillDec[N[randPermutMat[2^2,2^3]],UseDec->"ColumnByColumnDec"],error=4;False]]&& 1555 | Quiet[Check[checkKnillDec[PickRandomIsometry[1,2^2],UseDec->"ColumnByColumnDec"],error=5;False]]&& 1556 | Quiet[Check[checkKnillDec[PickRandomIsometry[2^3,2^3],UseDec->"ColumnByColumnDec"],error=6;False]], 1557 | True, 1558 | Print["Error in KnillDec[] (using the ColumnByColumnDec for decomposing the unitaries) with error message code ",error];False 1559 | ] 1560 | )] 1561 | 1562 | 1563 | FTestKnillDec := Module[{diag,exactDiagonalMat,bellIso,bellUnit,directUnit,error}, 1564 | (*tests with fractional (exact) inputs to Knill decomp. based on diagonal/ block diagonal inputs(based on Bell states). knill decomp does NOT work with arbitrary exact inputs*) 1565 | (*Construct matrices:*) 1566 | diag = {Exp[I*RandomInteger[15]*Pi/15]}; 1567 | Do[AppendTo[diag,Exp[I*RandomInteger[15]*Pi/15]],{i,3}]; 1568 | exactDiagonalMat = DiagonalMatrix[diag]; 1569 | bellIso = Transpose[{{1,0,0,1},{0,1,1,0}}/2^(1/2)]; 1570 | bellUnit= {{1,0,0,-1},{0,1,1,0},{0,-1,1,0},{1,0,0,1}}/2^(1/2); 1571 | For[i = 1, i <= 10, i++, directUnit = 1572 | FullSimplify[ 1573 | DirectSum[FPickRandomUnitary[2, 5], FPickRandomUnitary[2, 5]]]; 1574 | If[directUnit . CT[directUnit] == IdentityMatrix[4], Break[]]]; If[ 1575 | i == 11, Print[ 1576 | "Warning: Fractional Knill check on non-unitary input"]]; 1577 | error=0; 1578 | If[Quiet[Check[checkKnillDec[exactDiagonalMat],error=1;False]]&& 1579 | Quiet[Check[checkKnillDec[bellIso],error=2;False]]&& 1580 | Quiet[Check[checkKnillDec[bellUnit],error=3;False]]&& 1581 | Quiet[Check[checkKnillDec[directUnit],error=4;False]], 1582 | True, 1583 | Print["Error in KnillDec[] for exact inputs with error message code ",error];False 1584 | ] 1585 | ] 1586 | 1587 | 1588 | 1589 | (*All tests for Knill's decomposition*) 1590 | 1591 | 1592 | testKnill := Module[{},( 1593 | If[TestXToY &&TestIsoToUnitarySpecial&&TestUnitaryEigenvalueDecomp&&TestKnillDec1 1594 | &&TestKnillDec2&&TestKnillDec3&&FTestKnillDec, 1595 | Print["All tests for Knill's decomposition pass."],, 1596 | Print["testKnill neither returned True nor False"] 1597 | ] 1598 | )] 1599 | 1600 | 1601 | (*Unit tests for (sparse and dense) Housholder decomposition*) 1602 | 1603 | 1604 | (*Check Methods based on Householder decomposition*) 1605 | 1606 | 1607 | checkDenseHouseholder[v_]:=Module[{st,iso,n,nIso},( 1608 | st=DenseHouseholderDec[v]; 1609 | n = Log2[Dimensions[v][[1]]]; 1610 | iso=NCreateOperationFromGateList[st]; 1611 | nIso = Log2[Dimensions[iso][[1]]]; 1612 | If[nIso < n, 1613 | iso=NCreateOperationFromGateList[st,n]; 1614 | (*Ensure that the dimension is correct, even if the gates are 1615 | only acting on a part of the available qubits*) 1616 | ]; 1617 | isIdentityUpToPhase[N[ConjugateTranspose[v] . iso]] 1618 | ) 1619 | ] 1620 | checkSparseHouseholder[v_]:=Module[{st,iso,n,nIso},( 1621 | st=SparseHouseholderDec[v]; 1622 | n = Log2[Dimensions[v][[1]]]; 1623 | iso=NCreateOperationFromGateList[st]; 1624 | nIso = Log2[Dimensions[iso][[1]]]; 1625 | If[nIso < n, 1626 | iso=NCreateOperationFromGateList[st,n]; 1627 | (*Ensure that the dimension is correct, even if the gates are 1628 | only acting on a part of the available qubits*) 1629 | ]; 1630 | isIdentityUpToPhase[N[ConjugateTranspose[v] . iso]] 1631 | ) 1632 | ] 1633 | 1634 | 1635 | (*Tests for (sparse and dense) Householder decomposition*) 1636 | 1637 | 1638 | TestDenseHouseholder:=Module[{error},( 1639 | error=0; 1640 | If[Quiet[Check[checkDenseHouseholder[PickRandomIsometry[2,2^4]],error=1;False]]&& 1641 | Quiet[Check[checkDenseHouseholder[PickRandomIsometry[1,2^3]],error=2;False]]&& 1642 | Quiet[Check[checkDenseHouseholder[randPermutMat[2^1,2^2]],error=3;False]]&& 1643 | Quiet[Check[checkDenseHouseholder[N[randPermutMat[2^2,2^4]]],error=4;False]]&& 1644 | Quiet[Check[checkDenseHouseholder[PickRandomIsometry[1,2^2]],error=5;False]]&& 1645 | Quiet[Check[checkDenseHouseholder[PickRandomIsometry[2^3,2^3]],error=6;False]], 1646 | True, 1647 | Print["Error in DenseHouseholderDec with error message code ",error];False 1648 | ] 1649 | )] 1650 | 1651 | 1652 | TestSparseHouseholder:=Module[{error},( 1653 | error=0; 1654 | If[Quiet[Check[checkSparseHouseholder[PickRandomIsometry[2,2^4]],error=1;False]]&& 1655 | Quiet[Check[checkSparseHouseholder[PickRandomIsometry[1,2^3]],error=2;False]]&& 1656 | Quiet[Check[checkSparseHouseholder[randPermutMat[2^1,2^2]],error=3;False]]&& 1657 | Quiet[Check[checkSparseHouseholder[N[randPermutMat[2^2,2^4]]],error=4;False]]&& 1658 | Quiet[Check[checkSparseHouseholder[PickRandomSparseIsometry[1,2^2]],error=5;False]]&& 1659 | Quiet[Check[checkSparseHouseholder[PickRandomSparseIsometry[2^3,2^3]],error=6;False]], 1660 | True, 1661 | Print["Error in SparseHouseholderDec with error message code ",error];False 1662 | ] 1663 | )] 1664 | 1665 | 1666 | (*All tests for Housholder decomposition*) 1667 | 1668 | 1669 | testHouseholderAll := Module[{},( 1670 | If[TestDenseHouseholder&&TestSparseHouseholder, 1671 | Print["All tests for (dense and sparse) Householder decomposition pass."],, 1672 | Print["testHouseholderAll neither returned True nor False"] 1673 | ] 1674 | )] 1675 | 1676 | 1677 | (*Unit tests for state preparaion (Plesch-Brukner decomposition)*) 1678 | 1679 | 1680 | (*Checks for state preparation*) 1681 | 1682 | 1683 | CheckStatePreparation[v_,recLevel_]:=Module[{st,iso}, 1684 | st=StatePreparation[v,Range[Length[v]],recLevel]; 1685 | iso=NCreateIsometryFromListDim[st,Dimensions[v][[1]]]; 1686 | isIdentityUpToPhase[ConjugateTranspose[v] . iso] 1687 | ] 1688 | 1689 | 1690 | (*Tests for state preparation*) 1691 | 1692 | 1693 | TestStatePreparation:=Module[{error},( 1694 | error=0; 1695 | If[Quiet[Check[CheckStatePreparation[PickRandomPsi[2^4],level->1],error=1;False]]&& 1696 | Quiet[Check[CheckStatePreparation[PickRandomPsi[2^4],level->2],error=2;False]]&& 1697 | Quiet[Check[CheckStatePreparation[PickRandomPsi[2^4],level->3],error=3;False]]&& 1698 | Quiet[Check[CheckStatePreparation[N[{{0},{0},{1},{0},{0},{0},{0},{0}}],level->1],error=4;False]]&& 1699 | Quiet[Check[CheckStatePreparation[N[{{0},{0},{0},{0},{0},{1},{0},{0}}],level->2],error=5;False]]&& 1700 | Quiet[Check[CheckStatePreparation[N[{{0},{0},{0},{0},{0},{1},{0},{0}}],level->3],error=6;False]] 1701 | , 1702 | True, 1703 | Print["Error in StatePrepRecursive with error message code ",error];False 1704 | ] 1705 | )] 1706 | 1707 | 1708 | (*All tests for state preparation*) 1709 | 1710 | 1711 | testStatePreparationAll := Module[{},( 1712 | If[TestStatePreparation, 1713 | Print["All tests for state preparation pass."],, 1714 | Print["testStatePreparationAll neither returned True nor False"] 1715 | ] 1716 | )] 1717 | 1718 | 1719 | (*Unit tests for sparse state preparaion*) 1720 | 1721 | 1722 | (*Checks for sparse state preparation*) 1723 | 1724 | 1725 | checkSparseStatePreparation[psi_]:=Module[{st,iso},( 1726 | st=SparseStatePreparation[psi]; 1727 | iso=NCreateOperationFromGateList[st]; 1728 | isIdentityUpToPhase[N[ConjugateTranspose[psi] . iso]] 1729 | ) 1730 | ] 1731 | 1732 | 1733 | (*Tests for sparse state preparation*) 1734 | 1735 | 1736 | TestSparseStatePreparation:=Module[{error},( 1737 | error=0; 1738 | If[Quiet[Check[checkSparseStatePreparation[PickRandomPsi[2^4]],error=1;False]]&& 1739 | Quiet[Check[checkSparseStatePreparation[PickRandomSparsePsi[2^4,2^3]],error=2;False]]&& 1740 | Quiet[Check[checkSparseStatePreparation[PickRandomPsi[2^4]],error=3;False]]&& 1741 | Quiet[Check[checkSparseStatePreparation[N[{{0},{0},{1},{0},{0},{0},{0},{0}}]],error=4;False]]&& 1742 | Quiet[Check[checkSparseStatePreparation[N[{{0},{0},{0},{0},{0},{1},{0},{0}}]],error=5;False]]&& 1743 | Quiet[Check[checkSparseStatePreparation[N[{{0},{0},{0},{0},{0},{1},{0},{0}}]],error=6;False]] 1744 | , 1745 | True, 1746 | Print["Error in SparseStatePreparation with error message code ",error];False 1747 | ] 1748 | )] 1749 | 1750 | 1751 | (*All tests for sparse state preparation*) 1752 | 1753 | 1754 | testSparseStatePreparationAll := Module[{},( 1755 | If[TestSparseStatePreparation, 1756 | Print["All tests for sparse state preparation pass."],, 1757 | Print["testSparseStatePreparationAll neither returned True nor False"] 1758 | ] 1759 | )] 1760 | 1761 | 1762 | (*Unit tests for CNOT \[TwoWayRule] XX transformation*) 1763 | 1764 | 1765 | (*Checks for CNOT \[TwoWayRule] XX transformation*) 1766 | 1767 | 1768 | CheckCNOTtoXX[v_]:=Module[{st,st2,iso,ch}, 1769 | st=DecIsometryGeneric[v];st2=CNOTRotationsToXXRGates[st]; 1770 | iso=CreateOperationFromGateList[st2,Log[2,Dimensions[v][[1]]]];ch=CT[v] . iso; 1771 | Chop[ch/ch[[1,1]]-IdentityMatrix[Dimensions[iso][[2]]],10^-6]==0*IdentityMatrix[Dimensions[iso][[2]]]] 1772 | 1773 | CheckXXtoCNOT[v_]:=Module[{st,st2,st3,iso,ch}, 1774 | st=DecIsometryGeneric[v];st2=CNOTRotationsToXXRGates[st]; 1775 | st3=XXRGatesToCNOTRotations[st2]; 1776 | iso=CreateOperationFromGateList[st3,Log[2,Dimensions[v][[1]]]];ch=CT[v] . iso; 1777 | Chop[ch/ch[[1,1]]-IdentityMatrix[Dimensions[iso][[2]]],10^-6]==0*IdentityMatrix[Dimensions[iso][[2]]]] 1778 | 1779 | 1780 | (*Tests for CNOT \[TwoWayRule] XX transformation*) 1781 | 1782 | 1783 | TestCNOTtoXX:=Module[{error=0},If[Quiet[Check[CheckCNOTtoXX[PickRandomIsometry[2^2,2^2]],error=1;False]]&& 1784 | Quiet[Check[CheckCNOTtoXX[PickRandomIsometry[2^2,2^3]],error=2;False]]&& 1785 | Quiet[Check[CheckCNOTtoXX[PickRandomIsometry[2^2,2^4]],error=3;False]]&& 1786 | Quiet[Check[CheckCNOTtoXX[PickRandomIsometry[2^3,2^3]],error=4;False]]&& 1787 | Quiet[Check[CheckCNOTtoXX[PickRandomIsometry[2^3,2^4]],error=5;False]]&& 1788 | Quiet[Check[CheckCNOTtoXX[randPermutMat[4,4]],error=6;False]]&& 1789 | Quiet[Check[CheckCNOTtoXX[N[randPermutMat[8,8]]],error=7;False]] 1790 | , 1791 | True, 1792 | Print["Error in CheckCNOTtoXX with error message code ",error];False 1793 | ]] 1794 | 1795 | TestXXtoCNOT:=Module[{error=0},If[Quiet[Check[CheckXXtoCNOT[PickRandomIsometry[2^2,2^2]],error=1;False]]&& 1796 | Quiet[Check[CheckXXtoCNOT[PickRandomIsometry[2^2,2^3]],error=2;False]]&& 1797 | Quiet[Check[CheckXXtoCNOT[PickRandomIsometry[2^2,2^4]],error=3;False]]&& 1798 | Quiet[Check[CheckXXtoCNOT[PickRandomIsometry[2^3,2^3]],error=4;False]]&& 1799 | Quiet[Check[CheckXXtoCNOT[PickRandomIsometry[2^3,2^4]],error=5;False]]&& 1800 | Quiet[Check[CheckXXtoCNOT[randPermutMat[4,4]],error=6;False]]&& 1801 | Quiet[Check[CheckXXtoCNOT[N[randPermutMat[8,8]]],error=7;False]] 1802 | , 1803 | True, 1804 | Print["Error in CheckXXtoCNOT with error message code ",error];False 1805 | ]] 1806 | 1807 | 1808 | (*All tests for CNOT \[TwoWayRule] XX transformation*) 1809 | 1810 | 1811 | testXXCNOTAll := Module[{},( 1812 | If[TestCNOTtoXX&&TestXXtoCNOT, 1813 | Print["All tests for converting to and from XX gates pass."],, 1814 | Print["testXXCNOTAll neither returned True nor False"] 1815 | ] 1816 | )] 1817 | 1818 | 1819 | (* Unit tests for DecChannelInQCM *) 1820 | 1821 | checkDecChannelInQCM[chan_,t_:Null] := Module[{i, st, outChan, choi1, choi2}, 1822 | If[t===Null,st = DecChannelInQCM[chan],st = DecChannelInQCM[chan,DecomposeIso->"ColumnByColumnDec"]]; 1823 | outChan = CreateOperationFromGateList[st]; 1824 | If[Length[Dimensions[outChan]] == 2, outChan = {outChan}]; 1825 | choi1 = KrausToChoi[chan]; 1826 | choi2 = KrausToChoi[outChan]; 1827 | Norm[Chop[choi1 - choi2]] == 0 1828 | ] 1829 | 1830 | testDecChannelInQCM := Module[{error = 0},( 1831 | If[Quiet[Check[checkDecChannelInQCM[PickRandomChannel[2^2, 2^4, 2^2]], error = 1; False]]&& 1832 | Quiet[Check[checkDecChannelInQCM[PickRandomChannel[2^1, 2^2, 2^3]],error=2;False]]&& 1833 | Quiet[Check[checkDecChannelInQCM[PickRandomChannel[2^2, 2^3, 2^2]],error=4;False]]&& 1834 | Quiet[Check[checkDecChannelInQCM[PickRandomChannel[1, 2^2, 2^2]],error=5;False]]&& 1835 | Quiet[Check[checkDecChannelInQCM[PickRandomChannel[2^4, 2^4, 1]],error=6;False]]&& 1836 | Quiet[Check[checkDecChannelInQCM[{{{1/2,1/2},{-(1/2),1/2}},{{1/Sqrt[2],0},{0,1/Sqrt[2]}}},1],error=7;False]] 1837 | , 1838 | True, 1839 | Print["Error in DecChannelInQCM[] with error message code ",error];False 1840 | ]) 1841 | ] 1842 | 1843 | testChannelDecompositions := If[testDecChannelInQCM,Print["All tests for DecChannelInQCM pass."],, 1844 | Print["testChannelDecompositions neither returned True nor False"]] 1845 | 1846 | 1847 | 1848 | (* Unit Tests for DecInstrumentInQCM *) 1849 | 1850 | checkDecInstrumentInQCM[instr_,t_:Null] := Module[{i, st, rho, outInstr, sameAction, partialResultState, outPartialResultState}, 1851 | If[t===Null,st=DecInstrumentInQCM[instr],st=DecInstrumentInQCM[instr,DecomposeIso->"DecIsometryGeneric"]]; 1852 | outInstr = CreateOperationFromGateList[st]; 1853 | If[Length[Dimensions[outInstr]] == 3, outInstr = {outInstr}]; 1854 | If[Length[Dimensions[outInstr]] == 2, outInstr = {{outInstr}}]; 1855 | rho = PickRandomRho[Length[instr[[1]][[1]][[1]]]]; 1856 | sameAction = True; 1857 | For[i=1, i<=Length[instr], i++, 1858 | partialResultState = Chop[Sum[instr[[i]][[j]] . rho . CT[instr[[i]][[j]]], {j, 1, Length[instr[[i]]]}]]; 1859 | outPartialResultState = Chop[Sum[outInstr[[i]][[j]] . rho . CT[outInstr[[i]][[j]]], {j, 1, Length[outInstr[[i]]]}]]; 1860 | If[!(Chop[partialResultState - outPartialResultState] == 0), 1861 | sameAction = False]; 1862 | ]; 1863 | sameAction 1864 | ] 1865 | 1866 | testDecInstrumentInQCM := Module[{error = 0}, ( 1867 | If[Quiet[Check[checkDecInstrumentInQCM[PickRandomInstrument[1,1,2,3]], error = 1; False]]&& 1868 | Quiet[Check[checkDecInstrumentInQCM[PickRandomInstrument[2^1,2^2,4,2]], error = 2; False]]&& 1869 | Quiet[Check[checkDecInstrumentInQCM[PickRandomInstrument[2^1,2^2,4,{2,3,5,4}]],error=3;False]]&& 1870 | Quiet[Check[checkDecInstrumentInQCM[PickRandomInstrument[2^2,2^1,4,{5,2,3,2}]],error=4;False]]&& 1871 | Quiet[Check[checkDecInstrumentInQCM[PickRandomInstrument[1,2^2,4,4]],error=5;False]]&& 1872 | Quiet[Check[checkDecInstrumentInQCM[PickRandomInstrument[2^3,2^3,1,2]],error=6;False]]&& 1873 | Quiet[Check[checkDecInstrumentInQCM[PickRandomInstrument[2^3,2^3,2,1]],error=7;False]]&& 1874 | Quiet[Check[checkDecInstrumentInQCM[PickRandomInstrument[2^3,2^3,1,1]],error=8;False]]&& 1875 | Quiet[Check[checkDecInstrumentInQCM[{{{{1,1},{-1,1}},{{1,-1},{1,1}}}/2^(3/2),{{{1,0},{0,1}}/2^(1/2)}},1],error=9;False]] 1876 | , 1877 | True, 1878 | Print["Error in DecInstrumentInQCM[] with error message code ",error];False 1879 | ]) 1880 | ] 1881 | 1882 | testInstrumentDecompositions := If[testDecInstrumentInQCM,Print["All tests for DecInstrumentInQCM pass."],, 1883 | Print["testInstrumentDecompositions neither returned True nor False"]] 1884 | 1885 | 1886 | 1887 | (*Run all tests*) 1888 | runAllTests:=Module[{},(testAllBasicMethods;testUCGs;testAllDiagGateMethods;testIsoSmall;testCCDec;testDec2Qubit;testDecSingleQubit;testQSDAll;testQSD;testStatePreparationAll;testSparseStatePreparationAll;testAllMCGMethods;testKnill;testHouseholderAll;testIsometryDecompositions;testStinespring;testPOVM;testXXCNOTAll;testChannelDecompositions;testInstrumentDecompositions)] 1889 | 1890 | 1891 | Timing[runAllTests] 1892 | 1893 | 1894 | (*Switch precision warnings on again*) 1895 | On[N::meprec] 1896 | On[Floor::meprec] 1897 | On[Eigensystem::eivec0] 1898 | --------------------------------------------------------------------------------