├── .circleci └── config.yml ├── .devcontainer └── devcontainer.json ├── .gitignore ├── LICENSE ├── README.md ├── demo.py ├── requirements.txt └── tests ├── __init__.py ├── test_integration.py └── test_interfaces.py /.circleci/config.yml: -------------------------------------------------------------------------------- 1 | version: 2.1 2 | 3 | orbs: 4 | dwave: dwave/orb-examples@2 5 | 6 | workflows: 7 | version: 2.1 8 | tests: 9 | jobs: 10 | - dwave/test-linux 11 | - dwave/test-osx 12 | - dwave/test-win 13 | 14 | weekly: 15 | triggers: 16 | - schedule: 17 | cron: "0 4 * * 0" 18 | filters: 19 | branches: 20 | only: 21 | - master 22 | - main 23 | jobs: 24 | - dwave/test-linux: 25 | integration-tests: "canary" 26 | - dwave/test-osx: 27 | integration-tests: "skip" 28 | - dwave/test-win: 29 | integration-tests: "skip" 30 | -------------------------------------------------------------------------------- /.devcontainer/devcontainer.json: -------------------------------------------------------------------------------- 1 | // For format details, see https://aka.ms/devcontainer.json. For config options, see the 2 | // README at: https://github.com/devcontainers/templates/tree/main/src/debian 3 | { 4 | "name": "Ocean Development Environment", 5 | 6 | // python 3.11 on debian, with latest Ocean and optional packages 7 | // source repo: https://github.com/dwavesystems/ocean-dev-docker 8 | "image": "docker.io/dwavesys/ocean-dev:latest", 9 | 10 | // install repo requirements on create and content update 11 | "updateContentCommand": "pip install -r requirements.txt", 12 | 13 | // forward/expose container services (relevant only when run locally) 14 | "forwardPorts": [ 15 | // dwave-inspector web app 16 | 18000, 18001, 18002, 18003, 18004, 17 | // OAuth connect redirect URIs 18 | 36000, 36001, 36002, 36003, 36004 19 | ], 20 | 21 | "portsAttributes": { 22 | "18000-18004": { 23 | "label": "D-Wave Problem Inspector", 24 | "requireLocalPort": true 25 | }, 26 | "36000-36004": { 27 | "label": "OAuth 2.0 authorization code redirect URI", 28 | "requireLocalPort": true 29 | } 30 | }, 31 | 32 | // Configure tool-specific properties. 33 | "customizations": { 34 | // Configure properties specific to VS Code. 35 | "vscode": { 36 | // Set *default* container specific settings.json values on container create. 37 | "settings": { 38 | "workbench": { 39 | "editorAssociations": { 40 | "*.md": "vscode.markdown.preview.editor" 41 | }, 42 | "startupEditor": "readme" 43 | } 44 | }, 45 | "extensions": [ 46 | "ms-python.python", 47 | "ms-toolsai.jupyter" 48 | ] 49 | } 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | env/ 12 | build/ 13 | develop-eggs/ 14 | dist/ 15 | downloads/ 16 | eggs/ 17 | .eggs/ 18 | lib/ 19 | lib64/ 20 | parts/ 21 | sdist/ 22 | var/ 23 | wheels/ 24 | *.egg-info/ 25 | .installed.cfg 26 | *.egg 27 | 28 | # PyInstaller 29 | # Usually these files are written by a python script from a template 30 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 31 | *.manifest 32 | *.spec 33 | 34 | # Installer logs 35 | pip-log.txt 36 | pip-delete-this-directory.txt 37 | 38 | # Unit test / coverage reports 39 | htmlcov/ 40 | .tox/ 41 | .coverage 42 | .coverage.* 43 | .cache 44 | nosetests.xml 45 | coverage.xml 46 | *.cover 47 | .hypothesis/ 48 | 49 | # Translations 50 | *.mo 51 | *.pot 52 | 53 | # Django stuff: 54 | *.log 55 | local_settings.py 56 | 57 | # Flask stuff: 58 | instance/ 59 | .webassets-cache 60 | 61 | # Scrapy stuff: 62 | .scrapy 63 | 64 | # Sphinx documentation 65 | docs/_build/ 66 | 67 | # PyBuilder 68 | target/ 69 | 70 | # Jupyter Notebook 71 | .ipynb_checkpoints 72 | 73 | # pyenv 74 | .python-version 75 | 76 | # celery beat schedule file 77 | celerybeat-schedule 78 | 79 | # SageMath parsed files 80 | *.sage.py 81 | 82 | # dotenv 83 | .env 84 | 85 | # virtualenv 86 | .venv 87 | venv/ 88 | ENV/ 89 | 90 | # Spyder project settings 91 | .spyderproject 92 | .spyproject 93 | 94 | # Rope project settings 95 | .ropeproject 96 | 97 | # mkdocs documentation 98 | /site 99 | 100 | # mypy 101 | .mypy_cache/ 102 | -------------------------------------------------------------------------------- /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 | [![Open in GitHub Codespaces]( 2 | https://img.shields.io/badge/Open%20in%20GitHub%20Codespaces-333?logo=github)]( 3 | https://codespaces.new/dwave-examples/factoring?quickstart=1) 4 | [![Linux/Mac/Windows build status]( 5 | https://circleci.com/gh/dwave-examples/factoring.svg?style=shield)]( 6 | https://circleci.com/gh/dwave-examples/factoring) 7 | 8 | # Factoring 9 | 10 | This code demonstrates the use of the D-Wave system to solve a factoring 11 | problem. This is done by turning the problem into a three-bit multiplier 12 | circuit. 13 | 14 | ## Usage 15 | 16 | A minimal working example using the main interface function can be seen by 17 | running: 18 | 19 | ```bash 20 | python demo.py 21 | ``` 22 | 23 | The user is prompted to enter a six-bit integer: P, which represents a product 24 | to be factored. 25 | 26 | ```bash 27 | Input product ( 0 <= P <= 63): 28 | ``` 29 | 30 | The algorithm returns possible A and B values, which are the inputs the circuit 31 | multiplies to calculate the product, P. 32 | 33 | ## Code Overview 34 | 35 | Integer factoring is the decomposition of an integer into factors that, when 36 | multiplied together, give the original number. For example, the factors of 15 37 | are 3 and 5. 38 | 39 | D-Wave quantum computers allow us to factor numbers in an entirely new way, by 40 | turning a multiplication circuit into a constraint satisfaction problem that 41 | allows the quantum computer to compute inputs from a predefined output. 42 | Essentially, this means running the multiplication circuit in reverse! 43 | 44 | A Boolean logic circuit is usually viewed as computing outputs from inputs 45 | based on the logic of the gates. However, the problem can also be thought of as 46 | seeking an assignment of values to the inputs and outputs consistent with the 47 | logic of all the gates in the circuit. This perspective of constraint 48 | satisfaction has no directionality. That is, input values do not need to flow 49 | through a series of gates to yield a result, as they do in a multiplication 50 | circuit. 51 | 52 | ## License 53 | 54 | Released under the Apache License 2.0. See [LICENSE](LICENSE) file. 55 | -------------------------------------------------------------------------------- /demo.py: -------------------------------------------------------------------------------- 1 | # Copyright 2018 D-Wave Systems 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 | 15 | import sys 16 | import time 17 | import logging 18 | import functools 19 | from collections import OrderedDict 20 | 21 | import dwavebinarycsp as dbc 22 | from dwave.system import DWaveSampler, EmbeddingComposite 23 | 24 | log = logging.getLogger(__name__) 25 | 26 | def sanitised_input(description, variable, range_): 27 | start = range_[0] 28 | stop = range_[-1] 29 | 30 | while True: 31 | ui = input("Input {:15}({:2} <= {:1} <= {:2}): ".format(description, start, variable, stop)) 32 | 33 | try: 34 | ui = int(ui) 35 | except ValueError: 36 | print("Input type must be int") 37 | continue 38 | 39 | if ui not in range_: 40 | print("Input must be between {} and {}".format(start, stop)) 41 | continue 42 | 43 | return ui 44 | 45 | def validate_input(ui, range_): 46 | start = range_[0] 47 | stop = range_[-1] 48 | 49 | if not isinstance(ui, int): 50 | raise ValueError("Input type must be int") 51 | 52 | if ui not in range_: 53 | raise ValueError("Input must be between {} and {}".format(start, stop)) 54 | 55 | def factor(P): 56 | 57 | # Construct circuit 58 | # ================= 59 | construction_start_time = time.time() 60 | 61 | validate_input(P, range(2 ** 6)) 62 | 63 | # Constraint satisfaction problem 64 | csp = dbc.factories.multiplication_circuit(3) 65 | 66 | # Binary quadratic model 67 | bqm = dbc.stitch(csp, min_classical_gap=.1) 68 | 69 | # multiplication_circuit() creates these variables 70 | p_vars = ['p0', 'p1', 'p2', 'p3', 'p4', 'p5'] 71 | 72 | # Convert P from decimal to binary 73 | fixed_variables = dict(zip(reversed(p_vars), "{:06b}".format(P))) 74 | fixed_variables = {var: int(x) for(var, x) in fixed_variables.items()} 75 | 76 | # Fix product qubits 77 | for var, value in fixed_variables.items(): 78 | bqm.fix_variable(var, value) 79 | 80 | log.debug('bqm construction time: %s', time.time() - construction_start_time) 81 | 82 | # Run problem 83 | # =========== 84 | 85 | sample_time = time.time() 86 | 87 | # Set a QPU sampler 88 | sampler = EmbeddingComposite(DWaveSampler()) 89 | 90 | num_reads = 100 91 | sampleset = sampler.sample(bqm, 92 | num_reads=num_reads, 93 | label='Example - Factoring') 94 | 95 | log.debug('embedding and sampling time: %s', time.time() - sample_time) 96 | 97 | # Output results 98 | # ============== 99 | 100 | output = { 101 | "Results": [], 102 | # { 103 | # "a": Number, 104 | # "b": Number, 105 | # "Valid": Boolean, 106 | # "Occurrences": Number, 107 | # "Percentage of results": Number 108 | # } 109 | "Timing": { 110 | "Actual": { 111 | "QPU processing time": None # microseconds 112 | } 113 | }, 114 | "Number of reads": None 115 | } 116 | 117 | # multiplication_circuit() creates these variables 118 | a_vars = ['a0', 'a1', 'a2'] 119 | b_vars = ['b0', 'b1', 'b2'] 120 | 121 | results_dict = OrderedDict() 122 | for sample, num_occurrences in sampleset.data(['sample', 'num_occurrences']): 123 | # Convert A and B from binary to decimal 124 | a = b = 0 125 | for lbl in reversed(a_vars): 126 | a = (a << 1) | sample[lbl] 127 | for lbl in reversed(b_vars): 128 | b = (b << 1) | sample[lbl] 129 | # Cast from numpy.int to int 130 | a, b = int(a), int(b) 131 | # Aggregate results by unique A and B values (ignoring internal circuit variables) 132 | if (a, b, P) in results_dict: 133 | results_dict[(a, b, P)]["Occurrences"] += num_occurrences 134 | results_dict[(a, b, P)]["Percentage of results"] = 100 * \ 135 | results_dict[(a, b, P)]["Occurrences"] / num_reads 136 | else: 137 | results_dict[(a, b, P)] = {"a": a, 138 | "b": b, 139 | "Valid": a * b == P, 140 | "Occurrences": num_occurrences, 141 | "Percentage of results": 100 * num_occurrences / num_reads} 142 | 143 | output['Results'] = list(results_dict.values()) 144 | output['Number of reads'] = num_reads 145 | 146 | output['Timing']['Actual']['QPU processing time'] = sampleset.info['timing']['qpu_access_time'] 147 | 148 | return output 149 | 150 | def display_output(output): 151 | header1_str = 'Factors Valid? Percentage of Occurrences' 152 | header2_str = ' ' * header1_str.index('P') + 'Numeric & Graphic Representation' 153 | total_width = 80 # Assumed total console width 154 | # Width available to draw bars: 155 | available_width = total_width - header1_str.index('P') - 4 156 | 157 | header_len = max(len(header1_str), len(header2_str)) 158 | print('-'*header_len) 159 | print(header1_str) 160 | print(header2_str) 161 | print('-'*header_len) 162 | 163 | for result in output['Results']: 164 | percentage = result['Percentage of results'] 165 | print('({:3},{:3}) {:3} {:3.0f} '.format(result['a'], result['b'], 'Yes' if result['Valid'] else '', percentage), end='') 166 | nbars = int(percentage/100 * available_width) 167 | print('*' * nbars) 168 | 169 | 170 | if __name__ == '__main__': 171 | # get input from user 172 | print("Enter a number to be factored:") 173 | P = sanitised_input("product", "P", range(2 ** 6)) 174 | 175 | # send problem to QPU 176 | print("Running on QPU") 177 | output = factor(P) 178 | 179 | # output results 180 | display_output(output) 181 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | dwave-ocean-sdk>=3.3.0 2 | -------------------------------------------------------------------------------- /tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dwave-examples/factoring/54e4123ad2ade7a0c1bc57dac63f40c825a81579/tests/__init__.py -------------------------------------------------------------------------------- /tests/test_integration.py: -------------------------------------------------------------------------------- 1 | # Copyright 2020 D-Wave Systems 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 | 15 | from subprocess import Popen, PIPE,STDOUT 16 | import os 17 | import sys 18 | import unittest 19 | import re 20 | import ast 21 | 22 | from dwave.cloud.utils import retried 23 | 24 | project_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 25 | 26 | class IntegrationTests(unittest.TestCase): 27 | @unittest.skipIf(os.getenv('SKIP_INT_TESTS'), "Skipping integration test.") 28 | @retried(2) 29 | def test_factoring(self): 30 | demo_file = os.path.join(project_dir, 'demo.py') 31 | p = Popen([sys.executable, demo_file], stdout=PIPE, stdin=PIPE, stderr=STDOUT) 32 | p.stdin.write(b'49\n') 33 | output = p.communicate()[0] 34 | output = output.decode(encoding='UTF-8') 35 | if os.getenv('DEBUG_OUTPUT'): 36 | print("Example output \n"+ output) 37 | 38 | best_line = re.search('^(\([^\n]*)', output, re.M).group(0) 39 | best_factors = re.search('(\([^a-z]*)', best_line, re.I).group(0) 40 | 41 | with self.subTest(msg="Verify output contains factor (7,7)"): 42 | self.assertEqual(ast.literal_eval(best_factors), (7,7)) 43 | with self.subTest(msg="Verify output contains valid result"): 44 | self.assertIn("Yes", best_line) 45 | 46 | if __name__ == '__main__': 47 | unittest.main() 48 | -------------------------------------------------------------------------------- /tests/test_interfaces.py: -------------------------------------------------------------------------------- 1 | # Copyright 2018 D-Wave Systems 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 | 15 | import unittest 16 | from random import randint 17 | from dwave.cloud.utils import retried 18 | 19 | from demo import factor 20 | 21 | class TestInterfaces(unittest.TestCase): 22 | 23 | def test_factor_invalid(self): 24 | for P in [-1, 64, 'a']: 25 | self.assertRaises(ValueError, factor, P) 26 | 27 | @retried(2) 28 | def test_factor_validity(self): 29 | for P in [12, 21, 49]: # {a*b for a in range(2**3) for b in range(2**3)}: 30 | output = factor(P) 31 | self.assertTrue(output['Results'][0]['Valid']) 32 | --------------------------------------------------------------------------------