├── .pylintrc ├── LICENSE ├── README.md ├── three_mode.py └── two_mode.py /.pylintrc: -------------------------------------------------------------------------------- 1 | [MASTER] 2 | # A comma-separated list of package or module names from where C extensions may 3 | # be loaded. Extensions are loading into the active Python interpreter and may 4 | # run arbitrary code 5 | extension-pkg-whitelist=numpy,scipy,sklearn,strawberryfields,matplotlib 6 | 7 | [TYPECHECK] 8 | 9 | # List of module names for which member attributes should not be checked 10 | # (useful for modules/projects where namespaces are manipulated during runtime 11 | # and thus existing member attributes cannot be deduced by static analysis. It 12 | # supports qualified module names, as well as Unix pattern matching. 13 | ignored-modules=numpy,scipy,sklearn,strawberryfields,matplotlib 14 | 15 | # List of classes names for which member attributes should not be checked 16 | # (useful for classes with attributes dynamically set). This supports can work 17 | # with qualified names. 18 | ignored-classes=numpy,scipy,sklearn,strawberryfields,matplotlib 19 | 20 | [MESSAGES CONTROL] 21 | 22 | # Enable the message, report, category or checker with the given id(s). You can 23 | # either give multiple identifier separated by comma (,) or put this option 24 | # multiple time. 25 | #enable= 26 | 27 | # Disable the message, report, category or checker with the given id(s). You 28 | # can either give multiple identifier separated by comma (,) or put this option 29 | # multiple time (only on the command line, not in the configuration file where 30 | # it should appear only once). 31 | disable=line-too-long,invalid-name,too-many-lines,redefined-builtin,too-many-locals,duplicate-code,redefined-outer-name,expression-not-assigned -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Constrained quantum learning 2 | 3 | ### Using machine learning to train a Gaussian quantum circuit with PNRs to produce cubic phase resource states with high fidelity and probability. 4 | 5 | 6 | This repository contains the source code used to produce the results presented in *"Near-deterministic production of universal quantum photonic gates enhanced by machine learning"* [arXiv:1809.04680](https://arxiv.org/abs/1809.04680). 7 | 8 | ## Contents 9 | 10 | The following two scripts perform a constrained variational quantum circuit optimization, using both a global search (basin hopping) and a local search (BFGS optimization) to maximize the fidelity (and probability of generating) the cubic phase resource state in the last mode. 11 | 12 | * `two_mode.py`: a Python script to generate the results of the two-mode gadget architecture presented in the paper. Here, a two mode squeezed displaced state is incident on a beamsplitter, with the first mode measured by a photon-number resolving detector. 13 | 14 | * `three_mode.py`: a Python script to generate the results of the three-mode gadget architecture presented in the paper. Here, a three mode squeezed displaced state is incident on an interferometer consisting of three beamsplitters, with the first and second modes measured by photon-number resolving detectors. 15 | 16 | 17 | ## Requirements 18 | 19 | To construct and optimize the constrained variational quantum circuits, these scripts use the Fock backend of [Strawberry Fields](https://github.com/XanaduAI/strawberryfields). In addition, SciPy is required for use of the global Basin Hopping optimization method, as well as the local BFGS optimization method. 20 | 21 | ## Authors 22 | 23 | Krishna Kumar Sabapathy, Haoyu Qi, Josh Izaac, and Christian Weedbrook. 24 | 25 | If you are doing any research using this source code and Strawberry Fields, please cite the following two papers: 26 | 27 | > Krishna Kumar Sabapathy, Haoyu Qi, Josh Izaac, and Christian Weedbrook. Near-deterministic production of universal quantum photonic gates enhanced by machine learning. arXiv, 2018. [arXiv:1809.04680](https://arxiv.org/abs/1809.04680) 28 | 29 | > Nathan Killoran, Josh Izaac, Nicolás Quesada, Ville Bergholm, Matthew Amy, and Christian Weedbrook. Strawberry Fields: A Software Platform for Photonic Quantum Computing. arXiv, 2018. [Quantum, 3, 129](https://quantum-journal.org/papers/q-2019-03-11-129/) (2019). 30 | 31 | ## License 32 | 33 | This source code is free and open source, released under the Apache License, Version 2.0. 34 | -------------------------------------------------------------------------------- /three_mode.py: -------------------------------------------------------------------------------- 1 | # Copyright 2018 Xanadu Quantum Technologies Inc. 2 | 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | """Perform the three mode constrained variational quantum circuit optimization 15 | to learn the ON state.""" 16 | import pickle 17 | import time 18 | import datetime 19 | 20 | import numpy as np 21 | from scipy.optimize import basinhopping, minimize 22 | 23 | import strawberryfields as sf 24 | from strawberryfields.ops import BSgate, Dgate, Sgate 25 | 26 | 27 | def init(clip_size): 28 | """Generate an initial random parameter. 29 | 30 | Args: 31 | clip_size (float): the parameter will be clipped 32 | to the domain [-clip_size, clipsize]. 33 | 34 | Returns: 35 | float: the random clipped parameter 36 | """ 37 | return np.random.rand() * 2 * clip_size - clip_size 38 | 39 | 40 | def on_state(a, cutoff): 41 | """The ON resource state we would like to learn. 42 | 43 | |psi> = |0> + i*sqrt(3/2)*a|1> + a*i|3> 44 | 45 | Args: 46 | a (float): the ON state parameter 47 | cutoff (int): the Fock basis truncation 48 | 49 | Returns: 50 | array: the density matrix rho=|psi>ij', ket, np.conj(ket)) 58 | return dm 59 | 60 | 61 | def circuit(params, a, m1, m2, cutoff): 62 | """Runs the constrained variational circuit with specified parameters, 63 | returning the output fidelity to the requested ON state, as well as 64 | the post-selection probability. 65 | 66 | Args: 67 | params (list): list of gate parameters for the constrained 68 | variational quantum circuit. This should contain the following 15 values 69 | in the following order: 70 | 71 | * ``sq_r0, sq_r1, sq_r2``: the squeezing magnitudes applied to the first three modes 72 | * ``sq_phi0, sq_phi1, sq_phi2``: the squeezing phase applied to the first three modes 73 | * ``d_r0, d_r1, d_r2``: the displacement magnitudes applied to the first three modes 74 | * ``bs_theta1, bs_theta2, bs_theta3``: the 3-mode interferometer beamsplitter angles theta 75 | * ``bs_phi1, bs_phi2, bs_phi3``: the 3-mode interferometer beamsplitter phases phi 76 | 77 | a (float): the ON state parameter 78 | m1 (int): the Fock state measurement of mode 0 to be post-selected 79 | m2 (int): the Fock state measurement of mode 1 to be post-selected 80 | cutoff (int): the Fock basis truncation 81 | 82 | Returns: 83 | tuple: a tuple containing the output fidelity to the target ON state, 84 | the probability of post-selection, the state norm before entering the beamsplitter, 85 | the state norm after exiting the beamsplitter, and the density matrix of the output state. 86 | """ 87 | # define target state 88 | ONdm = on_state(a, cutoff) 89 | 90 | # unpack circuit parameters 91 | # squeezing magnitudes 92 | sq_r = params[:3] 93 | # squeezing phase 94 | sq_phi = params[3:6] 95 | # displacement magnitudes (assume displacement is real for now) 96 | d_r = params[6:9] 97 | # beamsplitter theta 98 | bs_theta1, bs_theta2, bs_theta3 = params[9:12] 99 | # beamsplitter phi 100 | bs_phi1, bs_phi2, bs_phi3 = params[12:] 101 | 102 | # quantum circuit prior to entering the beamsplitter 103 | prog = sf.Program(3) 104 | 105 | with prog.context as q: 106 | for k in range(3): 107 | Sgate(sq_r[k], sq_phi[k]) | q[k] 108 | Dgate(d_r[k]) | q[k] 109 | 110 | eng = sf.Engine("fock", backend_options={"cutoff_dim": cutoff}) 111 | stateIn = eng.run(prog).state 112 | normIn = np.abs(stateIn.trace()) 113 | 114 | # norm of output state and probability 115 | prog_BS = sf.Program(3) 116 | with prog_BS.context as q: 117 | BSgate(bs_theta1, bs_phi1) | (q[0], q[1]) 118 | BSgate(bs_theta2, bs_phi2) | (q[1], q[2]) 119 | BSgate(bs_theta3, bs_phi3) | (q[0], q[1]) 120 | 121 | stateOut = eng.run(prog_BS).state 122 | normOut = np.abs(stateOut.trace()) 123 | rho = stateOut.dm() 124 | 125 | # probability of meausring m1 and m2 126 | prob = np.abs(np.trace(rho[m1, m1, m2, m2])) 127 | 128 | # output state 129 | rhoC = rho[m1, m1, m2, m2]/prob 130 | 131 | #fidelity with the target 132 | fidelity = np.abs(np.trace(np.einsum('ij,jk->ik', rhoC, ONdm))) 133 | return (fidelity, prob, normIn, normOut, rhoC) 134 | 135 | 136 | def loss(params, a, m1, m2, cutoff): 137 | """Returns the loss function of the constrained variational circuit. 138 | 139 | The loss function is given by: 140 | 141 | loss = -fidelity + 10*(1-np.abs(normIn)) + 10*(1-np.abs(normOut)) 142 | 143 | Therefore, minimising the loss function will result in the output state 144 | approaching the target ON state. 145 | 146 | Args: 147 | params (list): list of gate parameters for the constrained 148 | variational quantum circuit. This should contain the following 15 values 149 | in the following order: 150 | 151 | * ``sq_r0, sq_r1, sq_r2``: the squeezing magnitudes applied to the first three modes 152 | * ``sq_phi0, sq_phi1, sq_phi2``: the squeezing phase applied to the first three modes 153 | * ``d_r0, d_r1, d_r2``: the displacement magnitudes applied to the first three modes 154 | * ``bs_theta1, bs_theta2, bs_theta3``: the 3-mode interferometer beamsplitter angles theta 155 | * ``bs_phi1, bs_phi2, bs_phi3``: the 3-mode interferometer beamsplitter phases phi 156 | 157 | a (float): the ON state parameter 158 | m1 (int): the Fock state measurement of mode 0 to be post-selected 159 | m2 (int): the Fock state measurement of mode 1 to be post-selected 160 | cutoff (int): the Fock basis truncation 161 | 162 | Returns: 163 | float: loss value. 164 | """ 165 | fidelity, _, normIn, normOut, _ = circuit(params, a, m1, m2, cutoff) 166 | loss = -fidelity + 10 * (1 - np.abs(normIn)) + 10 * (1 - np.abs(normOut)) 167 | return loss 168 | 169 | 170 | def loss_with_prob(params, a, m1, m2, cutoff): 171 | """Returns the loss function of the constrained variational circuit 172 | with post-selection probability to be also maximised. 173 | 174 | The loss function is given by: 175 | 176 | loss = -fidelity - prob + 10*(1-np.abs(normIn)) + 10*(1-np.abs(normOut)) 177 | 178 | Therefore, minimising the loss function will result in the output state 179 | approaching the target ON state, while also maximising the probability 180 | of generating the output state. 181 | 182 | Args: 183 | params (list): list of gate parameters for the constrained 184 | variational quantum circuit. This should contain the following 15 values 185 | in the following order: 186 | 187 | * ``sq_r0, sq_r1, sq_r2``: the squeezing magnitudes applied to the first three modes 188 | * ``sq_phi0, sq_phi1, sq_phi2``: the squeezing phase applied to the first three modes 189 | * ``d_r0, d_r1, d_r2``: the displacement magnitudes applied to the first three modes 190 | * ``bs_theta1, bs_theta2, bs_theta3``: the 3-mode interferometer beamsplitter angles theta 191 | * ``bs_phi1, bs_phi2, bs_phi3``: the 3-mode interferometer beamsplitter phases phi 192 | 193 | a (float): the ON state parameter 194 | m1 (int): the Fock state measurement of mode 0 to be post-selected 195 | m2 (int): the Fock state measurement of mode 1 to be post-selected 196 | cutoff (int): the Fock basis truncation 197 | 198 | Returns: 199 | float: loss value. 200 | """ 201 | fidelity, prob, normIn, normOut, _ = circuit(params, a, m1, m2, cutoff) 202 | loss = -fidelity - prob + 10 * (1 - np.abs(normIn)) + 10 * (1 - np.abs(normOut)) 203 | return loss 204 | 205 | 206 | i = 0 207 | xf = [] 208 | fid_progress = [] 209 | prob_progress = [] 210 | 211 | 212 | class stopException(Exception): 213 | """Exception used if the optimization is stopped""" 214 | pass 215 | 216 | 217 | def run_global_optimization(a, m1, m2, dir='data'): 218 | """Run the constrained variational quantum circuit global optimization 219 | using the basin hopping algorithm. 220 | 221 | Args: 222 | a (float): the ON state parameter 223 | m1 (int): the Fock state measurement of mode 0 to be post-selected 224 | m2 (int): the Fock state measurement of mode 1 to be post-selected 225 | dir (str): data directory to save output 226 | 227 | Returns: 228 | tuple: optimization results. A tuple of circuit parameters, 229 | fidelity to the target state, and probability of generating the state. 230 | """ 231 | # circuit hyperparameters 232 | clip_size = 1 233 | cutoff = 15 234 | 235 | # generate the initial parameters 236 | bound = [clip_size] * 3 + [np.pi] * 3 + [clip_size] * 3 + [np.pi] * 6 237 | x0 = map(init, bound) 238 | 239 | # perform the optimization 240 | minimizer_kwargs = {"method": "SLSQP", "args": (a, m1, m2, cutoff)} # SLSQP L-BFGS-B 241 | 242 | def myAccept(xk, f, accepted): 243 | """ this accept condition is to save some computational time which is optional""" 244 | global i 245 | global fid_progress 246 | global prob_progress 247 | i = i + 1 248 | fidelity, prob, normIn, normOut, _ = circuit(xk, a, m1, m2, cutoff) 249 | fid_progress.append(fidelity) 250 | prob_progress.append(prob) 251 | 252 | print("Hopping {} fidelity: {}, prob: {}, normIn: {}, normOut: {}".format(i, fidelity, prob, round(normIn, 2), round(normOut, 2))) 253 | if fidelity >= .9999 and prob >= 1e-4: 254 | file_name = dir 255 | results = {'para': xk, 256 | 'fid_progress': fid_progress, 257 | 'prob_progress': prob_progress} 258 | with open(file_name + '.pickle', 'wb') as handle: 259 | pickle.dump(results, handle, protocol=pickle.HIGHEST_PROTOCOL) 260 | print(time.time() - start) 261 | raise stopException() 262 | 263 | print("optimizing a={}".format(a)) 264 | 265 | res = basinhopping(loss, list(x0), minimizer_kwargs=minimizer_kwargs, niter=40, callback=myAccept) 266 | 267 | fidelity, prob, _, _, _ = circuit(res.x, a, m1, m2, cutoff) 268 | print(fidelity, prob) 269 | 270 | return res.x, fidelity, prob 271 | 272 | 273 | def run_local_optimization(a, m1, m2, init_params): 274 | """Run the constrained variational quantum circuit global optimization 275 | using the basin hopping algorithm. 276 | 277 | Args: 278 | a (float): the ON state parameter 279 | m1 (int): the Fock state measurement of mode 0 to be post-selected 280 | m2 (int): the Fock state measurement of mode 1 to be post-selected 281 | init_params (Sequence): initial gate parameters 282 | 283 | Returns: 284 | tuple: optimization results. A tuple of circuit parameters, 285 | fidelity to the target state, and probability of generating the state. 286 | """ 287 | cutoff = 15 288 | 289 | def printfunc(xk): 290 | """Callback print function for the BFGS minimisation algorithm""" 291 | global i 292 | global xf 293 | # global fidelity 294 | # global prob 295 | i = i+1 296 | fidelity, prob, normIn, normOut, _ = circuit(xk, a, m1, m2, cutoff) 297 | 298 | xf = xk 299 | # fidelity = fidelity_n 300 | # prob = prob_n 301 | print("step {} fidelity: {}, prob: {}, normIn: {}, normOut: {}".format(i, fidelity, prob, normIn, normOut)) 302 | if fidelity >= .999 and prob >= 0.02: 303 | raise stopException() 304 | 305 | # run optimization 306 | args = [a, m1, m2, cutoff] 307 | try: 308 | res = minimize(loss_with_prob, init_params, args=args, method='BFGS', callback=printfunc) 309 | except stopException: 310 | out_file_name = 'data/final3mode' + 'a=' + str(a) + 'm1=' + str(m1) + 'm2=' + str(m2) 311 | 312 | with open(out_file_name + '.pickle', 'wb') as handle: 313 | pickle.dump(xf, handle, protocol=pickle.HIGHEST_PROTOCOL) 314 | 315 | fid, prob, _, _, _ = circuit(xf, a, m1, m2, cutoff) 316 | print("Final fidelity: {}, prob: {}".format(fid, prob)) 317 | 318 | return res.x, fid, prob 319 | 320 | 321 | if __name__ == "__main__": 322 | # hyperparameters 323 | a = 0.3 324 | m1 = 1 325 | m2 = 2 326 | global_save_file_name = 'run1_global' 327 | 328 | print(datetime.datetime.now()) 329 | print("==============") 330 | print("Basin Hopping") 331 | print("==============") 332 | 333 | start = time.time() 334 | 335 | x0, _, _ = run_global_optimization(a, m1, m2, global_save_file_name) 336 | time_elapsed = time.time() - start 337 | print('Runtime: ', time_elapsed) 338 | 339 | start = time.time() 340 | print(datetime.datetime.now()) 341 | print("==============") 342 | print("Local search for high prob") 343 | print("==============") 344 | 345 | i = 0 346 | xf = [] 347 | 348 | run_local_optimization(a, m1, m2, x0) 349 | print("Use time {}".format(time.time()-start)) 350 | -------------------------------------------------------------------------------- /two_mode.py: -------------------------------------------------------------------------------- 1 | # Copyright 2018 Xanadu Quantum Technologies Inc. 2 | 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | """Perform the two mode constrained variational quantum circuit optimization 15 | to learn the ON state.""" 16 | import pickle 17 | import operator 18 | import time 19 | import datetime 20 | 21 | import numpy as np 22 | from scipy.optimize import basinhopping 23 | 24 | from sklearn.cluster import KMeans 25 | 26 | import strawberryfields as sf 27 | from strawberryfields.ops import BSgate, Dgate, Sgate 28 | 29 | 30 | def init(clip_size): 31 | """Generate an initial random parameter. 32 | 33 | Args: 34 | clip_size (float): the parameter will be clipped 35 | to the domain [-clip_size, clipsize]. 36 | 37 | Returns: 38 | float: the random clipped parameter 39 | """ 40 | return np.random.rand() * 2 * clip_size - clip_size 41 | 42 | 43 | def on_state(a, cutoff): 44 | """The ON resource state we would like to learn. 45 | 46 | |psi> = |0> + i*sqrt(3/2)*a|1> + a*i|3> 47 | 48 | Args: 49 | a (float): the ON state parameter 50 | cutoff (int): the Fock basis truncation 51 | 52 | Returns: 53 | array: the density matrix rho=|psi>ij', ket, np.conj(ket)) 61 | return dm 62 | 63 | 64 | def circuit(params, a, m, cutoff): 65 | """Runs the constrained variational circuit with specified parameters, 66 | returning the output fidelity to the requested ON state, as well as 67 | the post-selection probability. 68 | 69 | Args: 70 | params (list): list of gate parameters for the constrained 71 | variational quantum circuit. This should contain the following values 72 | in the following order: 73 | 74 | * ``'sq0' = (r, phi)``: the squeezing magnitude and phase on mode 0 75 | * ``'disp0' = (r, phi)``: the displacement magnitude and phase on mode 0 76 | * ``'sq1' = (r, phi)``: the squeezing magnitude and phase on mode 1 77 | * ``'disp1' = (r, phi)``: the displacement magnitude and phase on mode 1 78 | * ``'BS' = (theta, phi)``: the beamsplitter angles 79 | 80 | a (float): the ON state parameter 81 | m (int): the Fock state measurement to be post-selected 82 | cutoff (int): the Fock basis truncation 83 | 84 | Returns: 85 | tuple: a tuple containing the output fidelity to the target ON state, 86 | the probability of post-selection, the state norm before entering the beamsplitter, 87 | the state norm after exiting the beamsplitter, and the density matrix of the output state. 88 | """ 89 | # define target state 90 | ONdm = on_state(a, cutoff) 91 | 92 | # unpack circuit parameters 93 | sq0_r, sq0_phi, disp0_r, disp0_phi, sq1_r, sq1_phi, disp1_r, disp1_phi, theta, phi = params 94 | 95 | # quantum circuit prior to entering the beamsplitter 96 | prog1 = sf.Program(2) 97 | with prog1.context as q1: 98 | Sgate(sq0_r, sq0_phi) | q1[0] 99 | Dgate(disp0_r, disp0_phi) | q1[0] 100 | Sgate(sq1_r, sq1_phi) | q1[1] 101 | Dgate(disp1_r, disp1_phi) | q1[1] 102 | 103 | eng = sf.Engine("fock", backend_options={"cutoff_dim": cutoff}) 104 | stateIn = eng.run(prog1).state 105 | normIn = np.abs(stateIn.trace()) 106 | 107 | # norm of output state and probability 108 | prog_BS = sf.Program(2) 109 | with prog_BS.context as q1: 110 | BSgate(theta, phi) | (q1[0], q1[1]) 111 | 112 | stateOut = eng.run(prog_BS).state 113 | normOut = np.abs(stateOut.trace()) 114 | rho = stateOut.dm() 115 | 116 | # probability of meausring m1 and m2 117 | prob = np.abs(np.trace(rho[m, m])) 118 | 119 | # output state 120 | rhoB = rho[m, m]/prob 121 | 122 | fidelity = np.abs(np.trace(np.einsum('ij,jk->ik', rhoB, ONdm))) 123 | return (fidelity, prob, normIn, normOut, rhoB) 124 | 125 | 126 | def loss(params, a, m, cutoff): 127 | """Returns the loss function of the constrained variational circuit. 128 | 129 | The loss function is given by: 130 | 131 | loss = -fidelity + 10*(1-np.abs(normIn)) + 10*(1-np.abs(normOut)) 132 | 133 | Therefore, minimising the loss function will result in the output state 134 | approaching the target ON state. 135 | 136 | Args: 137 | params (list): list of gate parameters for the constrained 138 | variational quantum circuit. This should contain the following values 139 | in the following order: 140 | 141 | * ``'sq0' = (r, phi)``: the squeezing magnitude and phase on mode 0 142 | * ``'disp0' = (r, phi)``: the displacement magnitude and phase on mode 0 143 | * ``'sq1' = (r, phi)``: the squeezing magnitude and phase on mode 1 144 | * ``'disp1' = (r, phi)``: the displacement magnitude and phase on mode 1 145 | * ``'BS' = (theta, phi)``: the beamsplitter angles 146 | 147 | a (float): the ON state parameter 148 | m (int): the Fock state measurement to be post-selected 149 | cutoff (int): the Fock basis truncation 150 | 151 | Returns: 152 | float: loss value. 153 | """ 154 | fidelity, _, normIn, normOut, _ = circuit(params, a, m, cutoff) 155 | loss = -fidelity + 10*(1-np.abs(normIn)) + 10*(1-np.abs(normOut)) 156 | return loss 157 | 158 | 159 | def loss_with_prob(params, a, m, cutoff): 160 | """Returns the loss function of the constrained variational circuit 161 | with post-selection probability to be also maximised. 162 | 163 | The loss function is given by: 164 | 165 | loss = -fidelity - prob + 10*(1-np.abs(normIn)) + 10*(1-np.abs(normOut)) 166 | 167 | Therefore, minimising the loss function will result in the output state 168 | approaching the target ON state, while also maximising the probability 169 | of generating the output state. 170 | 171 | Args: 172 | params (list): list of gate parameters for the constrained 173 | variational quantum circuit. This should contain the following values 174 | in the following order: 175 | 176 | * ``'sq0' = (r, phi)``: the squeezing magnitude and phase on mode 0 177 | * ``'disp0' = (r, phi)``: the displacement magnitude and phase on mode 0 178 | * ``'sq1' = (r, phi)``: the squeezing magnitude and phase on mode 1 179 | * ``'disp1' = (r, phi)``: the displacement magnitude and phase on mode 1 180 | * ``'BS' = (theta, phi)``: the beamsplitter angles 181 | 182 | a (float): the ON state parameter 183 | m (int): the Fock state measurement to be post-selected 184 | cutoff (int): the Fock basis truncation 185 | 186 | Returns: 187 | float: loss value. 188 | """ 189 | fidelity, prob, normIn, normOut, _ = circuit(params, a, m, cutoff) 190 | loss = -fidelity -prob + 10*(1-np.abs(normIn)) + 10*(1-np.abs(normOut)) 191 | return loss 192 | 193 | 194 | def run_global_optimization(a, m, nhp): 195 | """Run the constrained variational quantum circuit global optimization 196 | using the basin hopping algorithm. 197 | 198 | Args: 199 | a (float): the ON state parameter 200 | m (int): the Fock state measurement to be post-selected 201 | nhp (int): number of basin hopping iterations 202 | 203 | Returns: 204 | tuple: optimization results. A tuple of circuit parameters, 205 | fidelity to the target state, and probability of generating the state. 206 | """ 207 | # circuit hyperparameters 208 | clip_size = 1 209 | cutoff = 15 210 | 211 | # generate the initial parameters 212 | bound = [clip_size, np.pi]*4+[np.pi]*2 213 | x0 = map(init, bound) 214 | 215 | # perform the optimization 216 | minimizer_kwargs = {"method": "SLSQP", "args": (a, m, cutoff)} # SLSQP L-BFGS-B 217 | print("hopping....") 218 | 219 | res = basinhopping(loss, list(x0), minimizer_kwargs=minimizer_kwargs, niter=nhp) 220 | 221 | #print the final restuls 222 | x_f = res.x 223 | fidelity, prob, _, _, _ = circuit(x_f, a, m, cutoff) 224 | print("final fid {}, prob {}".format(fidelity, prob)) 225 | return res.x, fidelity, prob 226 | 227 | 228 | if __name__ == "__main__": 229 | # Set the optimization hyperparameters 230 | a = 0.3 231 | m = 2 232 | file_name = 'run1' 233 | 234 | print(datetime.datetime.now()) 235 | print("=====================================") 236 | print("Direct optimization for a = {}, m ={}".format(a, m)) 237 | print("=====================================") 238 | start = time.time() 239 | 240 | # ============================================================= 241 | # Perform the global optimization 242 | # ============================================================= 243 | 244 | # run the bashin hopping algorithms (each hop nhp times) ntier times 245 | nhp = 20 246 | niter = 30 247 | 248 | #store the result from each global search 249 | dir = 'data' 250 | 251 | hpx = [] 252 | prob_ls = [] 253 | fid_ls = [] 254 | 255 | for e in range(niter): 256 | print("Global explore {}".format(e+1)) 257 | x, fid, prob = run_global_optimization(a, m, nhp) 258 | 259 | prob_ls.append(prob) 260 | fid_ls.append(fid) 261 | hpx.append(x) 262 | 263 | # ============================================================= 264 | # remove non-optimal fidelities which will happen occassionally 265 | # ============================================================= 266 | 267 | fid_ls = np.array(fid_ls) 268 | res = KMeans(n_clusters=2).fit(fid_ls.reshape(-1, 1)) 269 | mean0 = np.mean(fid_ls[np.where(res.labels_ == 0)]) 270 | mean1 = np.mean(fid_ls[np.where(res.labels_ == 1)]) 271 | 272 | if np.abs(mean0 - mean1) < 0.01: 273 | # this means there is no sub-optimal point so we don't need to remove it 274 | print('Fail') 275 | else: 276 | if mean0 > mean1: 277 | drop = 1 278 | else: 279 | drop = 0 280 | 281 | print("mean of cluster 0: {:.3f}, mean of cluster 1: {:.3f}, drop {:d}".format(mean0, mean1, drop)) 282 | 283 | prob_ls = np.array(prob_ls) 284 | prob_ls[np.where(res.labels_ == drop)] = 0 285 | print(prob_ls) 286 | 287 | # ============================================================= 288 | # Select the best prob 289 | # NOTE: this is only guaranteed to work if we have the 290 | # correct optimal fidelity 291 | # ============================================================= 292 | 293 | index, value = max(enumerate(prob_ls), key=operator.itemgetter(1)) 294 | x_opt = hpx[index] 295 | print("best fid: {}, best prob {}".format(fid_ls[index], prob_ls[index])) 296 | 297 | #save results to file_name.pickle 298 | with open(file_name + '.pickle', 'wb') as handle: 299 | pickle.dump(x_opt, handle, protocol=pickle.HIGHEST_PROTOCOL) 300 | 301 | print("Runtime: {}".format(time.time()-start)) 302 | --------------------------------------------------------------------------------