ommx-dwave-adapter 0.0.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,62 @@
1
+ name: Documents
2
+
3
+ on:
4
+ push:
5
+ branches:
6
+ - main
7
+ workflow_dispatch:
8
+
9
+ permissions:
10
+ contents: read
11
+ pages: write
12
+ id-token: write
13
+
14
+ jobs:
15
+ build:
16
+ runs-on: ubuntu-latest
17
+ steps:
18
+ - name: Checkout
19
+ uses: actions/checkout@v4
20
+
21
+ - name: Setup Python
22
+ uses: actions/setup-python@v5
23
+ with:
24
+ python-version: "3.9"
25
+
26
+ - name: Install dependencies
27
+ run: pip install ".[dev]"
28
+
29
+ - name: Build documentation
30
+ run: sphinx-build -b html ./docs/source ./docs/build
31
+
32
+ - name: Upload HTML
33
+ uses: actions/upload-artifact@v4
34
+ with:
35
+ name: docs
36
+ path: ./docs/build
37
+ retention-days: 30
38
+
39
+ deploy:
40
+ needs: build
41
+ environment:
42
+ name: github-pages
43
+ url: ${{ steps.deployment.outputs.page_url }}
44
+ runs-on: ubuntu-latest
45
+ steps:
46
+ - name: Download HTML
47
+ uses: actions/download-artifact@v4
48
+ with:
49
+ name: docs
50
+ path: .
51
+
52
+ - name: Configure GitHub Pages
53
+ uses: actions/configure-pages@v5
54
+
55
+ - name: Upload artifact
56
+ uses: actions/upload-pages-artifact@v3
57
+ with:
58
+ path: "."
59
+
60
+ - name: Deploy to GitHub Pages
61
+ id: deployment
62
+ uses: actions/deploy-pages@v4
@@ -0,0 +1,47 @@
1
+ name: Release
2
+
3
+ on:
4
+ push:
5
+ tags:
6
+ - "*"
7
+ workflow_dispatch:
8
+
9
+ jobs:
10
+ build:
11
+ runs-on: ubuntu-latest
12
+ steps:
13
+ - name: Checkout
14
+ uses: actions/checkout@v4
15
+
16
+ - name: Setup Python
17
+ uses: actions/setup-python@v5
18
+ with:
19
+ python-version: "3.9"
20
+
21
+ - name: Build wheel
22
+ run: |
23
+ python -m pip install --upgrade pip build
24
+ python -m build --sdist --outdir ./dist .
25
+
26
+ - name: Upload
27
+ uses: actions/upload-artifact@v4
28
+ with:
29
+ name: wheel
30
+ path: ./dist/
31
+ retention-days: 30
32
+
33
+ publish:
34
+ runs-on: ubuntu-latest
35
+ permissions:
36
+ id-token: write
37
+ needs: [build]
38
+ steps:
39
+ - name: Download artifact
40
+ uses: actions/download-artifact@v4
41
+ with:
42
+ path: dist
43
+ pattern: "*"
44
+ merge-multiple: true
45
+
46
+ - name: Upload wheels to PyPI
47
+ uses: pypa/gh-action-pypi-publish@release/v1
@@ -0,0 +1,47 @@
1
+ name: test
2
+
3
+ on:
4
+ push:
5
+ branches: [main]
6
+ pull_request:
7
+ workflow_dispatch:
8
+
9
+ jobs:
10
+ test:
11
+ runs-on: ubuntu-latest
12
+ strategy:
13
+ fail-fast: false
14
+ matrix:
15
+ python-version: ["3.9", "3.10", "3.11", "3.12"]
16
+ steps:
17
+ - uses: actions/checkout@v4
18
+
19
+ - name: Setup Python ${{ matrix.python-version }}
20
+ uses: actions/setup-python@v5
21
+ with:
22
+ python-version: ${{ matrix.python-version }}
23
+
24
+ - name: Install Dependencies
25
+ run: |
26
+ pip install ".[dev]"
27
+ pip install pytest-github-actions-annotate-failures
28
+
29
+ - name: Type check
30
+ if: always()
31
+ run: |
32
+ pyright
33
+
34
+ - name: Lint
35
+ if: always()
36
+ run: |
37
+ ruff check
38
+
39
+ - name: Check format
40
+ if: always()
41
+ run: |
42
+ ruff format --check
43
+
44
+ - name: Run Tests
45
+ if: always()
46
+ run: |
47
+ pytest --doctest-modules -vv
@@ -0,0 +1,171 @@
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
+ build/
12
+ develop-eggs/
13
+ dist/
14
+ downloads/
15
+ eggs/
16
+ .eggs/
17
+ lib/
18
+ lib64/
19
+ parts/
20
+ sdist/
21
+ var/
22
+ wheels/
23
+ share/python-wheels/
24
+ *.egg-info/
25
+ .installed.cfg
26
+ *.egg
27
+ MANIFEST
28
+
29
+ # PyInstaller
30
+ # Usually these files are written by a python script from a template
31
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
32
+ *.manifest
33
+ *.spec
34
+
35
+ # Installer logs
36
+ pip-log.txt
37
+ pip-delete-this-directory.txt
38
+
39
+ # Unit test / coverage reports
40
+ htmlcov/
41
+ .tox/
42
+ .nox/
43
+ .coverage
44
+ .coverage.*
45
+ .cache
46
+ nosetests.xml
47
+ coverage.xml
48
+ *.cover
49
+ *.py,cover
50
+ .hypothesis/
51
+ .pytest_cache/
52
+ cover/
53
+
54
+ # Translations
55
+ *.mo
56
+ *.pot
57
+
58
+ # Django stuff:
59
+ *.log
60
+ local_settings.py
61
+ db.sqlite3
62
+ db.sqlite3-journal
63
+
64
+ # Flask stuff:
65
+ instance/
66
+ .webassets-cache
67
+
68
+ # Scrapy stuff:
69
+ .scrapy
70
+
71
+ # Sphinx documentation
72
+ docs/_build/
73
+
74
+ # PyBuilder
75
+ .pybuilder/
76
+ target/
77
+
78
+ # Jupyter Notebook
79
+ .ipynb_checkpoints
80
+
81
+ # IPython
82
+ profile_default/
83
+ ipython_config.py
84
+
85
+ # pyenv
86
+ # For a library or package, you might want to ignore these files since the code is
87
+ # intended to run in multiple environments; otherwise, check them in:
88
+ # .python-version
89
+
90
+ # pipenv
91
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
92
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
93
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
94
+ # install all needed dependencies.
95
+ #Pipfile.lock
96
+
97
+ # UV
98
+ # Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.
99
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
100
+ # commonly ignored for libraries.
101
+ #uv.lock
102
+
103
+ # poetry
104
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
105
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
106
+ # commonly ignored for libraries.
107
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
108
+ #poetry.lock
109
+
110
+ # pdm
111
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
112
+ #pdm.lock
113
+ # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
114
+ # in version control.
115
+ # https://pdm.fming.dev/latest/usage/project/#working-with-version-control
116
+ .pdm.toml
117
+ .pdm-python
118
+ .pdm-build/
119
+
120
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
121
+ __pypackages__/
122
+
123
+ # Celery stuff
124
+ celerybeat-schedule
125
+ celerybeat.pid
126
+
127
+ # SageMath parsed files
128
+ *.sage.py
129
+
130
+ # Environments
131
+ .env
132
+ .venv
133
+ env/
134
+ venv/
135
+ ENV/
136
+ env.bak/
137
+ venv.bak/
138
+
139
+ # Spyder project settings
140
+ .spyderproject
141
+ .spyproject
142
+
143
+ # Rope project settings
144
+ .ropeproject
145
+
146
+ # mkdocs documentation
147
+ /site
148
+
149
+ # mypy
150
+ .mypy_cache/
151
+ .dmypy.json
152
+ dmypy.json
153
+
154
+ # Pyre type checker
155
+ .pyre/
156
+
157
+ # pytype static type analyzer
158
+ .pytype/
159
+
160
+ # Cython debug symbols
161
+ cython_debug/
162
+
163
+ # PyCharm
164
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
165
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
166
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
167
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
168
+ #.idea/
169
+
170
+ # PyPI configuration file
171
+ .pypirc
@@ -0,0 +1,201 @@
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.
@@ -0,0 +1,61 @@
1
+ Metadata-Version: 2.4
2
+ Name: ommx_dwave_adapter
3
+ Version: 0.0.0
4
+ Summary: An adapter between OMMX and DWave
5
+ Author-email: "Jij Inc." <info@j-ij.com>
6
+ Classifier: Programming Language :: Python :: 3 :: Only
7
+ Classifier: Programming Language :: Python :: 3.9
8
+ Classifier: Programming Language :: Python :: 3.10
9
+ Classifier: Programming Language :: Python :: 3.11
10
+ Classifier: Programming Language :: Python :: 3.12
11
+ Classifier: License :: OSI Approved :: Apache Software License
12
+ Requires-Python: >=3.9
13
+ Description-Content-Type: text/markdown
14
+ License-File: LICENSE
15
+ Requires-Dist: ommx<2.0.0,>=1.8.5
16
+ Requires-Dist: dwave-system>=1.29.1
17
+ Provides-Extra: dev
18
+ Requires-Dist: pyright; extra == "dev"
19
+ Requires-Dist: pytest; extra == "dev"
20
+ Requires-Dist: ruff; extra == "dev"
21
+ Requires-Dist: sphinx; extra == "dev"
22
+ Requires-Dist: sphinx-autoapi; extra == "dev"
23
+ Requires-Dist: sphinx_fontawesome; extra == "dev"
24
+ Requires-Dist: sphinx_rtd_theme; extra == "dev"
25
+ Dynamic: license-file
26
+
27
+ # ommx-dwave-adapter
28
+
29
+ Provides an adapter to translate between [OMMX](https://github.com/Jij-Inc/ommx) and [D-Wave](https://docs.ocean.dwavesys.com/en/stable/index.html) samplers.
30
+
31
+ Currently only implements an adapter to LeapHybridCQMSampler.
32
+
33
+ # Usage
34
+
35
+ `ommx-dwave-adapter` can be installed from PyPI as follows:
36
+
37
+ ```bash
38
+ pip install ommx-dwave-adapter
39
+ ```
40
+
41
+ An example usage of the LeapHybridCQMSampler through this adapter:
42
+
43
+ ```python
44
+ from ommx_dwave_adapter import OMMXLeapHybridCQMAdapter
45
+ from ommx.v1 import Instance, DecisionVariable
46
+
47
+ x1 = DecisionVariable.integer(1, lower=0, upper=5)
48
+ ommx_instance = Instance.from_components(
49
+ decision_variables=[x1],
50
+ objective=x1,
51
+ constraints=[],
52
+ sense=Instance.MINIMIZE,
53
+ )
54
+
55
+ # Create `ommx.v1.SampleSet` through `diwave.system.LeapHybridCQMSampler`
56
+ # Your Leap token can be set through configuration file, environment variable,
57
+ # or passed with a `token` parameter.
58
+ ommx_sampleset = OMMLeapHybridCQMAdapter.sample(ommx_instance)
59
+
60
+ print(ommx_sampleset)
61
+ ```
@@ -0,0 +1,35 @@
1
+ # ommx-dwave-adapter
2
+
3
+ Provides an adapter to translate between [OMMX](https://github.com/Jij-Inc/ommx) and [D-Wave](https://docs.ocean.dwavesys.com/en/stable/index.html) samplers.
4
+
5
+ Currently only implements an adapter to LeapHybridCQMSampler.
6
+
7
+ # Usage
8
+
9
+ `ommx-dwave-adapter` can be installed from PyPI as follows:
10
+
11
+ ```bash
12
+ pip install ommx-dwave-adapter
13
+ ```
14
+
15
+ An example usage of the LeapHybridCQMSampler through this adapter:
16
+
17
+ ```python
18
+ from ommx_dwave_adapter import OMMXLeapHybridCQMAdapter
19
+ from ommx.v1 import Instance, DecisionVariable
20
+
21
+ x1 = DecisionVariable.integer(1, lower=0, upper=5)
22
+ ommx_instance = Instance.from_components(
23
+ decision_variables=[x1],
24
+ objective=x1,
25
+ constraints=[],
26
+ sense=Instance.MINIMIZE,
27
+ )
28
+
29
+ # Create `ommx.v1.SampleSet` through `diwave.system.LeapHybridCQMSampler`
30
+ # Your Leap token can be set through configuration file, environment variable,
31
+ # or passed with a `token` parameter.
32
+ ommx_sampleset = OMMLeapHybridCQMAdapter.sample(ommx_instance)
33
+
34
+ print(ommx_sampleset)
35
+ ```
@@ -0,0 +1,4 @@
1
+ from .adapter import OMMXLeapHybridCQMAdapter
2
+ from .exception import OMMXDWaveAdapterError
3
+
4
+ __all__ = ["OMMXLeapHybridCQMAdapter", "OMMXDWaveAdapterError"]
@@ -0,0 +1,289 @@
1
+ from ommx.adapter import SamplerAdapter
2
+ from ommx.v1 import Instance, SampleSet, Solution, DecisionVariable, Constraint
3
+ from ommx.v1.linear_pb2 import Linear
4
+ from ommx.v1.quadratic_pb2 import Quadratic
5
+
6
+ import math
7
+ import dimod
8
+ from dimod import ConstrainedQuadraticModel
9
+ from dwave.system import LeapHybridCQMSampler
10
+ from typing import Optional
11
+
12
+ from .exception import OMMXDWaveAdapterError
13
+
14
+
15
+ class OMMXLeapHybridCQMAdapter(SamplerAdapter):
16
+ def __init__(self, ommx_instance: Instance):
17
+ """
18
+ :param ommx_instance: The ommx.v1.Instance to sample.
19
+ """
20
+ self.instance = ommx_instance
21
+ self.model = ConstrainedQuadraticModel()
22
+
23
+ self._set_decision_variables()
24
+ self._set_objective()
25
+ self._set_constraints()
26
+
27
+ @classmethod
28
+ def sample(
29
+ cls,
30
+ ommx_instance: Instance,
31
+ *,
32
+ token: Optional[str] = None,
33
+ time_limit: Optional[int] = None,
34
+ label: Optional[str] = None,
35
+ ) -> SampleSet:
36
+ """Solve the given ommx.v1.Instance using dwave's LeapHybridCQMSampler,
37
+ returning the samples as an ommx.v1.SampleSet.
38
+
39
+ **NOTE** The `token` must be specified either through the optional
40
+ parameter or the DWave config file. Refer to DWave documentation for
41
+ more info.
42
+
43
+ :param ommx_instance: The ommx.v1.Instance to solve.
44
+ :param token: Token for instantiating the DWave sampler, obtained from your Leap account.
45
+ :param time_limit: Maximum time the solver will use, in seconds. Must be greater than the minimum time limit specified by DWave (currently 5)
46
+ :param label: Optional label to tag the problem with.
47
+
48
+ Example:
49
+ =========
50
+ The following example shows how to solve an unconstrained linear optimization problem with `x` as the objective function.
51
+
52
+ .. doctest::
53
+
54
+ >>> from ommx_dwave_adapter import OMMXLeapHybridCQMAdapter
55
+ >>> from ommx.v1 import Instance, DecisionVariable, Linear
56
+ >>>
57
+ >>> x1 = DecisionVariable.integer(1, lower=0, upper=5)
58
+ >>> ommx_instance = Instance.from_components(
59
+ ... decision_variables=[x1],
60
+ ... objective=x1,
61
+ ... constraints=[],
62
+ ... sense=Instance.MINIMIZE,
63
+ ... )
64
+ >>> token = "YOUR API TOKEN" # Set your API token
65
+ >>> solution = OMMXFixstarsAmplifyAdapter.sample(ommx_instance, token=token) # doctest: +SKIP
66
+ """
67
+ # Dwave appears to be able to read configuration from a config file
68
+ # automatically, and this apparently includes the token. Users may want
69
+ # to use the file as a way to pass the token, so we can't necessarily
70
+ # give an error on an empty token
71
+
72
+ adapter = cls(ommx_instance)
73
+ model = adapter.sampler_input
74
+ sampler = LeapHybridCQMSampler(token=token)
75
+
76
+ # TODO is this necessary or will it always just go for the minimum if no time limit is set?
77
+ if (
78
+ time_limit is None
79
+ or time_limit < sampler.properties["minimum_time_limit_s"]
80
+ ):
81
+ time_limit = sampler.properties["minimum_time_limit_s"]
82
+
83
+ dimod_sampleset = sampler.sample_cqm(model, time_limit=time_limit, label=label)
84
+ dimod_sampleset.resolve()
85
+
86
+ return adapter.decode_to_sampleset(dimod_sampleset)
87
+
88
+ @classmethod
89
+ def solve(
90
+ cls,
91
+ ommx_instance: Instance,
92
+ *,
93
+ token: Optional[str] = None,
94
+ time_limit: Optional[int] = None,
95
+ label: Optional[str] = None,
96
+ ) -> Solution:
97
+ """Solve the given ommx.v1.Instance using dwave's LeapHybridCQMSampler,
98
+ returning the best feasible solution as an ommx.v1.Solution.
99
+
100
+ **NOTE** The `token` must be specified either through the optional
101
+ parameter or the DWave config file. Refer to DWave documentation for
102
+ more info.
103
+
104
+ :param ommx_instance: The ommx.v1.Instance to solve.
105
+ :param token: Token for instantiating the DWave sampler, obtained from your Leap account.
106
+ :param time_limit: Maximum time the solver will use, in seconds. Must be greater than the minimum time limit specified by DWave (currently 5)
107
+ :param label: Optional label to tag the problem with.
108
+
109
+ Example:
110
+ =========
111
+ The following example shows how to solve an unconstrained linear optimization problem with `x` as the objective function.
112
+
113
+ .. doctest::
114
+
115
+ >>> from ommx_dwave_adapter import OMMXLeapHybridCQMAdapter
116
+ >>> from ommx.v1 import Instance, DecisionVariable, Linear
117
+ >>>
118
+ >>> x1 = DecisionVariable.integer(1, lower=0, upper=5)
119
+ >>> ommx_instance = Instance.from_components(
120
+ ... decision_variables=[x1],
121
+ ... objective=x1,
122
+ ... constraints=[],
123
+ ... sense=Instance.MINIMIZE,
124
+ ... )
125
+ >>> token = "YOUR API TOKEN" # Set your API token
126
+ >>> solution = OMMXFixstarsAmplifyAdapter.solve(ommx_instance, token=token) # doctest: +SKIP
127
+ """
128
+ return cls.sample(
129
+ ommx_instance, token=token, time_limit=time_limit, label=label
130
+ ).best_feasible()
131
+
132
+ @property
133
+ def sampler_input(self) -> ConstrainedQuadraticModel:
134
+ """The dimod.ConstrainedQuadraticModel representing this OMMX instance"""
135
+ return self.model
136
+
137
+ def decode_to_sampleset(self, data: dimod.SampleSet) -> SampleSet:
138
+ """Convert a dimod.SampleSet model matching this instance to an ommx.v1.SampleSet.
139
+
140
+ This method is intended to be used if the model has been acquired with
141
+ `sampler_input` for futher adjustment of the sampler parameters, and
142
+ separately optimizing the model.
143
+
144
+ Note that alterations to the model may make the decoding process
145
+ incompatible -- decoding will only work if the model still describes
146
+ effectively the same problem as the OMMX instance used to create the
147
+ adapter.
148
+
149
+ Example:
150
+ =========
151
+ The following example shows how to solve an unconstrained linear optimization problem with `x` as the objective function.
152
+
153
+ .. doctest::
154
+
155
+ >>> from ommx_dwave_adapter import OMMXLeapHybridCQMAdapter
156
+ >>> from ommx.v1 import Instance, DecisionVariable, Linear
157
+ >>> from dwave.system import LeapHybridCQMSampler
158
+ >>> x1 = DecisionVariable.integer(1, lower=0, upper=5)
159
+ >>> ommx_instance = Instance.from_components(
160
+ ... decision_variables=[x1],
161
+ ... objective=x1,
162
+ ... constraints=[],
163
+ ... sense=Instance.MINIMIZE,
164
+ ... )
165
+ >>>
166
+ >>> adapter = OMMXLeapHybridCQMAdapter(ommx_instance)
167
+ >>> model = adapter.sampler_input # obtain dimod.ConstrainedQuadraticModel
168
+ >>> sampler = LeapHybridCQMSampler() # doctest: +SKIP
169
+ >>> # ... some modification of the sampler parameters
170
+ >>> dimod_sampleset = sampler.sample_cqm(model) # doctest: +SKIP
171
+ >>> sample = adapter.decode_to_sampleset(dimod_sampleset) # doctest: +SKIP
172
+ """
173
+ # the only type info we have with vars in data.variables is that they're
174
+ # Hashable. We know they are integers but we hash them anyway for type
175
+ # safety. As we stored our variables as integer the hash should still be
176
+ # our IDs
177
+ samples = {
178
+ i: {
179
+ var.__hash__(): float(coeff)
180
+ for var, coeff in zip(data.variables, sample)
181
+ }
182
+ for i, sample in enumerate(data.record.sample)
183
+ }
184
+ return self.instance.evaluate_samples(samples)
185
+
186
+ def _set_decision_variables(self):
187
+ for var in self.instance.raw.decision_variables:
188
+ if var.kind == DecisionVariable.BINARY:
189
+ self.model.add_variable("BINARY", var.id)
190
+ elif var.kind == DecisionVariable.INTEGER:
191
+ self.model.add_variable(
192
+ "INTEGER",
193
+ var.id,
194
+ lower_bound=var.bound.lower,
195
+ upper_bound=var.bound.upper,
196
+ )
197
+ elif var.kind == DecisionVariable.CONTINUOUS:
198
+ self.model.add_variable(
199
+ "REAL",
200
+ var.id,
201
+ lower_bound=var.bound.lower,
202
+ upper_bound=var.bound.upper,
203
+ )
204
+ else:
205
+ raise OMMXDWaveAdapterError(
206
+ f"Unsupported decision variable kind: "
207
+ f"id: {var.id}, kind: {var.kind}"
208
+ )
209
+
210
+ def _set_objective(self):
211
+ objective = self.instance.raw.objective
212
+
213
+ if objective.HasField("constant"):
214
+ self.model.set_objective([(objective.constant,)])
215
+ return
216
+ elif objective.HasField("linear"):
217
+ expr = self._make_linear_expr(objective.linear)
218
+ self.model.set_objective(expr)
219
+ elif objective.HasField("quadratic"):
220
+ expr = self._make_quadratic_expr(objective.quadratic)
221
+ self.model.set_objective(expr)
222
+ else:
223
+ raise OMMXDWaveAdapterError(
224
+ f"Unsupport objective function type: must be either `constant`, `linear` or `quadratic`."
225
+ f"type: {objective.WhichOneof('function')}"
226
+ )
227
+
228
+ if self.instance.raw.sense == Instance.MAXIMIZE:
229
+ # multiply all coefficients by -1:
230
+ # this takes all except the last element from the tuple and concatenates it
231
+ # with the last element multiplied with -1 to get a new tuple
232
+ expr = [tuple[:-1] + (-1 * tuple[-1],) for tuple in expr]
233
+ self.model.set_objective(expr)
234
+
235
+ def _set_constraints(self):
236
+ for constraint in self.instance.raw.constraints:
237
+ if constraint.function.HasField("linear"):
238
+ expr = self._make_linear_expr(constraint.function.linear)
239
+ elif constraint.function.HasField("quadratic"):
240
+ expr = self._make_quadratic_expr(constraint.function.quadratic)
241
+ elif constraint.function.HasField("constant"):
242
+ if constraint.equality == Constraint.EQUAL_TO_ZERO and math.isclose(
243
+ constraint.function.constant, 0, abs_tol=1e-6
244
+ ):
245
+ continue
246
+ elif (
247
+ constraint.equality == Constraint.LESS_THAN_OR_EQUAL_TO_ZERO
248
+ and constraint.function.constant <= 1e-6
249
+ ):
250
+ continue
251
+ else:
252
+ raise OMMXDWaveAdapterError(
253
+ f"Infeasible constant constraint was found: id {constraint.id}"
254
+ )
255
+ else:
256
+ raise OMMXDWaveAdapterError(
257
+ f"Constraints must be either `constant`, `linear` or `quadratic`."
258
+ f"id: {constraint.id}, "
259
+ f"type: {constraint.function.WhichOneof('function')}"
260
+ )
261
+
262
+ if constraint.equality == Constraint.EQUAL_TO_ZERO:
263
+ constr_sense = "=="
264
+ elif constraint.equality == Constraint.LESS_THAN_OR_EQUAL_TO_ZERO:
265
+ constr_sense = "<="
266
+ else:
267
+ raise OMMXDWaveAdapterError(
268
+ f"Unsupported constraint equality: "
269
+ f"id: {constraint.id}, equality: {constraint.equality}"
270
+ )
271
+
272
+ # rhs is assumed 0 by dwave
273
+ self.model.add_constraint_from_iterable(
274
+ expr, constr_sense, label=constraint.id
275
+ )
276
+
277
+ def _make_linear_expr(self, linear: Linear):
278
+ # we transform our expression into a list of tuples.
279
+ # Each tuple is all the variable IDs used in a term, followed by the coefficient of that term.
280
+ tuples = [(term.id, term.coefficient) for term in linear.terms]
281
+ return tuples + [(linear.constant,)]
282
+
283
+ def _make_quadratic_expr(self, quad: Quadratic):
284
+ quad_tuples = [
285
+ (row, column, value)
286
+ for row, column, value in zip(quad.rows, quad.columns, quad.values)
287
+ ]
288
+ linear_tuples = [(term.id, term.coefficient) for term in quad.linear.terms]
289
+ return quad_tuples + linear_tuples + [(quad.linear.constant,)]
@@ -0,0 +1,2 @@
1
+ class OMMXDWaveAdapterError(Exception):
2
+ pass
@@ -0,0 +1,61 @@
1
+ Metadata-Version: 2.4
2
+ Name: ommx_dwave_adapter
3
+ Version: 0.0.0
4
+ Summary: An adapter between OMMX and DWave
5
+ Author-email: "Jij Inc." <info@j-ij.com>
6
+ Classifier: Programming Language :: Python :: 3 :: Only
7
+ Classifier: Programming Language :: Python :: 3.9
8
+ Classifier: Programming Language :: Python :: 3.10
9
+ Classifier: Programming Language :: Python :: 3.11
10
+ Classifier: Programming Language :: Python :: 3.12
11
+ Classifier: License :: OSI Approved :: Apache Software License
12
+ Requires-Python: >=3.9
13
+ Description-Content-Type: text/markdown
14
+ License-File: LICENSE
15
+ Requires-Dist: ommx<2.0.0,>=1.8.5
16
+ Requires-Dist: dwave-system>=1.29.1
17
+ Provides-Extra: dev
18
+ Requires-Dist: pyright; extra == "dev"
19
+ Requires-Dist: pytest; extra == "dev"
20
+ Requires-Dist: ruff; extra == "dev"
21
+ Requires-Dist: sphinx; extra == "dev"
22
+ Requires-Dist: sphinx-autoapi; extra == "dev"
23
+ Requires-Dist: sphinx_fontawesome; extra == "dev"
24
+ Requires-Dist: sphinx_rtd_theme; extra == "dev"
25
+ Dynamic: license-file
26
+
27
+ # ommx-dwave-adapter
28
+
29
+ Provides an adapter to translate between [OMMX](https://github.com/Jij-Inc/ommx) and [D-Wave](https://docs.ocean.dwavesys.com/en/stable/index.html) samplers.
30
+
31
+ Currently only implements an adapter to LeapHybridCQMSampler.
32
+
33
+ # Usage
34
+
35
+ `ommx-dwave-adapter` can be installed from PyPI as follows:
36
+
37
+ ```bash
38
+ pip install ommx-dwave-adapter
39
+ ```
40
+
41
+ An example usage of the LeapHybridCQMSampler through this adapter:
42
+
43
+ ```python
44
+ from ommx_dwave_adapter import OMMXLeapHybridCQMAdapter
45
+ from ommx.v1 import Instance, DecisionVariable
46
+
47
+ x1 = DecisionVariable.integer(1, lower=0, upper=5)
48
+ ommx_instance = Instance.from_components(
49
+ decision_variables=[x1],
50
+ objective=x1,
51
+ constraints=[],
52
+ sense=Instance.MINIMIZE,
53
+ )
54
+
55
+ # Create `ommx.v1.SampleSet` through `diwave.system.LeapHybridCQMSampler`
56
+ # Your Leap token can be set through configuration file, environment variable,
57
+ # or passed with a `token` parameter.
58
+ ommx_sampleset = OMMLeapHybridCQMAdapter.sample(ommx_instance)
59
+
60
+ print(ommx_sampleset)
61
+ ```
@@ -0,0 +1,16 @@
1
+ .gitignore
2
+ LICENSE
3
+ README.md
4
+ pyproject.toml
5
+ .github/workflows/docs.yml
6
+ .github/workflows/release.yml
7
+ .github/workflows/test.yaml
8
+ ommx_dwave_adapter/__init__.py
9
+ ommx_dwave_adapter/adapter.py
10
+ ommx_dwave_adapter/exception.py
11
+ ommx_dwave_adapter.egg-info/PKG-INFO
12
+ ommx_dwave_adapter.egg-info/SOURCES.txt
13
+ ommx_dwave_adapter.egg-info/dependency_links.txt
14
+ ommx_dwave_adapter.egg-info/requires.txt
15
+ ommx_dwave_adapter.egg-info/top_level.txt
16
+ tests/test_cqm_adapter.py
@@ -0,0 +1,11 @@
1
+ ommx<2.0.0,>=1.8.5
2
+ dwave-system>=1.29.1
3
+
4
+ [dev]
5
+ pyright
6
+ pytest
7
+ ruff
8
+ sphinx
9
+ sphinx-autoapi
10
+ sphinx_fontawesome
11
+ sphinx_rtd_theme
@@ -0,0 +1 @@
1
+ ommx_dwave_adapter
@@ -0,0 +1,37 @@
1
+ [build-system]
2
+ requires = ["setuptools>=64", "setuptools_scm>=8", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "ommx_dwave_adapter"
7
+ dynamic = ["version"]
8
+ description = "An adapter between OMMX and DWave"
9
+ authors = [
10
+ { name = "Jij Inc.", email = "info@j-ij.com" }
11
+ ]
12
+ readme = "README.md"
13
+ requires-python = ">= 3.9"
14
+ classifiers = [
15
+ "Programming Language :: Python :: 3 :: Only",
16
+ "Programming Language :: Python :: 3.9",
17
+ "Programming Language :: Python :: 3.10",
18
+ "Programming Language :: Python :: 3.11",
19
+ "Programming Language :: Python :: 3.12",
20
+ "License :: OSI Approved :: Apache Software License",
21
+ ]
22
+
23
+ dependencies = [
24
+ "ommx >= 1.8.5, < 2.0.0",
25
+ "dwave-system>=1.29.1",
26
+ ]
27
+
28
+ [project.optional-dependencies]
29
+ dev = [
30
+ "pyright",
31
+ "pytest",
32
+ "ruff",
33
+ "sphinx",
34
+ "sphinx-autoapi",
35
+ "sphinx_fontawesome",
36
+ "sphinx_rtd_theme",
37
+ ]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,127 @@
1
+ from ommx.v1 import Instance, DecisionVariable, Polynomial, Function
2
+ from dimod.sym import Sense
3
+ import dimod
4
+ import pytest
5
+
6
+ from ommx_dwave_adapter import OMMXLeapHybridCQMAdapter, OMMXDWaveAdapterError
7
+
8
+
9
+ def test_instance_to_cqm_model():
10
+ # simple knapsack problem
11
+ p = [10, 13, 18, 31, 7, 15]
12
+ w = [11, 25, 20, 35, 10, 33]
13
+ W = 47
14
+ N = len(p)
15
+
16
+ x = [
17
+ DecisionVariable.binary(
18
+ id=i,
19
+ name="x",
20
+ subscripts=[i],
21
+ )
22
+ for i in range(N)
23
+ ]
24
+ constraints = [Function(sum(w[i] * x[i] for i in range(N))) <= W]
25
+ instance = Instance.from_components(
26
+ decision_variables=x,
27
+ objective=sum(p[i] * x[i] for i in range(N)),
28
+ constraints=constraints,
29
+ sense=Instance.MAXIMIZE,
30
+ )
31
+ adapter = OMMXLeapHybridCQMAdapter(instance)
32
+ model = adapter.solver_input
33
+ assert model.vartype(x[0].id) == dimod.BINARY
34
+ assert list(model.variables) == [var.id for var in x]
35
+
36
+ assert model.objective.quadratic == {}
37
+ # MAXIMIZE check: dwave only minimizes, so all coefficients must have had their sign changed
38
+ assert model.objective.linear == {x[i].id: -p[i] for i in range(N)}
39
+ assert model.objective.offset == 0.0
40
+
41
+ assert model.constraints[0].sense == Sense.Le
42
+ assert model.constraints[0].lhs.offset == -W
43
+ assert model.constraints[0].lhs.linear == {x[i].id: w[i] for i in range(N)}
44
+ assert model.constraints[0].rhs == 0
45
+
46
+
47
+ def test_error_on_unsupported_function():
48
+ decision_variables = [
49
+ DecisionVariable.of_type(
50
+ kind=DecisionVariable.BINARY, id=0, lower=0, upper=1, name="x"
51
+ ),
52
+ DecisionVariable.of_type(
53
+ kind=DecisionVariable.INTEGER,
54
+ id=1,
55
+ lower=-20.0,
56
+ upper=20.0,
57
+ name="y",
58
+ subscripts=[],
59
+ ),
60
+ DecisionVariable.of_type(
61
+ kind=DecisionVariable.CONTINUOUS,
62
+ id=2,
63
+ lower=-30,
64
+ upper=30,
65
+ name="z",
66
+ subscripts=[0],
67
+ ),
68
+ DecisionVariable.of_type(
69
+ kind=DecisionVariable.CONTINUOUS,
70
+ id=3,
71
+ # TODO dwave doesn't accept -inf, +inf. how to handle this? should the adapter convert?
72
+ lower=float("-1e30"),
73
+ upper=float("1e30"),
74
+ name="w",
75
+ subscripts=[1, 2],
76
+ ),
77
+ ]
78
+ objective = Polynomial(terms={(0, 1, 2): 2.0, (1, 2): 3.0, (2,): 4.0, (): 5.0})
79
+
80
+ instance = Instance.from_components(
81
+ decision_variables=decision_variables,
82
+ objective=objective,
83
+ constraints=[],
84
+ sense=Instance.MINIMIZE,
85
+ )
86
+ with pytest.raises(OMMXDWaveAdapterError):
87
+ OMMXLeapHybridCQMAdapter(instance)
88
+
89
+
90
+ def test_decode():
91
+ p = [10, 13, 18, 31, 7, 15]
92
+ w = [11, 25, 20, 35, 10, 33]
93
+ W = 47
94
+ N = len(p)
95
+
96
+ x = [
97
+ DecisionVariable.binary(
98
+ id=i,
99
+ name="x",
100
+ subscripts=[i],
101
+ )
102
+ for i in range(N)
103
+ ]
104
+ constraints = [Function(sum(w[i] * x[i] for i in range(N))) <= W]
105
+ instance = Instance.from_components(
106
+ decision_variables=x,
107
+ objective=sum(p[i] * x[i] for i in range(N)),
108
+ constraints=constraints,
109
+ sense=Instance.MAXIMIZE,
110
+ )
111
+ adapter = OMMXLeapHybridCQMAdapter(instance)
112
+ cqm = adapter.sampler_input
113
+
114
+ # using ExactCQM solver as a testable stand-in
115
+ dimod_sampleset = dimod.ExactCQMSolver().sample_cqm(cqm)
116
+ dimod_sampleset.resolve()
117
+
118
+ sampleset = adapter.decode_to_sampleset(dimod_sampleset)
119
+ assert sampleset.raw.sense == Instance.MAXIMIZE
120
+ best = sampleset.best_feasible()
121
+ assert best.objective == 41
122
+ assert best.raw.state.entries[0] == pytest.approx(1)
123
+ assert best.raw.state.entries[1] == pytest.approx(0)
124
+ assert best.raw.state.entries[2] == pytest.approx(0)
125
+ assert best.raw.state.entries[3] == pytest.approx(1)
126
+ assert best.raw.state.entries[4] == pytest.approx(0)
127
+ assert best.raw.state.entries[5] == pytest.approx(0)