├── .circleci └── config.yml ├── .devcontainer └── devcontainer.json ├── .gitpod.yml ├── LICENSE ├── README.md ├── antennas.py ├── data ├── germany_states.cpg ├── germany_states.dbf ├── germany_states.geojson ├── germany_states.prj ├── germany_states.shp ├── germany_states.shx └── locations.txt ├── demo.py ├── readme_imgs ├── example_map.png ├── example_original.png └── example_solution.png ├── requirements.txt └── tests ├── __init__.py └── test_antennas.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 * * 4" 18 | filters: 19 | branches: 20 | only: 21 | - master 22 | - main 23 | jobs: 24 | - dwave/test-linux 25 | - dwave/test-osx 26 | - dwave/test-win 27 | -------------------------------------------------------------------------------- /.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 | -------------------------------------------------------------------------------- /.gitpod.yml: -------------------------------------------------------------------------------- 1 | tasks: 2 | - init: pip install -r requirements.txt 3 | -------------------------------------------------------------------------------- /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/antenna-selection?quickstart=1) 4 | [![Linux/Mac/Windows build status]( 5 | https://circleci.com/gh/dwave-examples/antenna-selection.svg?style=shield)]( 6 | https://circleci.com/gh/dwave-examples/antenna-selection) 7 | 8 | # Antennas Selection 9 | 10 | This code was taken from the webinar, *Quantum Programming with the Ocean Tools 11 | Suite* [[2]](#2). 12 | 13 | The graph below represents antenna coverage. Each of the seven nodes below 14 | represents an antenna with some amount of coverage. Note that the coverage 15 | provided by each antenna is identical. The edges between each node represent 16 | antennas with overlapping coverage. 17 | 18 | ![Example Original](readme_imgs/example_original.png) 19 | 20 | Problem: Given the above set of antennas, which antennas should you choose such 21 | that you maximize antenna coverage without any overlaps? 22 | 23 | Solution: One possible solution is indicated by the red nodes below. 24 | 25 | ![Example Solution](readme_imgs/example_solution.png) 26 | 27 | This problem is an example of an optimization problem known as the maximum 28 | independent set problem. Our objective is to maximize the number of nodes in a 29 | set, with the constraint that no edges be contained in the set. To solve on a 30 | D-Wave system, we can reformulate this problem as a quadratic unconstrained 31 | binary optimization problem (QUBO). There are a wide variety of applications 32 | for this problem, such as scheduling and error correcting codes (as shown in 33 | [[1]](#1)). 34 | 35 | ## Usage 36 | 37 | To run the demo: 38 | 39 | ```bash 40 | python antennas.py 41 | ``` 42 | 43 | After running, the largest independent set found in the graph will be printed 44 | to the command line and two images (.png files) will be created. An image of 45 | the original graph can be found in the file `antenna_plot_original.png`, and 46 | an image of the graph with the nodes in the independent set highlighted in a 47 | different color can be found in the file `antenna_plot_solution.png`. 48 | 49 | To run the program on a different problem, modify graph G to represent a 50 | different antenna network. 51 | 52 | ## Code Overview 53 | 54 | The program `antennas.py` creates a graph using the Python package `networkx`, 55 | and then uses the Ocean software tools to run the `maximum_independent_set` 56 | function from within the `dwave_networkx` package. 57 | 58 | ## Real-World Scenario 59 | 60 | Germany is well-known for their iconic television towers. Given the locations 61 | of existing television towers, where should new ones be built to minimize 62 | interference? Using the LeapHybridCQMSampler we can solve this problem, 63 | formulated as a constrained quadratic model (CQM) in the following way. Rather 64 | than formulating this problem as an independent set problem where no 65 | interference is tolerated, we will optimize to find the minimum amount of 66 | interference since it's unlikely that in the real-world we will be able to 67 | eliminate it entirely. 68 | 69 | ### CQM Formulation 70 | 71 | A map of Germany with the locations of 30 towers is provided, and 100 new 72 | potential tower locations are identified randomly within the country borders. 73 | 74 | Our objective is to select a subset of these potential new tower locations so 75 | that the pairwise distances between all towers (existing and new) is as large 76 | as possible. In the code, we do this by first calculating all pairwise 77 | distances. Note that if we simply sum these raw distances we might end up with 78 | a variety of distance distrubtions. For example, we might have pairs of towers 79 | with distance 1 and 9, and other pairs with distance 5 and 5, each of which has 80 | a sum of 10. In our scenario, we will prefer the pairs with distance 1 and 9. 81 | 82 | To rectify this, we square the distances before summing them. Squaring the 83 | distances provides a more even distribution. In our example, this provides us 84 | with distance sums 1+81=82 and 25+25=50, prefering the pairs with distances 1 85 | and 9 (since we are maximizing the sum). 86 | 87 | Additionally, since interference only affects towers within a certain proximity 88 | of each other, we set a cutoff radius. Every pair of towers with distance 89 | greater than the cutoff radius receives a minimum-value bias so that they are 90 | not penalized for both being selected. Each pair of towers with distance less 91 | than the cutoff radius receives a bias of the negative of the distance squared. 92 | 93 | Lastly, we add a constraint to choose exactly 10 new towers and fix the 94 | existing tower variables to have value 1.0. This ensures that the existing 95 | towers are identified as locations where towers must exist. 96 | 97 | ### Running the Demo 98 | 99 | To run the demo: 100 | 101 | ```bash 102 | python demo.py 103 | ``` 104 | 105 | Once the program has run, an image will be saved as `map.png` that visualizes 106 | the initial scenario (left) and solution (right), as shown below. 107 | 108 | ![Example Solution](readme_imgs/example_map.png) 109 | 110 | ## Further Information 111 | 112 | [1] Sergiy Butenko and Panagote M. Pardalos. "Maximum independent set and 113 | related problems, with applications." PhD dissertation, University of 114 | Florida, 2003. 115 | 116 | [2] Victoria Goliber, "Quantum Programming with the Ocean Tools Suite", 117 | https://www.youtube.com/watch?v=ckJ59gsFllU 118 | 119 | [3] Andrew Lucas, "Ising formulations of many NP problems", [doi: 120 | 10.3389/fphy.2014.00005](https://www.frontiersin.org/articles/10.3389/fphy.2014.00005/full) 121 | 122 | [4] Towers in Germany, https://www.latlong.net/category/towers-83-45.html 123 | 124 | ## License 125 | 126 | Released under the Apache License 2.0. See [LICENSE](LICENSE) file. 127 | -------------------------------------------------------------------------------- /antennas.py: -------------------------------------------------------------------------------- 1 | # Copyright 2019 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 networkx for graph tools 16 | import networkx as nx 17 | 18 | # Import dwave_networkx for d-wave graph tools/functions 19 | import dwave_networkx as dnx 20 | 21 | # Import matplotlib.pyplot to draw graphs on screen 22 | import matplotlib 23 | matplotlib.use("agg") 24 | import matplotlib.pyplot as plt 25 | 26 | # Set the solver we're going to use 27 | from dwave.system.samplers import DWaveSampler 28 | from dwave.system.composites import EmbeddingComposite 29 | 30 | sampler = EmbeddingComposite(DWaveSampler()) 31 | 32 | # Create empty graph 33 | G = nx.Graph() 34 | 35 | # Add edges to graph - this also adds the nodes 36 | G.add_edges_from([(1, 2), (1, 3), (2, 3), (3, 4), (3, 5), (4, 5), (4, 6), (5, 6), (6, 7)]) 37 | 38 | # Find the maximum independent set, S 39 | S = dnx.maximum_independent_set(G, sampler=sampler, num_reads=10, label='Example - Antenna Selection') 40 | 41 | # Print the solution for the user 42 | print('Maximum independent set size found is', len(S)) 43 | print(S) 44 | 45 | # Visualize the results 46 | k = G.subgraph(S) 47 | notS = list(set(G.nodes()) - set(S)) 48 | othersubgraph = G.subgraph(notS) 49 | pos = nx.spring_layout(G) 50 | plt.figure() 51 | 52 | # Save original problem graph 53 | original_name = "antenna_plot_original.png" 54 | nx.draw_networkx(G, pos=pos, with_labels=True) 55 | plt.savefig(original_name, bbox_inches='tight') 56 | 57 | # Save solution graph 58 | # Note: red nodes are in the set, blue nodes are not 59 | solution_name = "antenna_plot_solution.png" 60 | nx.draw_networkx(k, pos=pos, with_labels=True, node_color='r', font_color='k') 61 | nx.draw_networkx(othersubgraph, pos=pos, with_labels=True, node_color='b', font_color='w') 62 | plt.savefig(solution_name, bbox_inches='tight') 63 | 64 | print("Your plots are saved to {} and {}".format(original_name, solution_name)) 65 | -------------------------------------------------------------------------------- /data/germany_states.cpg: -------------------------------------------------------------------------------- 1 | ISO-8859-1 -------------------------------------------------------------------------------- /data/germany_states.dbf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dwave-examples/antenna-selection/f09077cea28340685002f52df0e8b8ddd7a91a4a/data/germany_states.dbf -------------------------------------------------------------------------------- /data/germany_states.prj: -------------------------------------------------------------------------------- 1 | GEOGCS["GCS_WGS_1984",DATUM["D_WGS_1984",SPHEROID["WGS_1984",6378137.0,298.257223563]],PRIMEM["Greenwich",0.0],UNIT["Degree",0.0174532925199433]] -------------------------------------------------------------------------------- /data/germany_states.shp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dwave-examples/antenna-selection/f09077cea28340685002f52df0e8b8ddd7a91a4a/data/germany_states.shp -------------------------------------------------------------------------------- /data/germany_states.shx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dwave-examples/antenna-selection/f09077cea28340685002f52df0e8b8ddd7a91a4a/data/germany_states.shx -------------------------------------------------------------------------------- /data/locations.txt: -------------------------------------------------------------------------------- 1 | Holstein Tower, Sierksdorf, Germany 54.074089 10.779130 2 | Scream (Heide Park), Soltau, Germany 53.027111 9.878511 3 | Bremerhaven Radar Tower, Bremerhaven, Germany 53.538406 8.580290 4 | Brocken Transmitter, Weringerode, Germany 51.800194 10.614367 5 | Großer Inselsberg, Thuringia, Germany 50.851246 10.465513 6 | Hohenstadt Transmission Tower, Hohenstadt, Germany 48.549782 9.670841 7 | Jakobsberg Telecommunication Tower, Germany 52.240753 8.944976 8 | Am Fallturm, Bremen, Germany 53.110493 8.858183 9 | Funkturm Berlin, Berlin, Germany 52.505032 13.278189 10 | Hünenburg Telecommunication Tower, Germany 52.014660 8.473570 11 | Bungsberg Telecommunications Tower, Germany 54.209484 10.724172 12 | Transmitter Hornisgrinde, Sasbach, Germany 48.604443 8.201944 13 | Fernmeldeturm Berlin, Schäferberg, Berlin, Germany 52.417847 13.127895 14 | Fernmeldeturm Mannheim, Germany 49.487034 8.492177 15 | Fernsehturm Stuttgart, Stuttgart, Germany 48.755749 9.190182 16 | Florianturm, Dortmund, Germany 51.496593 7.476613 17 | Fernmeldeturm Münster, Münster, Germany 51.949928 7.666372 18 | Bremer TV Tower, Bremen, Germany 53.095814 8.791273 19 | Rheinturm, Dusseldorf, Germany 51.217941 6.761680 20 | Dresden TV Tower, Dresden, Germany 51.040291 13.838788 21 | Fernmeldeturm Koblenz, Koblentz, Germany 50.309032 7.569359 22 | Colonius, Cologne, Germany 50.947086 6.931865 23 | Heinrich-Hertz-Tower, Hamburg, Germany 53.563400 9.976219 24 | Telemax Tower, Hanover, Germany 52.393013 9.799687 25 | Olympiaturm, Olympiapark, Munich, Germany 48.174419 11.553776 26 | Fernmeldeturm Nürnberg, Germany 49.426113 11.038977 27 | Europaturm, Frankfurt, Germany 50.135307 8.654652 28 | Fernsehturm Berlin, Berlin, Germany 52.520817 13.409419 29 | Rostock, Mecklenburg-Vorpommern, Germany 54.083336 12.108811 30 | Fernsehturm, Berlin, Germany 52.520645 13.409779 -------------------------------------------------------------------------------- /demo.py: -------------------------------------------------------------------------------- 1 | # Copyright 2022 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 itertools import combinations 16 | from math import asin, cos, radians, sin, sqrt 17 | 18 | import matplotlib 19 | import numpy as np 20 | import pandas as pd 21 | import shapefile 22 | from dimod import Binary, ConstrainedQuadraticModel, quicksum 23 | from dwave.system import LeapHybridCQMSampler 24 | from shapely.geometry import Point, shape 25 | from shapely.ops import unary_union 26 | 27 | try: 28 | import matplotlib.pyplot as plt 29 | except ImportError: 30 | matplotlib.use("agg") 31 | import matplotlib.pyplot as plt 32 | 33 | def distance(lat1, long1, lat2, long2): 34 | ''' Compute the distance (miles) between two lat/long points. 35 | Args: 36 | - lat1, long1: float. Lat and long of point 1. 37 | - lat2, long 2: float. Lat and long of point 2. 38 | Returns: 39 | - dist: float. Distance in miles between points. 40 | ''' 41 | # Taken from https://www.geeksforgeeks.org/program-distance-two-points-earth/ 42 | 43 | # The math module contains a function named 44 | # radians which converts from degrees to radians. 45 | long1 = radians(long1) 46 | long2 = radians(long2) 47 | lat1 = radians(lat1) 48 | lat2 = radians(lat2) 49 | 50 | # Haversine formula 51 | dlong = long2 - long1 52 | dlat = lat2 - lat1 53 | a = sin(dlat / 2)**2 + cos(lat1) * cos(lat2) * sin(dlong / 2)**2 54 | 55 | c = 2 * asin(sqrt(a)) 56 | 57 | # Radius of earth in miles 58 | r = 3956 59 | 60 | # calculate the result 61 | return(c * r) 62 | 63 | def get_existing_towers(filename): 64 | ''' Loads existing tower locations. 65 | Args: 66 | - filename: string. File name to load. 67 | Returns: 68 | - towers: df. Dataframe containing tower information. 69 | ''' 70 | 71 | with open(filename) as f: 72 | lines = f.readlines() 73 | 74 | points = [] 75 | lats = [] 76 | longs = [] 77 | for line in lines: 78 | temp = line.split("\t") 79 | points.append(temp[0]) 80 | lats.append(float(temp[1])) 81 | longs.append(float(temp[2][:-2])) 82 | 83 | towers = pd.DataFrame({'Name': points, 'Latitude': lats, 'Longitude':longs}) 84 | 85 | return towers 86 | 87 | def gen_new_points(num_new_points, region_map): 88 | ''' Generates a random set of new locations in the region. 89 | Args: 90 | - num_new_points: int. Number of random points to identify. 91 | - region_map: gdf. Region of interest. 92 | Returns: 93 | - new_locs: list of [float, float]. New points as [lat, long]. 94 | ''' 95 | 96 | # Load the map boundaries for the region 97 | polys = [shape(p) for p in region_map.shapes()] 98 | boundary = unary_union(polys) 99 | min_long, min_lat, max_long, max_lat = boundary.bounds 100 | 101 | counter = 0 102 | new_locs = [] 103 | 104 | while counter < num_new_points: 105 | new_long = (max_long - min_long) * np.random.random() + min_long 106 | new_lat = (max_lat - min_lat) * np.random.random() + min_lat 107 | point = Point(new_long, new_lat) 108 | 109 | # Check that new point is within region before appending 110 | if point.intersects(boundary): 111 | counter += 1 112 | new_locs.append([new_lat, new_long]) 113 | 114 | return new_locs 115 | 116 | def build_cqm(num_to_build, existing_towers, new_locs, radius): 117 | ''' Builds CQM for scenario. 118 | Args: 119 | - num_to_build: int. Number of new antennas to build. 120 | - existing_towers: df. Existing tower locations. 121 | - new_locs: List of [float, float]. List of potential build sites lat/long coords. 122 | - radius: int or float. Distance radius for interference. 123 | Returns: 124 | - cqm: ConstrainedQuadraticModel representing the optimization problem. 125 | ''' 126 | 127 | # Initialize model 128 | cqm = ConstrainedQuadraticModel() 129 | 130 | # Build CQM variables 131 | tower_vars = {(row['Latitude'],row['Longitude'],row['Name']): Binary(row['Name']) for _, row in existing_towers.iterrows()} 132 | new_vars = {(new_locs[n][0],new_locs[n][1]): Binary(n) for n in range(len(new_locs))} 133 | 134 | # Make a combined list of all variables to calculate objective 135 | all_vars = tower_vars.copy() 136 | all_vars.update(new_vars) 137 | 138 | # Objective: minimize interference / maximize distance 139 | pair_list = list(combinations(all_vars.keys(), 2)) 140 | dist = [distance(a[0], a[1], b[0], b[1])**2 for (a, b) in pair_list] 141 | max_dist = max(dist) 142 | biases = [dist[i] if dist[i] < radius**2 else max_dist for i in range(len(dist))] 143 | 144 | # Set the objective; negate the biases since we want to maximize 145 | cqm.set_objective(quicksum(-biases[i]*all_vars[pair_list[i][0]]*all_vars[pair_list[i][1]] for i in range(len(pair_list)))) 146 | 147 | # Constraint: build exactly num_to_build new sites 148 | cqm.add_constraint(quicksum(new_vars.values()) == num_to_build) 149 | 150 | # Fix existing sites binary variables equal to 1 151 | cqm.fix_variables({key[2]: 1.0 for key in tower_vars.keys()}) 152 | 153 | return cqm 154 | 155 | def visualize(region_map, existing_towers, new_locs, build_sites): 156 | ''' Visualize the scenario and solution. 157 | Args: 158 | - region_map: gdf. Whole region map. 159 | - existing_towers: df. Dataframe containing tower information. 160 | - new_locs: list of [float, float]. New points as [lat, long]. 161 | - build_sites: list of [float, float]. Build site points as [lat, long]. 162 | Returns: 163 | None. 164 | ''' 165 | 166 | print("\nVisualizing scenario and solution...") 167 | 168 | # Initialize figure and axes 169 | _, (ax, ax_final) = plt.subplots(nrows=1, ncols=2, figsize=(32, 12)) 170 | ax.axis('off') 171 | ax_final.axis('off') 172 | 173 | # Draw borders or region 174 | polys = [shape(p) for p in region_map.shapes()] 175 | boundary = unary_union(polys) 176 | for geom in boundary.geoms: 177 | xs, ys = geom.exterior.xy 178 | ax.fill(xs, ys, alpha=0.5, fc='#d3d3d3', ec='none', zorder=0) 179 | ax_final.fill(xs, ys, alpha=0.5, fc='#d3d3d3', ec='none', zorder=0) 180 | 181 | # Draw existing towers 182 | ax.scatter(existing_towers.Longitude, existing_towers.Latitude, color='r', zorder=2) 183 | ax_final.scatter(existing_towers.Longitude, existing_towers.Latitude, color='r', zorder=2) 184 | 185 | # Draw radius around existing towers 186 | radius = 30 187 | ax.scatter(existing_towers.Longitude, existing_towers.Latitude, color='r', alpha=0.1, s=radius**2, zorder=1) 188 | ax_final.scatter(existing_towers.Longitude, existing_towers.Latitude, color='r', alpha=0.1, s=radius**2, zorder=1) 189 | 190 | # Draw new potential build sites on map 191 | new_locations = pd.DataFrame(new_locs, columns=['Latitude','Longitude']) 192 | ax.scatter(new_locations.Longitude, new_locations.Latitude, color='y', zorder=8) 193 | 194 | # Draw new selected build sites on map 195 | new_builds = pd.DataFrame(build_sites, columns=['Latitude','Longitude']) 196 | ax_final.scatter(new_builds.Longitude, new_builds.Latitude, color='b', zorder=8) 197 | 198 | # Draw radius around selected build sites 199 | ax_final.scatter(new_builds.Longitude, new_builds.Latitude, color='b', alpha=0.1, s=radius**2, zorder=8) 200 | 201 | # Make the figure look good 202 | ax.axis('scaled') 203 | ax_final.axis('scaled') 204 | ax.set_title("Potential Sites", fontsize = 24) 205 | ax_final.set_title("Determined Sites", fontsize = 24) 206 | 207 | # Save the figure 208 | plot_filename = 'map.png' 209 | plt.savefig(plot_filename) 210 | print("\nOutput saved as", plot_filename) 211 | 212 | 213 | if __name__ == "__main__": 214 | 215 | # Load and draw country map from geojson file 216 | print("\nLoading map and scenario...") 217 | shp_file = "data/germany_states.shp" 218 | germany_map = shapefile.Reader(shp_file, encoding='CP1252') 219 | 220 | # Load existing towers 221 | existing_towers = get_existing_towers("data/locations.txt") 222 | 223 | # Select random points within the country borders 224 | num_new = 100 225 | new_locs = gen_new_points(num_new, germany_map) 226 | num_to_build = 10 227 | 228 | print("\nBuilding CQM...") 229 | cqm = build_cqm(num_to_build, existing_towers, new_locs, radius=75) 230 | 231 | # Initialize the CQM solver 232 | sampler = LeapHybridCQMSampler() 233 | 234 | # Solve the problem using the CQM solver 235 | print("\nSending problem to hybrid solver...") 236 | sampleset = sampler.sample_cqm(cqm, label='Example - TV Towers') 237 | feasible_sampleset = sampleset.filter(lambda row: row.is_feasible) 238 | 239 | try: 240 | sample = feasible_sampleset.first.sample 241 | except: 242 | print("\nNo feasible solutions found.") 243 | exit() 244 | 245 | build_sites = [new_locs[key] for key, val in sample.items() if val == 1.0] 246 | print("\nSelected", len(build_sites), "build sites.") 247 | 248 | visualize(germany_map, existing_towers, new_locs, build_sites) -------------------------------------------------------------------------------- /readme_imgs/example_map.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dwave-examples/antenna-selection/f09077cea28340685002f52df0e8b8ddd7a91a4a/readme_imgs/example_map.png -------------------------------------------------------------------------------- /readme_imgs/example_original.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dwave-examples/antenna-selection/f09077cea28340685002f52df0e8b8ddd7a91a4a/readme_imgs/example_original.png -------------------------------------------------------------------------------- /readme_imgs/example_solution.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dwave-examples/antenna-selection/f09077cea28340685002f52df0e8b8ddd7a91a4a/readme_imgs/example_solution.png -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | dwave-ocean-sdk>=4.5.0 2 | matplotlib~=3.0 3 | descartes==1.1.0 4 | pyshp==2.3.0 5 | pandas>=1.3.5 6 | Shapely~=2.0 7 | -------------------------------------------------------------------------------- /tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dwave-examples/antenna-selection/f09077cea28340685002f52df0e8b8ddd7a91a4a/tests/__init__.py -------------------------------------------------------------------------------- /tests/test_antennas.py: -------------------------------------------------------------------------------- 1 | # Copyright 2019 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 os 16 | import subprocess 17 | import sys 18 | import unittest 19 | 20 | # /path/to/demos/antenna-selection/tests/test_antennas.py 21 | project_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 22 | 23 | 24 | class TestDemo(unittest.TestCase): 25 | def test_antennas_smoke(self): 26 | """run antennas.py and check that nothing crashes""" 27 | 28 | demo_file = os.path.join(project_dir, 'antennas.py') 29 | subprocess.check_output([sys.executable, demo_file]) 30 | 31 | def test_demo_smoke(self): 32 | """run demo.py and check that nothing crashes""" 33 | 34 | demo_file = os.path.join(project_dir, 'demo.py') 35 | subprocess.check_output([sys.executable, demo_file]) 36 | 37 | def test_antenna_selection(self): 38 | """ Verify contents of output """ 39 | 40 | demo_file = os.path.join(project_dir, 'antennas.py') 41 | output = subprocess.check_output([sys.executable, demo_file]) 42 | output = str(output).upper() 43 | if os.getenv('DEBUG_OUTPUT'): 44 | print("Example output \n" + output) 45 | 46 | with self.subTest(msg="Verify if output contains 'Maximum independent set size found' \n"): 47 | self.assertIn("Maximum independent set size found".upper(), output) 48 | with self.subTest(msg="Verify if error string contains in output \n"): 49 | self.assertNotIn("ERROR", output) 50 | with self.subTest(msg="Verify if warning string contains in output \n"): 51 | self.assertNotIn("WARNING", output) --------------------------------------------------------------------------------