├── tests ├── __init__.py └── test_clustering.py ├── requirements.txt ├── readme_imgs ├── clustered_plot.png └── logical_graph.png ├── .circleci └── config.yml ├── .devcontainer └── devcontainer.json ├── example_clusters.py ├── utilities.py ├── clustering.py ├── README.md └── LICENSE /tests/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | dwave-ocean-sdk>=3.3.0 2 | matplotlib>=3.3.0 3 | -------------------------------------------------------------------------------- /readme_imgs/clustered_plot.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dwave-examples/clustering/HEAD/readme_imgs/clustered_plot.png -------------------------------------------------------------------------------- /readme_imgs/logical_graph.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dwave-examples/clustering/HEAD/readme_imgs/logical_graph.png -------------------------------------------------------------------------------- /.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 2 * * 3" 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 | -------------------------------------------------------------------------------- /tests/test_clustering.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 | import os 15 | import subprocess 16 | import sys 17 | import unittest 18 | 19 | from clustering import Coordinate, get_distance, get_max_distance 20 | 21 | 22 | class TestHelperFunctions(unittest.TestCase): 23 | def test_get_distance(self): 24 | coord0 = Coordinate(2.5, 3) 25 | coord1 = Coordinate(10, -2) 26 | 27 | distance = get_distance(coord0, coord1) 28 | self.assertAlmostEqual(9.01387818866, distance) 29 | 30 | def test_get_max_distance(self): 31 | coords = [Coordinate(-1, 0), Coordinate(-.5, 3), Coordinate(-4, 4)] 32 | max_distance = get_max_distance(coords) 33 | 34 | self.assertEqual(5, max_distance) 35 | 36 | class IntegrationTests(unittest.TestCase): 37 | @unittest.skipIf(os.getenv('SKIP_INT_TESTS'), "Skipping integration test.") 38 | def test_clustering(self): 39 | project_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 40 | demo_file = os.path.join(project_dir, 'clustering.py') 41 | 42 | output = subprocess.check_output([sys.executable, demo_file, "--no-problem-inspector"]) 43 | output = output.decode('utf-8').upper() 44 | 45 | if os.getenv('DEBUG_OUTPUT'): 46 | print("Example output\n" + output) 47 | 48 | self.assertIn("Your plots are saved to".upper(), output) 49 | -------------------------------------------------------------------------------- /example_clusters.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 | # This is not the main demo script. It is simple a handy script generate more 16 | # interesting data to try with the main demo script, `clustering.py`. 17 | # 18 | # This script is about setting up this more interesting data and then passing 19 | # the data to `clustering.cluster_points(..)`, a key function `clustering.py`. 20 | 21 | import argparse 22 | import numpy as np 23 | 24 | from utilities import visualize_scatterplot 25 | from clustering import cluster_points 26 | 27 | parser = argparse.ArgumentParser() 28 | parser.add_argument('--no-problem-inspector', action='store_false', dest='problem_inspector', help='do not show problem inspector') 29 | args = parser.parse_args() 30 | 31 | 32 | # Set up three different clusters of data points 33 | covariance = [[3, 0], [0, 3]] 34 | n_points = 3 35 | x0, y0 = np.random.multivariate_normal([0, 0], covariance, n_points).T 36 | x1, y1 = np.random.multivariate_normal([10, 5], covariance, n_points).T 37 | x2, y2 = np.random.multivariate_normal([5, 15], covariance, n_points).T 38 | 39 | # Combine data points together into a list of tuples 40 | # Note: data points now look like [(x0, y0), (x1, y1), ..] 41 | xs = np.hstack([x0, x1, x2]) 42 | ys = np.hstack([y0, y1, y2]) 43 | xys = np.vstack([xs, ys]).T 44 | scattered_points = list(map(tuple, xys)) 45 | 46 | # Save the original, un-clustered plot 47 | orig_filename = "nine_points.png" 48 | visualize_scatterplot(scattered_points, orig_filename) 49 | 50 | # Run clustering script with scattered_points 51 | clustered_filename = "nine_points_clustered.png" 52 | cluster_points(scattered_points, clustered_filename, args.problem_inspector) 53 | 54 | print("Your plots are saved to '{}' and '{}'.".format(orig_filename, 55 | clustered_filename)) 56 | -------------------------------------------------------------------------------- /utilities.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 | # Handy functions that are not necessary for the conceptual understanding of 16 | # this code example 17 | 18 | from collections import defaultdict 19 | 20 | import matplotlib 21 | matplotlib.use("agg") 22 | import matplotlib.pyplot as plt 23 | 24 | 25 | def get_groupings(sample): 26 | """Grab selected items and group them by color""" 27 | colored_points = defaultdict(list) 28 | 29 | for label, bool_val in sample.items(): 30 | # Skip over items that were not selected 31 | if not bool_val: 32 | continue 33 | 34 | # Parse selected items 35 | # Note: label look like ",_" 36 | coord, color = label.split("_") 37 | coord_tuple = tuple(map(float, coord.split(","))) 38 | colored_points[color].append(coord_tuple) 39 | 40 | return dict(colored_points) 41 | 42 | 43 | def visualize_groupings(groupings_dict, filename): 44 | """ 45 | Args: 46 | groupings_dict: key is a color, value is a list of x-y coordinate tuples. 47 | For example, {'r': [(0,1), (2,3)], 'b': [(8,3)]} 48 | filename: name of the file to save plot in 49 | """ 50 | for color, points in groupings_dict.items(): 51 | # Ignore items that do not contain any coordinates 52 | if not points: 53 | continue 54 | 55 | # Populate plot 56 | point_style = color + "o" 57 | plt.plot(*zip(*points), point_style) 58 | 59 | plt.savefig(filename) 60 | 61 | 62 | def visualize_scatterplot(x_y_tuples_list, filename): 63 | """Plotting out a list of x-y tuples 64 | 65 | Args: 66 | x_y_tuples_list: A list of x-y coordinate values. e.g. [(1,4), (3, 2)] 67 | """ 68 | plt.plot(*zip(*x_y_tuples_list), "o") 69 | plt.savefig(filename) 70 | -------------------------------------------------------------------------------- /clustering.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 | import math 15 | 16 | import dwavebinarycsp 17 | import dwave.inspector 18 | from dwave.system import EmbeddingComposite, DWaveSampler 19 | 20 | from utilities import get_groupings, visualize_groupings, visualize_scatterplot 21 | 22 | 23 | class Coordinate: 24 | def __init__(self, x, y): 25 | self.x = x 26 | self.y = y 27 | 28 | # coordinate labels for groups red, green, and blue 29 | label = "{0},{1}_".format(x, y) 30 | self.r = label + "r" 31 | self.g = label + "g" 32 | self.b = label + "b" 33 | 34 | 35 | def get_distance(coordinate_0, coordinate_1): 36 | diff_x = coordinate_0.x - coordinate_1.x 37 | diff_y = coordinate_0.y - coordinate_1.y 38 | 39 | return math.sqrt(diff_x**2 + diff_y**2) 40 | 41 | 42 | def get_max_distance(coordinates): 43 | max_distance = 0 44 | for i, coord0 in enumerate(coordinates[:-1]): 45 | for coord1 in coordinates[i+1:]: 46 | distance = get_distance(coord0, coord1) 47 | max_distance = max(max_distance, distance) 48 | 49 | return max_distance 50 | 51 | 52 | def cluster_points(scattered_points, filename, problem_inspector): 53 | """Perform clustering analysis on given points 54 | 55 | Args: 56 | scattered_points (list of tuples): 57 | Points to be clustered 58 | filename (str): 59 | Output file for graphic 60 | problem_inspector (bool): 61 | Whether to show problem inspector 62 | """ 63 | # Set up problem 64 | # Note: max_distance gets used in division later on. Hence, the max(.., 1) 65 | # is used to prevent a division by zero 66 | coordinates = [Coordinate(x, y) for x, y in scattered_points] 67 | max_distance = max(get_max_distance(coordinates), 1) 68 | 69 | # Build constraints 70 | csp = dwavebinarycsp.ConstraintSatisfactionProblem(dwavebinarycsp.BINARY) 71 | 72 | # Apply constraint: coordinate can only be in one colour group 73 | choose_one_group = {(0, 0, 1), (0, 1, 0), (1, 0, 0)} 74 | for coord in coordinates: 75 | csp.add_constraint(choose_one_group, (coord.r, coord.g, coord.b)) 76 | 77 | # Build initial BQM 78 | bqm = dwavebinarycsp.stitch(csp) 79 | 80 | # Edit BQM to bias for close together points to share the same color 81 | for i, coord0 in enumerate(coordinates[:-1]): 82 | for coord1 in coordinates[i+1:]: 83 | # Set up weight 84 | d = get_distance(coord0, coord1) / max_distance # rescale distance 85 | weight = -math.cos(d*math.pi) 86 | 87 | # Apply weights to BQM 88 | bqm.add_interaction(coord0.r, coord1.r, weight) 89 | bqm.add_interaction(coord0.g, coord1.g, weight) 90 | bqm.add_interaction(coord0.b, coord1.b, weight) 91 | 92 | # Edit BQM to bias for far away points to have different colors 93 | for i, coord0 in enumerate(coordinates[:-1]): 94 | for coord1 in coordinates[i+1:]: 95 | # Set up weight 96 | # Note: rescaled and applied square root so that far off distances 97 | # are all weighted approximately the same 98 | d = math.sqrt(get_distance(coord0, coord1) / max_distance) 99 | weight = -math.tanh(d) * 0.1 100 | 101 | # Apply weights to BQM 102 | bqm.add_interaction(coord0.r, coord1.b, weight) 103 | bqm.add_interaction(coord0.r, coord1.g, weight) 104 | bqm.add_interaction(coord0.b, coord1.r, weight) 105 | bqm.add_interaction(coord0.b, coord1.g, weight) 106 | bqm.add_interaction(coord0.g, coord1.r, weight) 107 | bqm.add_interaction(coord0.g, coord1.b, weight) 108 | 109 | # Submit problem to D-Wave sampler 110 | sampler = EmbeddingComposite(DWaveSampler()) 111 | sampleset = sampler.sample(bqm, 112 | chain_strength=4, 113 | num_reads=1000, 114 | label='Example - Clustering') 115 | best_sample = sampleset.first.sample 116 | 117 | # Visualize graph problem 118 | if problem_inspector: 119 | dwave.inspector.show(bqm, sampleset) 120 | 121 | # Visualize solution 122 | groupings = get_groupings(best_sample) 123 | visualize_groupings(groupings, filename) 124 | 125 | # Print solution onto terminal 126 | # Note: This is simply a more compact version of 'best_sample' 127 | print(groupings) 128 | 129 | 130 | if __name__ == "__main__": 131 | import argparse 132 | 133 | parser = argparse.ArgumentParser() 134 | parser.add_argument('--no-problem-inspector', action='store_false', dest='problem_inspector', help='do not show problem inspector') 135 | args = parser.parse_args() 136 | 137 | # Simple, hardcoded data set 138 | scattered_points = [(0, 0), (1, 1), (2, 4), (3, 2)] 139 | 140 | # Save the original, un-clustered plot 141 | orig_filename = "four_points.png" 142 | visualize_scatterplot(scattered_points, orig_filename) 143 | 144 | # Find clusters 145 | # Note: the key part of this demo is in the construction of this function 146 | clustered_filename = "four_points_clustered.png" 147 | cluster_points(scattered_points, clustered_filename, args.problem_inspector) 148 | 149 | print("Your plots are saved to '{}' and '{}'.".format(orig_filename, 150 | clustered_filename)) 151 | -------------------------------------------------------------------------------- /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/clustering?quickstart=1) 4 | [![Linux/Mac/Windows build status]( 5 | https://circleci.com/gh/dwave-examples/clustering.svg?style=shield)]( 6 | https://circleci.com/gh/dwave-examples/clustering) 7 | 8 | # Clustering 9 | 10 | A demo on identifying clusters in a data set using the D-Wave quantum computer. 11 | 12 | When dealing with large data sets, we do not always have neatly labeled data 13 | (i.e. most, if not all, the data could be unlabeled). However, all is not lost 14 | as we can still extract insights from this data through clustering. 15 | 16 | For example, when dealing with housing data---namely, square footage and 17 | price---we can identify clusters in that data which may be indicative of 18 | different neighborhoods. Another example could be having a boolean vector of TV 19 | shows that consumers watch; clusters in this data could help identify a 20 | particular consumer demographic. 21 | 22 | As well, if we do have a few labelled data points in our data set, we could 23 | potentially label the entire cluster based on these. 24 | 25 | ![Clustered Plot](readme_imgs/clustered_plot.png) 26 | 27 | Figure: A data set of nine points that have been divided into three clusters 28 | (shown with different colors). 29 | 30 | ## Usage 31 | 32 | To run the demo with a simple, hardcoded data set: 33 | 34 | ```bash 35 | python clustering.py 36 | ``` 37 | 38 | To run the same demo with a slightly more sophisticated data set: 39 | 40 | ```bash 41 | python example_clusters.py 42 | ``` 43 | 44 | This provides a visualization of the problem on the D-Wave problem inspector, 45 | and plots of the original data set and its solution. 46 | 47 | ## Code Overview 48 | 49 | The D-Wave quantum computer accepts problems formulated mathematically in Binary 50 | Quadratic Model (BQM) format. The goal here is to build a BQM such that it 51 | represents our clustering problem. Namely, we want a BQM such that a low-energy 52 | solution found by the D-Wave quantum computer would correspond to a solution 53 | to our clustering problem. 54 | 55 | Key properties of the clustering problem that we need to capture in our BQM: 56 | 57 | * Each data point can only be a part of one cluster 58 | * Data points that are close together should be a part of the same cluster 59 | * Data points that are far apart should be in different clusters 60 | 61 | ## Code Specifics 62 | 63 | Let's go through how we implement each of the key properties of our clustering 64 | problem. 65 | 66 | ### Each data point can only join one cluster 67 | 68 | * The code is only considering three different cluster labels: red, green, and 69 | blue. 70 | * Since a qubit can only end up in one of two states (i.e. it can only 71 | answer yes or no questions), each data point has three nodes associated to it: 72 | `.r`, `.g`, and `.b`. That way, we 73 | can answer yes-no questions for whether a specific coordinate is in a 74 | particular colour cluster. 75 | * The rule that a data point may only join one cluster is represented by the 76 | variable `choose_one_group` (shown below). Each three-item-tuple below can 77 | be interpreted as `(, , )`, where the 78 | 1s and 0s indicate true and false, respectively. Hence, the 79 | `choose_one_group` is a set of all valid states. (e.g. `(1, 1, 0)` is not 80 | valid because a data point is not allowed to be in both red and green clusters 81 | at once). 82 | 83 | ```bash 84 | choose_one_group = {(0, 0, 1), (0, 1, 0), (1, 0, 0)} 85 | ``` 86 | 87 | * You can easily see this "choose one group" constraint in the D-Wave inspector. 88 | The image below has four data points (as seen in `clustering.py`). Each of 89 | the four data points has three nodes associated with it - `.r`, 90 | ``, and `` - hence the twelve nodes below. 91 | * A particular data point's set of three nodes can actually be identified in the 92 | graph below. By noting the yellow triangles below, we can see that one vertex 93 | is selected (in yellow) and two vertices are not selected (in white). 94 | 95 | ![Logical Graph](readme_imgs/logical_graph.png) 96 | 97 | * In the actual D-Wave Inspector, you can hover over these nodes and find out 98 | which data point and colour they represent and the BQM weights that are placed 99 | on them. 100 | 101 | ### Close data points should be in the same cluster 102 | 103 | * If we set BQM weights such that clustering close data points has lower-energy 104 | solutions, when the quantum computer minimizes the BQM, it finds good 105 | solutions to the clustering problem. 106 | * These weights are dependent on distance. In order to keep the weights within 107 | a reasonable range, the distances are all scaled with respect to the 108 | `max_distance`, the largest distance between any two points in the data set. 109 | * Below is the function used to determine the weight to encourage close together 110 | points to be in the same cluster 111 | 112 | ```bash 113 | d = get_distance(coord0, coord1) / max_distance # rescale distance 114 | weight = -math.cos(d*math.pi) 115 | ``` 116 | 117 | * We can apply many different types of functions for generating the weight. 118 | In this case, we chose a cosine function. The main idea is that we simply 119 | need short distances (nearby points) to generate a strong negative value that 120 | contributes to clustering these points, while points with large distances are 121 | only mildly affected. 122 | 123 | ### Far-apart data points should be in different clusters 124 | 125 | * Here, we want to encourage far apart data points to be in different clusters. 126 | Again, since the D-Wave quantum computer seeks low-energy configurations, we 127 | need to make far apart data points correspond to lower energy. 128 | * We do this by choosing a strong negative weight for far apart points. Hence, 129 | the choice of the `tanh` function. 130 | 131 | ```bash 132 | d = math.sqrt(get_distance(coord0, coord1) / max_distance) 133 | weight = -math.tanh(d) * 0.1 134 | ``` 135 | 136 | * Note that a scalar of `0.1` was applied in order to prevent this weight from 137 | overwhelming the other weights in the BQM. The `0.1` is arbitrary and was 138 | found by tinkering with the code. 139 | 140 | ## License 141 | 142 | Released under the Apache License 2.0. See [LICENSE](LICENSE) file. 143 | -------------------------------------------------------------------------------- /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 | --------------------------------------------------------------------------------