### Install PyQUBO from Source Source: https://github.com/recruit-communications/pyqubo/blob/master/docs/getting_started.rst Installs the PyQUBO library directly from the source code repository. This is useful for developers or if you need the latest unreleased version. ```shell git clone https://github.com/recruit-communications/pyqubo.git cd pyqubo python setup.py install ``` -------------------------------- ### Install PyQUBO via pip Source: https://github.com/recruit-communications/pyqubo/blob/master/docs/getting_started.rst Installs the PyQUBO library using the pip package manager. This is the recommended method for installation. ```shell pip install pyqubo ``` -------------------------------- ### Define Hamiltonian with Spin Variables (Simple Example) Source: https://github.com/recruit-communications/pyqubo/blob/master/docs/getting_started.rst Illustrates defining a simple Hamiltonian using Spin variables and converting it to QUBO. Spin variables take values {-1, 1}. ```python from pyqubo import Spin s1, s2 = Spin('s1'), Spin('s2') H = 2*s1*s2 + 3*s1 pprint(H.compile().to_qubo()) # doctest: +SKIP ``` -------------------------------- ### Creating BQM from Hamiltonian - PyQUBO - Python Source: https://github.com/recruit-communications/pyqubo/blob/master/docs/getting_started.rst Demonstrates how to define binary variables using `pyqubo.Binary`, construct a simple quadratic Hamiltonian, compile the model, and convert it into a Binary Quadratic Model (BQM) suitable for solvers. ```Python from pyqubo import Binary x1, x2 = Binary('x1'), Binary('x2') H = (x1 + x2 - 1)**2 model = H.compile() bqm = model.to_bqm() ``` -------------------------------- ### Sampling BQM with Simulated Annealing - PyQUBO/Neal - Python Source: https://github.com/recruit-communications/pyqubo/blob/master/docs/getting_started.rst Shows how to use `neal.SimulatedAnnealingSampler` to sample solutions from a BQM. It then demonstrates decoding the resulting `SampleSet` using `Model.decode_sampleset` and finding the sample with the minimum energy. Requires the `neal` library. ```Python import neal sa = neal.SimulatedAnnealingSampler() sampleset = sa.sample(bqm, num_reads=10) decoded_samples = model.decode_sampleset(sampleset) best_sample = min(decoded_samples, key=lambda x: x.energy) pprint(best_sample.sample) ``` -------------------------------- ### Convert Model to QUBO Source: https://github.com/recruit-communications/pyqubo/blob/master/docs/getting_started.rst Converts the compiled PyQUBO model into a QUBO (Quadratic Unconstrained Binary Optimization) representation. It returns the QUBO coefficients as a dictionary and a constant offset. ```python qubo, offset = model.to_qubo() pprint(qubo) # doctest: +SKIP print(offset) ``` -------------------------------- ### Compile the Hamiltonian Source: https://github.com/recruit-communications/pyqubo/blob/master/docs/getting_started.rst Compiles the defined Hamiltonian expression into a PyQUBO Model object. This step prepares the Hamiltonian for conversion to QUBO or Ising format. ```python model = H.compile() ``` -------------------------------- ### Decoding Sample and Validating Constraints - PyQUBO - Python Source: https://github.com/recruit-communications/pyqubo/blob/master/docs/getting_started.rst Demonstrates how to define a Hamiltonian including a constraint using `pyqubo.Constraint`. It shows how to compile the model, decode a raw solution obtained from a solver using `Model.decode_sample`, and access the decoded sample and the validation status of the constraints. ```Python from pyqubo import Binary, Constraint a, b = Binary('a'), Binary('b') M = 5.0 # strength of the constraint H = 2*a + b + M * Constraint((a+b-1)**2, label='a+b=1') model = H.compile() raw_solution = {'a': 0, 'b': 1} # solution from the solver decoded_sample = model.decode_sample(raw_solution, vartype='BINARY') pprint(decoded_sample.sample) pprint(decoded_sample.constraints()) ``` -------------------------------- ### Creating QUBO for Partitioning Problem - PyQUBO - Python Source: https://github.com/recruit-communications/pyqubo/blob/master/docs/getting_started.rst Demonstrates using `pyqubo.Array` to represent spin variables for a partitioning problem. It shows how to construct the Hamiltonian for this problem, compile the model, and convert it into a QUBO dictionary format suitable for solvers. ```Python from pyqubo import Array numbers = [4, 2, 7, 1] s = Array.create('s', shape=4, vartype='SPIN') H = sum(n * s for s, n in zip(s, numbers))**2 model = H.compile() qubo, offset = model.to_qubo() pprint(qubo) # doctest: +SKIP ``` -------------------------------- ### Define Hamiltonian with Binary Variables Source: https://github.com/recruit-communications/pyqubo/blob/master/docs/getting_started.rst Shows how to define a simple Hamiltonian using Binary variables in PyQUBO and convert it to QUBO. Binary variables take values {0, 1}. ```python from pyqubo import Binary x1, x2 = Binary('x1'), Binary('x2') H = 2*x1*x2 + 3*x1 pprint(H.compile().to_qubo()) # doctest: +SKIP ``` -------------------------------- ### Define Hamiltonian with Spin Variables Source: https://github.com/recruit-communications/pyqubo/blob/master/docs/getting_started.rst Demonstrates how to define a Hamiltonian expression using Spin variables in PyQUBO. Spin variables take values {-1, 1}. ```python from pyqubo import Spin s1, s2, s3, s4 = Spin("s1"), Spin("s2"), Spin("s3"), Spin("s4") H = (4*s1 + 2*s2 + 7*s3 + s4)**2 ``` -------------------------------- ### Accessing Array Elements - PyQUBO - Python Source: https://github.com/recruit-communications/pyqubo/blob/master/docs/getting_started.rst Illustrates the creation of a multi-dimensional array of binary variables using `pyqubo.Array.create`. It shows how to access specific elements of the array using standard Python indexing and how these elements can be used in expressions. ```Python from pyqubo import Array x = Array.create('x', shape=(2, 3), vartype='BINARY') x[0, 1] + x[1, 2] ``` -------------------------------- ### Creating QUBOs with Varying Parameters (Without Placeholder) - PyQUBO - Python Source: https://github.com/recruit-communications/pyqubo/blob/master/docs/getting_started.rst Illustrates the traditional approach to generating QUBOs when a parameter value changes. It shows that the Hamiltonian must be redefined with the new parameter value and the model must be recompiled for each new value, which can be inefficient for large problems. ```Python from pyqubo import Binary a, b = Binary('a'), Binary('b') M = 5.0 H = 2*a + b + M*(a+b-1)**2 model = H.compile() qubo, offset = model.to_qubo() # QUBO with M=5.0 M = 6.0 H = 2*a + b + M*(a+b-1)**2 model = H.compile() qubo, offset = model.to_qubo() # QUBO with M=6.0 ``` -------------------------------- ### Convert Model to Ising Source: https://github.com/recruit-communications/pyqubo/blob/master/docs/getting_started.rst Converts the compiled PyQUBO model into an Ising model representation. It returns the linear coefficients (external fields), quadratic coefficients (interactions), and a constant offset. ```python linear, quadratic, offset = model.to_ising() pprint(linear) # doctest: +SKIP pprint(quadratic) # doctest: +SKIP print(offset) ``` -------------------------------- ### Installing PyQUBO in Development Mode - Shell Source: https://github.com/recruit-communications/pyqubo/blob/master/CONTRIBUTING.rst Shows how to install PyQUBO in development mode using the setup.py script, allowing local code changes to be effective immediately without reinstallation. ```shell python setup.py develop ``` -------------------------------- ### Creating QUBO with Placeholder Parameter - PyQUBO - Python Source: https://github.com/recruit-communications/pyqubo/blob/master/docs/getting_started.rst Demonstrates how to use `pyqubo.Placeholder` to represent a parameter in the Hamiltonian. This allows the model to be compiled once, and the parameter value can be specified later when generating the QUBO using the `feed_dict` argument in `to_qubo`. ```Python from pyqubo import Placeholder a, b = Binary('a'), Binary('b') M = Placeholder('M') H = 2*a + b + M*(a+b-1)**2 model = H.compile() qubo, offset = model.to_qubo(feed_dict={'M': 5.0}) ``` -------------------------------- ### Installing PyQUBO from Source Shell Source: https://github.com/recruit-communications/pyqubo/blob/master/README.rst Provides the command-line instruction to install PyQUBO directly from its source code directory. This is typically used for development or installing specific versions not on PyPI. Requires Python and being in the root directory of the PyQUBO source code. ```shell python -m pip install . ``` -------------------------------- ### Installing PyQUBO via pip Shell Source: https://github.com/recruit-communications/pyqubo/blob/master/README.rst Provides the standard command-line instruction to install the PyQUBO library using the pip package manager. This is the recommended way to install PyQUBO. Requires Python and pip installed. ```shell pip install pyqubo ``` -------------------------------- ### Generating QUBO with Different Placeholder Value - PyQUBO - Python Source: https://github.com/recruit-communications/pyqubo/blob/master/docs/getting_started.rst Following the compilation with a `Placeholder`, this snippet shows how to generate a QUBO for a different value of the placeholder parameter by simply calling `to_qubo` again with an updated `feed_dict`. This avoids the need for recompilation. ```Python qubo, offset = model.to_qubo(feed_dict={'M': 6.0}) ``` -------------------------------- ### Retrieving Constraint Information from Decoded Sample in PyQUBO Source: https://github.com/recruit-communications/pyqubo/blob/master/docs/reference/model.rst Shows how to define constraints using PyQUBO, build and compile a Hamiltonian, decode a sample, and use the `constraints` method to get a dictionary containing the satisfaction status (boolean) and energy value (float) for each defined constraint. The example demonstrates getting all constraints and filtering for only broken ones. ```Python from pyqubo import Binary, Constraint a, b = Binary('a'), Binary('b') H = Constraint(a+b-2, "const1") + Constraint(a+b-1, "const2") model = H.compile() dec = model.decode_sample({'a': 1, 'b': 0}, vartype='BINARY') pprint(dec.constraints()) {'const1': (False, -1.0), 'const2': (True, 0.0)} pprint(dec.constraints(only_broken=True)) {'const1': (False, -1.0)} ``` -------------------------------- ### Running Doctests - Shell Source: https://github.com/recruit-communications/pyqubo/blob/master/CONTRIBUTING.rst Provides the command to execute doctests, which are example codes embedded within docstrings or documentation files, using the make utility. ```shell make doctest ``` -------------------------------- ### Running PyQUBO Doctests Shell Source: https://github.com/recruit-communications/pyqubo/blob/master/README.rst Provides the command-line instruction to run the doctests for PyQUBO. Doctests are examples embedded within documentation strings that are executed as tests. Requires the project's build system (likely `make`) and being in the project root. ```shell make doctest ``` -------------------------------- ### Creating QUBO with PyQUBO Python Source: https://github.com/recruit-communications/pyqubo/blob/master/README.rst Demonstrates how to define spin variables, construct a quadratic expression, compile it into a PyQUBO model, and convert the model into a QUBO dictionary representation. This example solves a Number Partitioning Problem. Requires the `pyqubo` library. ```python from pyqubo import Spin from pprint import pprint s1, s2, s3, s4 = Spin("s1"), Spin("s2"), Spin("s3"), Spin("s4") H = (4*s1 + 2*s2 + 7*s3 + s4)**2 model = H.compile() qubo, offset = model.to_qubo() pprint(qubo) # doctest: +SKIP ``` -------------------------------- ### Checking Broken Constraints with PyQUBO (Python) Source: https://github.com/recruit-communications/pyqubo/blob/master/docs/getting_started.rst This snippet demonstrates how to use the `constraints` method of a decoded sample object in PyQUBO to check for broken constraints. By setting `only_broken=True`, it filters the results to show only constraints that are violated. An empty dictionary output indicates no broken constraints. ```Python pprint(decoded_sample.constraints(only_broken=True)) ``` -------------------------------- ### Decoding SampleSet in PyQUBO Python Source: https://github.com/recruit-communications/pyqubo/blob/master/docs/reference/model.rst Shows the process of compiling a PyQUBO Hamiltonian with constraints, converting to BQM, solving with ExactSolver to get a SampleSet, and using `decode_sampleset` to decode the entire set and find the best sample's details. ```python >>> from pyqubo import Binary, Constraint >>> from dimod import ExactSolver >>> a, b = Binary('a'), Binary('b') >>> H = Constraint(2*a-3*b, "const1") + Constraint(a+b-1, "const2") >>> model = H.compile() >>> bqm = model.to_bqm() >>> sampleset = ExactSolver().sample(bqm) >>> decoded_samples = model.decode_sampleset(sampleset) >>> best_sample = min(decoded_samples, key=lambda s: s.energy) >>> print(best_sample.energy) -3.0 >>> pprint(best_sample.sample) {'a': 0, 'b': 1} >>> pprint(best_sample.constraints()) {'const1': (False, -3.0), 'const2': (True, 0.0)} ``` -------------------------------- ### Generating QUBO with Labels (Python) Source: https://github.com/recruit-communications/pyqubo/blob/master/docs/reference/model.rst This example shows how to compile a PyQUBO expression into a `Model` and then use the `to_qubo()` method to obtain the QUBO representation. The resulting dictionary uses the original variable labels as keys. It requires importing `Binary` from `pyqubo` and using `pprint` for output. ```Python >>> from pyqubo import Binary >>> from pprint import pprint >>> x, y, z = Binary("x"), Binary("y"), Binary("z") >>> model = (x*y + y*z + 3*z).compile() >>> pprint(model.to_qubo()) # doctest: +SKIP ({ ('x', 'x'): 0.0, ('x', 'y'): 1.0, ('y', 'y'): 0.0, ('z', 'y'): 1.0, ('z', 'z'): 3.0 }, 0.0) ``` -------------------------------- ### Uninstalling PyQUBO - Shell Source: https://github.com/recruit-communications/pyqubo/blob/master/CONTRIBUTING.rst Provides the command to uninstall an existing PyQUBO installation using pip, which is recommended before installing in development mode. ```shell pip uninstall pyqubo ``` -------------------------------- ### Checking Constraint Satisfaction with PyQUBO DecodedSample (Python) Source: https://github.com/recruit-communications/pyqubo/blob/master/docs/reference/express.rst This example shows how to define constraints using the `Constraint` class, compile the Hamiltonian, decode a sample solution, and then check which constraints are satisfied or broken using the `constraints()` method of the `DecodedSample` object. ```python >>> from pyqubo import Binary, Constraint >>> a, b = Binary('a'), Binary('b') >>> H = Constraint(a+b-2, "const1") + Constraint(a+b-1, "const2") >>> model = H.compile() >>> dec = model.decode_sample({'a': 1, 'b': 0}, vartype='BINARY') >>> pprint(dec.constraints()) {'const1': (False, -1.0), 'const2': (True, 0.0)} >>> pprint(dec.constraints(only_broken=True)) {'const1': (False, -1.0)} ``` -------------------------------- ### Setting Minimum CMake Version and Project Name (CMake) Source: https://github.com/recruit-communications/pyqubo/blob/master/CMakeLists.txt Specifies the minimum required CMake version (3.20) for the project and defines the project name as `cpp_pyqubo`. This is a standard starting point for any CMake project. ```CMake cmake_minimum_required(VERSION 3.20) project(cpp_pyqubo) ``` -------------------------------- ### Defining Sub-Hamiltonians (SubH) Source: https://github.com/recruit-communications/pyqubo/blob/master/docs/reference/express.rst Demonstrates how to use the SubH class to define named sub-expressions within a larger Hamiltonian. Shows an example of squaring these sub-expressions to create a penalty term. ```python from pyqubo import Spin, SubH s1, s2, s3 = Spin('s1'), Spin('s2'), Spin('s3') exp = (SubH(s1 + s2, 'n1'))**2 + (SubH(s1 + s3, 'n2'))**2 ``` -------------------------------- ### Examining DecodedSample Object in PyQUBO Python Source: https://github.com/recruit-communications/pyqubo/blob/master/docs/reference/model.rst Provides an example of creating a `DecodedSample` object from a simulated sample using `decode_sample` and accessing its attributes (`energy`, `sample`, `subh`) to inspect the results. ```python >>> from pyqubo import Binary, SubH >>> a, b = Binary('a'), Binary('b') >>> H = SubH(a+b-2, "subh1") + 2*a + b >>> model = H.compile() >>> decoded_sample = model.decode_sample({'a': 1, 'b': 0}, vartype='BINARY') >>> print(decoded_sample.energy) 1.0 >>> pprint(decoded_sample.sample) {'a': 1, 'b': 0} >>> print(decoded_sample.subh) {'subh1': -1.0} ``` -------------------------------- ### Generating Ising Model with Labels (Python) Source: https://github.com/recruit-communications/pyqubo/blob/master/docs/reference/model.rst This example shows how to compile a PyQUBO expression into a `Model` and then use the `to_ising()` method to obtain the Ising model representation. The result includes linear and quadratic terms, using the original variable labels as keys. It requires importing `Binary` from `pyqubo` and using `pprint` for output. ```Python >>> from pyqubo import Binary >>> from pprint import pprint >>> x, y, z = Binary("x"), Binary("y"), Binary("z") >>> model = (x*y + y*z + 3*z).compile() >>> pprint(model.to_ising()) # doctest: +SKIP ({'x': 0.25, 'y': 0.5, 'z': 1.75}, {('x', 'y'): 0.25, ('z', 'y'): 0.25}, 2.0) ``` -------------------------------- ### Decoding Single Sample in PyQUBO Python Source: https://github.com/recruit-communications/pyqubo/blob/master/docs/reference/model.rst Illustrates how to compile a PyQUBO Hamiltonian with a SubHamiltonian, simulate a sample result (dictionary), and use `decode_sample` to get a `DecodedSample` object showing energy, sample values, and SubH values. ```python >>> from pyqubo import Binary, SubH >>> a, b = Binary('a'), Binary('b') >>> H = SubH(a+b-2, "subh1") + 2*a + b >>> model = H.compile() >>> decoded_sample = model.decode_sample({'a': 1, 'b': 0}, vartype='BINARY') >>> print(decoded_sample.energy) 1.0 >>> pprint(decoded_sample.sample) {'a': 1, 'b': 0} >>> print(decoded_sample.subh) {'subh1': -1.0} ``` -------------------------------- ### Generating Index-Labeled Ising Model (Python) Source: https://github.com/recruit-communications/pyqubo/blob/master/docs/reference/model.rst This snippet illustrates how to get an index-labeled Ising model from a compiled `pyqubo.Model` using `to_ising(index_label=True)`. The mapping between indices and original labels is stored in `model.variables`. It requires importing `Binary` from `pyqubo` and using `pprint` for output. ```Python >>> from pyqubo import Binary >>> from pprint import pprint >>> x, y, z = Binary("x"), Binary("y"), Binary("z") >>> model = (x*y + y*z + 3*z).compile() >>> pprint(model.to_ising(index_label=True)) # doctest: +SKIP ({0: 1.75, 1: 0.25, 2: 0.5}, {(0, 2): 0.25, (1, 2): 0.25}, 2.0) ``` -------------------------------- ### Generating Index-Labeled QUBO (Python) Source: https://github.com/recruit-communications/pyqubo/blob/master/docs/reference/model.rst This snippet illustrates how to get an index-labeled QUBO from a compiled `pyqubo.Model` using `to_qubo(index_label=True)`. The mapping between indices and original labels is stored in `model.variables`. It requires importing `Binary` from `pyqubo` and using `pprint` for output. ```Python >>> from pyqubo import Binary >>> from pprint import pprint >>> x, y, z = Binary("x"), Binary("y"), Binary("z") >>> model = (x*y + y*z + 3*z).compile() >>> pprint(model.to_qubo(index_label=True)) # doctest: +SKIP ({(0, 0): 3.0, (0, 2): 1.0, (1, 1): 0.0, (1, 2): 1.0, (2, 2): 0.0}, 0.0) >>> model.variables ['z', 'x', 'y'] ``` -------------------------------- ### Defining Custom Expressions with PyQUBO UserDefinedExpress (Python) Source: https://github.com/recruit-communications/pyqubo/blob/master/docs/reference/express.rst This example demonstrates how to create a custom expression class, `LogicalAnd`, by inheriting from `UserDefinedExpress`. The custom class encapsulates a standard PyQUBO expression (in this case, multiplication for logical AND) and can be used like other expressions. ```python >>> from pyqubo import UserDefinedExpress, Binary >>> class LogicalAnd(UserDefinedExpress): ... def __init__(self, bit_a, bit_b): ... express = bit_a * bit_b ... super().__init__(express) >>> a, b = Binary('a'), Binary('b') >>> logical_and = LogicalAnd(a, b) ``` -------------------------------- ### Running PyQUBO Tests Shell Source: https://github.com/recruit-communications/pyqubo/blob/master/README.rst Provides command-line instructions to execute the test suite for PyQUBO. It includes setting an environment variable `USE_TEST=1` and running tests using `python -m unittest discover tests`. Commands for generating a coverage report are also included. Requires the test dependencies and being in the project root. ```shell export USE_TEST=1 python -m unittest discover tests ``` ```shell export USE_TEST=1 coverage run -m unittest discover coverage html ``` -------------------------------- ### Compiling and Solving PyQUBO Model with Simulated Annealing Source: https://github.com/recruit-communications/pyqubo/blob/master/notebooks/integer_partition.ipynb Compiles the PyQUBO Hamiltonian into a model, converts it to a Binary Quadratic Model (BQM), and solves it using `neal.SimulatedAnnealingSampler`. The resulting sampleset is decoded back to the original variables, and the sample with the minimum energy (best solution found) is printed. Requires the `neal` library. ```python # Create Ising model model = H.compile() bqm = model.to_bqm() # Solve Ising model # Solve Ising model import neal sa = neal.SimulatedAnnealingSampler() sampleset = sa.sample(bqm) # Decode solution decoded_samples = model.decode_sampleset(sampleset) best_sample = min(decoded_samples, key=lambda x: x.energy) print(best_sample.sample) ``` -------------------------------- ### Building Documentation HTML - Shell Source: https://github.com/recruit-communications/pyqubo/blob/master/CONTRIBUTING.rst Gives the command to clean previous Sphinx builds and generate updated HTML documentation files from source, with the output located in the 'docs/_build' directory. ```shell make clean html ``` -------------------------------- ### Converting PyQUBO Model to BQM in Python Source: https://github.com/recruit-communications/pyqubo/blob/master/docs/reference/model.rst Demonstrates compiling a PyQUBO Hamiltonian with constraints, converting it to a dimod BinaryQuadraticModel (BQM), solving it using ExactSolver, and decoding the results to find the best sample and its energy/constraints. ```python >>> from pyqubo import Binary, Constraint >>> from dimod import ExactSolver >>> a, b = Binary('a'), Binary('b') >>> H = Constraint(2*a-3*b, "const1") + Constraint(a+b-1, "const2") >>> model = H.compile() >>> bqm = model.to_bqm() >>> sampleset = ExactSolver().sample(bqm) >>> decoded_samples = model.decode_sampleset(sampleset) >>> best_sample = min(decoded_samples, key=lambda s: s.energy) >>> print(best_sample.energy) -3.0 >>> pprint(best_sample.sample) {'a': 0, 'b': 1} >>> pprint(best_sample.constraints()) {'const1': (False, -3.0), 'const2': (True, 0.0)} ``` -------------------------------- ### Running Unit Tests with unittest - Shell Source: https://github.com/recruit-communications/pyqubo/blob/master/CONTRIBUTING.rst Gives the command to execute all unit tests found within the 'tests' directory using Python's built-in unittest discovery feature. ```shell python -m unittest discover tests ``` -------------------------------- ### Creating Basic PyQUBO Expression (Base) Source: https://github.com/recruit-communications/pyqubo/blob/master/docs/reference/express.rst Demonstrates how to create a simple quadratic expression using Binary variables which inherit from the Base class. Shows the resulting expression object representation. ```python from pyqubo import Binary a, b = Binary("a"), Binary("b") 2*a*b + 1 (((2.000000 * Binary('a')) * Binary('b')) + 1.000000) ``` -------------------------------- ### Integrating PyQUBO with D-Wave Ocean Python Source: https://github.com/recruit-communications/pyqubo/blob/master/README.rst Shows how to use a compiled PyQUBO model with D-Wave Ocean SDK samplers. It converts the model to a BinaryQuadraticModel (BQM), samples it using `neal.SimulatedAnnealingSampler`, decodes the results, and finds the best sample. Requires `pyqubo` and a D-Wave Ocean compatible sampler like `neal`. ```python import neal sampler = neal.SimulatedAnnealingSampler() bqm = model.to_bqm() sampleset = sampler.sample(bqm, num_reads=10) decoded_samples = model.decode_sampleset(sampleset) best_sample = min(decoded_samples, key=lambda x: x.energy) best_sample.sample # doctest: +SKIP ``` -------------------------------- ### Importing Libraries for Graph Partitioning - Python Source: https://github.com/recruit-communications/pyqubo/blob/master/notebooks/graph_partition.ipynb Imports necessary libraries for defining and solving the graph partitioning problem using PyQUBO, plotting with matplotlib, and handling graph structures with networkx. Includes a magic command for inline plotting in notebooks. ```python %matplotlib inline from pyqubo import Spin, Array, Placeholder, Constraint import matplotlib.pyplot as plt import networkx as nx ``` -------------------------------- ### Generating Test Coverage Report - Shell Source: https://github.com/recruit-communications/pyqubo/blob/master/CONTRIBUTING.rst Provides the sequence of commands to run tests using the coverage tool and then generate an HTML report in the 'htmlcov' directory for analyzing code coverage. ```shell coverage run -m unittest discover coverage html ``` -------------------------------- ### Visualizing Graph Partitioning Solution - Python Source: https://github.com/recruit-communications/pyqubo/blob/master/notebooks/graph_partition.ipynb Visualizes the graph again, this time coloring the nodes according to the partition found by the solver. The node colors are determined by the values of the spin variables in the best solution. ```python # Plot graph plot_graph(E, [best_sample.sample[k]+1 for k in sorted(best_sample.sample.keys())]) ``` -------------------------------- ### Specify Read the Docs Theme Dependency Version (Other) Source: https://github.com/recruit-communications/pyqubo/blob/master/requirements_doctest.txt Defines the minimum required version for the sphinx-rtd-theme package. This specifies the visual theme used when building the project's documentation. ```Other sphinx-rtd-theme>=0.5.2 ``` -------------------------------- ### Solving BQM with Simulated Annealing and Decoding - Python Source: https://github.com/recruit-communications/pyqubo/blob/master/notebooks/graph_partition.ipynb Uses the `neal` simulated annealing sampler to find a low-energy solution for the generated BQM. It then decodes the resulting sample set back into the original variables using the PyQUBO model and identifies the best solution based on energy. ```python # Solve Ising model import neal sa = neal.SimulatedAnnealingSampler() sampleset = sa.sample(bqm) # Decode solution decoded_samples = model.decode_sampleset(sampleset, feed_dict=feed_dict) best_sample = min(decoded_samples, key=lambda x: x.energy) print("#broken constraints: {}".format(len(best_sample.constraints(only_broken=True)))) ``` -------------------------------- ### Running Tests with CircleCI CLI - Shell Source: https://github.com/recruit-communications/pyqubo/blob/master/CONTRIBUTING.rst Instructs how to run specific test jobs locally using the CircleCI command-line interface, requiring replacement of '$JOBNAME' with a job name from the CircleCI configuration. ```shell circleci build --job $JOBNAME ``` -------------------------------- ### Importing Spin Variable for PyQUBO Source: https://github.com/recruit-communications/pyqubo/blob/master/notebooks/integer_partition.ipynb Imports the necessary `Spin` class from the `pyqubo` library. The `Spin` class is used to represent binary variables that can take values of -1 or 1, which are fundamental building blocks for constructing Hamiltonians in PyQUBO. ```python from pyqubo import Spin ``` -------------------------------- ### Creating and Compiling Binary Expression (Binary) Source: https://github.com/recruit-communications/pyqubo/blob/master/docs/reference/express.rst Shows how to define Binary variables and construct a quadratic expression. Compiles the expression and converts it to a QUBO dictionary using compile() and to_qubo(). Requires the pprint library for formatted output. ```python from pyqubo import Binary # Assuming pprint is imported for the output format a, b = Binary('a'), Binary('b') exp = 2*a*b + 3*a # pprint(exp.compile().to_qubo()) # doctest: +SKIP # Output: # ({('a', 'a'): 3.0, ('a', 'b'): 2.0, ('b', 'b'): 0}, 0.0) ``` -------------------------------- ### Defining PyQUBO Variables (Spin Array, Placeholder) - Python Source: https://github.com/recruit-communications/pyqubo/blob/master/notebooks/graph_partition.ipynb Initializes the variables required for the PyQUBO formulation. An array of spin variables `s` is created to represent the nodes' partition assignments, and a `Placeholder` `a` is defined for the penalty strength $\alpha$. ```python # Define spin vector s = Array.create("s", 8, 'SPIN') # Define placeholder alpha a = Placeholder("alpha") ``` -------------------------------- ### Creating and Compiling Spin Expression (Spin) Source: https://github.com/recruit-communications/pyqubo/blob/master/docs/reference/express.rst Demonstrates defining Spin variables and building a quadratic expression. Compiles the expression and converts it to an Ising model (represented as a QUBO dictionary) using compile() and to_qubo(). Requires the pprint library for formatted output. ```python from pyqubo import Spin # Assuming pprint is imported for the output format a, b = Spin('a'), Spin('b') exp = 2*a*b + 3*a # pprint(exp.compile().to_qubo()) # doctest: +SKIP # Output: # ({('a', 'a'): 2.0, ('a', 'b'): 8.0, ('b', 'b'): -4.0}, -1.0) ``` -------------------------------- ### Importing Libraries for PyQUBO Logic Gates Source: https://github.com/recruit-communications/pyqubo/blob/master/notebooks/multiplier.ipynb Imports necessary classes from the pyqubo library for building QUBO expressions, along with dimod and neal for solving and sampling the resulting problems. ```python from pyqubo import UserDefinedExpress, Array, Xor, And, Or, AndConst, OrConst, XorConst, Binary, Spin, Integer import dimod import neal ``` -------------------------------- ### Compiling Higher-Order Expression to QUBO (Base.compile) Source: https://github.com/recruit-communications/pyqubo/blob/master/docs/reference/express.rst Illustrates compiling a higher-order polynomial expression involving Binary variables into a QUBO model using the compile method. Shows the resulting QUBO dictionary representation after calling to_qubo(). Requires the pprint library for formatted output. ```python from pyqubo import Binary # Assuming pprint is imported for the output format a, b, c, d = Binary("a"), Binary("b"), Binary("c"), Binary("d") model = (a*b*c + a*b*d).compile() # pprint(model.to_qubo()) # doctest: +SKIP # Output: # ({('a', 'a'): 0.0, # ('a', 'a*b'): -10.0, # ('a', 'b'): 5.0, # ('a*b', 'a*b'): 15.0, # ('a*b', 'b'): -10.0, # ('a*b', 'c'): 1.0, # ('a*b', 'd'): 1.0, # ('b', 'b'): 0.0, # ('c', 'c'): 0, # ('d', 'd'): 0}, # 0.0) ``` -------------------------------- ### Accessing Two-Bit Multiplier Solution Sample Source: https://github.com/recruit-communications/pyqubo/blob/master/notebooks/multiplier.ipynb Accesses the 'sample' attribute of the solution object obtained from the solver. This attribute contains the variable assignments (the binary values for x, y, and p) that represent the found solution to the QUBO problem. ```python two_bit_multiplier_solutions.sample ``` -------------------------------- ### Compiling PyQUBO Model and Creating BQM - Python Source: https://github.com/recruit-communications/pyqubo/blob/master/notebooks/graph_partition.ipynb Compiles the symbolic PyQUBO Hamiltonian expression into a model object. It then converts this compiled model into a Binary Quadratic Model (BQM), providing a specific value for the placeholder `alpha` via a feed dictionary. ```python # Compile model model = H.compile() # Create Ising model with alpha = 0.1 feed_dict={'alpha': 0.1} bqm = model.to_bqm(feed_dict=feed_dict) ``` -------------------------------- ### Finding Factors for a Specific Product - Python Source: https://github.com/recruit-communications/pyqubo/blob/master/notebooks/multiplier.ipynb This snippet demonstrates how to use the `find_three_bit_multiplier_factors` function. It sets a specific 6-bit binary array for the product `p_bits` and calls the function to find the corresponding 3-bit binary arrays for the factors `a` and `b`, then prints the resulting bit arrays. ```python p_bits = [0, 0, 1, 0, 1, 0] a_bits, b_bits = find_three_bit_multiplier_factors(p_bits) print("Bit array of a is", a_bits) print("Bit array of b is", b_bits) ``` -------------------------------- ### Using Placeholder in Expression (Placeholder) Source: https://github.com/recruit-communications/pyqubo/blob/master/docs/reference/express.rst Illustrates defining an expression with a Placeholder variable. Shows how to compile the expression once and then generate QUBOs with different placeholder values using the feed_dict parameter in to_qubo(). Requires the pprint library for formatted output. ```python from pyqubo import Binary, Placeholder # Assuming pprint is imported for the output format x, y, a = Binary('x'), Binary('y'), Placeholder('a') exp = a*x*y + 2.0*x # pprint(exp.compile().to_qubo(feed_dict={'a': 3.0})) # doctest: +SKIP # Output: # ({('x', 'x'): 2.0, ('x', 'y'): 3.0, ('y', 'y'): 0}, 0.0) # pprint(exp.compile().to_qubo(feed_dict={'a': 5.0})) # doctest: +SKIP # Output: # ({('x', 'x'): 2.0, ('x', 'y'): 5.0, ('y', 'y'): 0}, 0.0) ``` -------------------------------- ### Specify Sphinx Dependency Version (Other) Source: https://github.com/recruit-communications/pyqubo/blob/master/requirements_doctest.txt Defines the minimum required version for the Sphinx documentation generator package. This ensures compatibility with the project's documentation build configuration. ```Other Sphinx>=3.5.4 ``` -------------------------------- ### Verifying Multiplication Result - Python Source: https://github.com/recruit-communications/pyqubo/blob/master/notebooks/multiplier.ipynb This snippet performs an assertion to confirm that the integer values of the factors `a` and `b` found by the sampler, when multiplied together, are equal to the integer value of the original product `p`. This verifies the correctness of the solution found by the quantum annealing process. ```python # we can confirm that a*b=p assert a*b==p ``` -------------------------------- ### Accessing Array Values from Decoded Sample in PyQUBO Source: https://github.com/recruit-communications/pyqubo/blob/master/docs/reference/model.rst Demonstrates how to create a PyQUBO Array, build and compile a Hamiltonian, decode a sample obtained from a solver, and retrieve the value of specific array elements using the `array` method of the decoded sample object. Requires PyQUBO and a solver (implicitly used for sample generation). ```Python from pyqubo import Array x = Array.create('x', shape=(2, 1), vartype="BINARY") H = (x[0, 0] + x[1, 0] - 1)**2 model = H.compile() qubo, offset = model.to_qubo() pprint(qubo) {('x[0][0]', 'x[0][0]'): -1.0, ('x[0][0]', 'x[1][0]'): 2.0, ('x[1][0]', 'x[1][0]'): -1.0} dec = model.decode_sample({'x[0][0]': 1, 'x[1][0]': 0}, vartype='BINARY') print(dec.array('x', (0, 0))) 1 print(dec.array('x', (1, 0))) 0 ``` -------------------------------- ### Decoding and Displaying Integer Factors and Product - Python Source: https://github.com/recruit-communications/pyqubo/blob/master/notebooks/multiplier.ipynb This snippet takes the binary arrays for the product `p_bits` and the found factors `a_bits` and `b_bits`, uses the `decode_bits` function to convert them into their integer representations, and prints these integer values. ```python # we show the decoded values of a, b, and p p = decode_bits(p_bits) a = decode_bits(a_bits) b = decode_bits(b_bits) print(f"p={p}") print(f"a={a}") print(f"b={b}") ``` -------------------------------- ### Defining Graph Edges and Initial Visualization - Python Source: https://github.com/recruit-communications/pyqubo/blob/master/notebooks/graph_partition.ipynb Specifies the set of edges that define the graph for the partitioning problem instance. It then calls the `plot_graph` function to display the structure of the graph before solving. ```python # Following edges are given E = {(0, 6), (2, 4), (7, 5), (0, 4), (2, 0), (5, 3), (2, 3), (2, 6), (4, 6), (1, 3), (1, 5), (7, 1), (7, 3), (2, 5)} plot_graph(E) ``` -------------------------------- ### Implementing Full Adder with PyQUBO Source: https://github.com/recruit-communications/pyqubo/blob/master/notebooks/multiplier.ipynb Defines a FullAdder class inheriting from pyqubo.UserDefinedExpress. It implements a full adder by composing two HalfAdder instances and an OrConst gate, representing the sum and carry logic based on input bits and a carry-in bit. ```python class FullAdder(UserDefinedExpress): def __init__(self, a, b, c_in, s, c_out, label): s1 = Binary(label+'_s1') c1 = Binary(label+'_c1') c2 = Binary(label+'_c2') h1 = HalfAdder(a, b, s1, c1, label+'_FA_HA1') h2 = HalfAdder(s1, c_in, s, c2, label+'_FA_HA2') or_const = OrConst(c1, c2, c_out, label+'_FA_or') H = h1 + h2 + or_const super().__init__(H) ``` -------------------------------- ### Defining Hamiltonian for Set Partitioning with PyQUBO Source: https://github.com/recruit-communications/pyqubo/blob/master/notebooks/integer_partition.ipynb Defines the Hamiltonian (objective function) for the set partitioning problem using `Spin` variables. The expression `(2*s1 + 4*s2 + 6*s3)**2` penalizes solutions where the sum of elements assigned to one set (represented by the spin values) is not zero. Minimizing this Hamiltonian finds partitions where the sum is zero. ```python # Define hamiltonian s1, s2, s3 = Spin("s1"), Spin("s2"), Spin("s3") H = (2*s1 + 4*s2 + 6*s3)**2 ``` -------------------------------- ### Constructing Graph Partitioning Hamiltonian - Python Source: https://github.com/recruit-communications/pyqubo/blob/master/notebooks/graph_partition.ipynb Constructs the PyQUBO expression for the Ising Hamiltonian based on the graph partitioning formulation. It defines the constraint term `HA` for equal partition size and the objective term `HB` for minimizing cut edges, combining them with the placeholder `a`. ```python # Define hamiltonian H_{A} HA =Constraint(sum(s) ** 2, "num_nodes") # Define hamiltonian H_{B} HB = sum((1.0 - s[i]*s[j]) / 2.0 for (i, j) in E) H = a * HA + HB ``` -------------------------------- ### Setting Target Include Directories (CMake) Source: https://github.com/recruit-communications/pyqubo/blob/master/CMakeLists.txt Adds the include directories specified by the CMake variable `${Boost_INCLUDE_DIRS}` to the private include path for the `cpp_pyqubo` target. This allows the target to find Boost header files during compilation. ```CMake target_include_directories(cpp_pyqubo PRIVATE ${Boost_INCLUDE_DIRS}) ``` -------------------------------- ### Defining Graph Plotting Function - Python Source: https://github.com/recruit-communications/pyqubo/blob/master/notebooks/graph_partition.ipynb Defines a helper function to visualize a graph given its edges. It uses networkx to create the graph structure and matplotlib to draw it, supporting optional node coloring to represent partitions or other properties. ```python def plot_graph(E, colors=None): G = nx.Graph() for (i, j) in E: G.add_edge(i, j) plt.figure(figsize=(4,4)) pos = nx.spring_layout(G) if colors: nx.draw_networkx(G, pos, node_color=[colors[node] for node in G.nodes]) else: nx.draw_networkx(G, pos) plt.axis("off") plt.show() ``` -------------------------------- ### Project Dependencies - Python Source: https://github.com/recruit-communications/pyqubo/blob/master/requirements_rtd.txt Specifies the necessary Python packages and their version constraints for the project. Includes conditional dependencies based on Python version. ```Python coverage>=4.5.1 codecov>=2.1.9 dwave-neal>=0.5.4 nbsphinx>=0.3.5 Deprecated>=1.2.10 six>=1.15.0 numpy==1.19.4; python_version >= '3.6' numpy==1.18.5; python_version == '3.5' dimod==0.9.14 nbsphinx>=0.8.3; python_version >= '3.8' nbsphinx==0.3.5; python_version < '3.8' docutils<0.17,>=0.12; python_version < '3.8' ``` -------------------------------- ### Sampling and Decoding TSP Solution with PyQUBO and Simulated Annealing Source: https://github.com/recruit-communications/pyqubo/blob/master/notebooks/TSP.ipynb Uses the `neal` simulated annealing sampler to find low-energy solutions for the generated BQM. The samples are then decoded using the PyQUBO model to interpret the binary results, and the best sample (lowest energy) is identified. ```python import neal sa = neal.SimulatedAnnealingSampler() sampleset = sa.sample(bqm, num_reads=100, num_sweeps=100) # Decode solution decoded_samples = model.decode_sampleset(sampleset, feed_dict=feed_dict) best_sample = min(decoded_samples, key=lambda x: x.energy) num_broken = len(best_sample.constraints(only_broken=True)) print("number of broken constarint = {}".format(num_broken)) ``` -------------------------------- ### Including External Dependencies (CMake) Source: https://github.com/recruit-communications/pyqubo/blob/master/CMakeLists.txt Includes CMake configuration files for various external libraries like Boost, cimod, Eigen, pybind11, and robin_hood. These files help CMake find and configure these dependencies for the build process. ```CMake include(external/boost_assert.cmake) include(external/boost_config.cmake) include(external/boost_container.cmake) include(external/boost_container_hash.cmake) include(external/boost_core.cmake) include(external/boost_detail.cmake) include(external/boost_integer.cmake) include(external/boost_intrusive.cmake) include(external/boost_move.cmake) include(external/boost_static_assert.cmake) include(external/boost_type_traits.cmake) include(external/cimod.cmake) include(external/eigen.cmake) include(external/pybind11.cmake) include(external/robin_hood.cmake) ``` -------------------------------- ### Project Dependencies - Python Requirements Source: https://github.com/recruit-communications/pyqubo/blob/master/requirements.txt Specifies the necessary Python libraries and their minimum/exact versions required to run or develop the pyqubo project. Includes conditional dependencies based on Python version. ```Python Requirements numpy>=1.17.3 Cython==0.29.21 dimod>=0.9.14, <0.13 dwave-neal>=0.5.7 Deprecated>=1.2.10 six>=1.15.0 cmake>=3.18.4 setuptools>=56.0.0; python_version >= '3.8' scikit-build>=0.11.1 wheel>=0.36.2 coverage==4.5.1 codecov>=2.1.9 bsphinx>=0.8.3; python_version >= '3.8' bsphinx==0.3.5; python_version < '3.8' docutils<0.17,>=0.12; python_version < '3.8' ``` -------------------------------- ### Importing IFrame for IPython Display Source: https://github.com/recruit-communications/pyqubo/blob/master/notebooks/multiplier.ipynb Imports the IFrame class from IPython.display, typically used for embedding external content like images or web pages within an IPython notebook or environment. ```python from IPython.display import IFrame ``` -------------------------------- ### Finding Solutions for Two-Bit Multiplier QUBO Source: https://github.com/recruit-communications/pyqubo/blob/master/notebooks/multiplier.ipynb Defines a function that creates the QUBO model for the TwoBitMultiplier, compiles it, solves it using dimod.ExactSolver, and decodes the best solution found from the resulting sampleset. ```python def find_two_bit_multiplier_solutions(num_sol=5): x = Array.create('x', shape=(2), vartype='BINARY') y = Array.create('y', shape=(2), vartype='BINARY') p = Array.create('p', shape=(4), vartype='BINARY') H = TwoBitMultiplier(x, y, p, "mult") model = H.compile() qubo, offset = model.to_qubo() all_solutions = dimod.ExactSolver().sample_qubo(qubo) best_n_solutions = min(model.decode_sampleset(all_solutions), key=lambda x: x.energy) return best_n_solutions ``` -------------------------------- ### Importing Libraries for TSP PyQUBO Source: https://github.com/recruit-communications/pyqubo/blob/master/notebooks/TSP.ipynb Imports necessary libraries for defining, solving, and visualizing the Traveling Salesman Problem using PyQUBO. This includes PyQUBO components for arrays, placeholders, and constraints, as well as Matplotlib and NetworkX for plotting and NumPy for numerical operations. ```python %matplotlib inline from pyqubo import Array, Placeholder, Constraint import matplotlib.pyplot as plt import networkx as nx import numpy as np ```