{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# QLCBO on Dirac\n",
"#### Device: Dirac-1\n",
"\n",
"## Introduction\n",
"Quadratic Linearly Constrained Binary Optimization, or QLCBO, is a fundamental building block for optimizing where the primary goal is maximizing or minimizing a function that has both quadratic terms (involving pairwise products of decision variables) and linear constraints (applied to sums of terms). Furthermore, QLCBO problems serve as fundamental building blocks for more complex optimization models that can address many real world problems. This tutorial will go through why QLCBOs are valuable, what they can do, and how to run such problems on QCi's Dirac entropy computing systems.\n",
"\n",
"\n",
"## Importance\n",
"\n",
"In general, the QLCBO formulation allows a combination of the types of constraints that more typically appear in traditional computer science, as well as quadratic terms that naturally arise in physics-based hardware such as ours. Note that if the $O$ matrix is diagonal then QLCBO reduces to standard binary linear programming, but the off-diagonal terms allow the quadratic interactions that are native to our device to be added. This could be useful for example if formulating a [quadratic knapsack problem](https://en.wikipedia.org/wiki/Quadratic_knapsack_problem) with a global constraint on weights but a quadratic objective function. Terms of this form tend to arise because physical interactions are naturally two-body. By providing a way to effectively use a binary linear programming problem as a starting point, the QLCBO formulation allows a natural way to start with an existing model and then add complexity. This may correspond to the kind of quadratic terms on which systems like ours excel, and provide a bridge from a linear programming setting that may be more familiar to some of our users to a quadratic setting that is more natural for quantum hardware.\n",
"\n",
"## Applications\n",
"\n",
"Because of its versatility and the sample constraint function, our software implementation of QLCBO is the workhorse of many tutorial examples using Dirac-1, and is likely to be the same for many of your use cases. The following tutorials and use cases rely on constructing a QLCBO problem:\n",
"\n",
"* [Portfolio Optimization](https://quantumcomputinginc.com/learn/tutorials-and-use-cases/portfolio-optimization-on-dirac)\n",
"* [Quadratic Assignment Problem](https://quantumcomputinginc.com/learn/tutorials-and-use-cases/quadratic-assignment-on-dirac)\n",
"* [Feature Selection](https://quantumcomputinginc.com/learn/tutorials-and-use-cases/feature-selection-on-dirac)\n",
"* [Travelling Salesperson](https://quantumcomputinginc.com/learn/tutorials-and-use-cases/traveling-salesperson-on-dirac)\n",
"* [Set Partitioning](https://quantumcomputinginc.com/learn/tutorials-and-use-cases/set-partitioning-on-dirac) (A QUBO is sent to the device, but linear constraints are used)\n",
"\n",
"## Mathematical Definition\n",
"Quadratic Unconstrained Binary Optimization (QUBO) problems can be formulated from a square, symmetric objective function and a matrix of binary constraints. Suppose we are given an objective function, $O$, of dimension $n \\times n$, and a set of $m$ constraints, represented by the matrix $A$, with dimension $m \\times n$ and right-hand side vector $b$ of length $m$. We want to combine them into a QUBO, which can be defined as $Q = O + \\alpha (A^T A-2\\mathrm{diag}(b^TA))$, where $\\alpha \\in \\mathbb{R}$. At this point, we can find an optimal solution,\n",
"$x^{*} = \\min_{x} x^T Q x$. \n",
"The parameter $\\alpha$ plays an important role in guaranteeing that the constraints are satisfied. We will not go into more detail on this page, but we will define a simple problem on the Upload tab and show how to upload the components.\n",
"Suppose the original problem we want to minimize is \n",
"$-3xy + xz,$\n",
"subject to the constraints $x + z = 1$ and $2x + 2y= 2$.\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Uploading\n",
"There are three matrix components that can be associated with a constraint problem of this type. The objective function in matrix form, the linear constraints matrix, and the right-hand side (RHS) represent the linear constraints themselves. The format should follow the transformation from $\\mathbf{A}\\vec{x}$ = $\\vec{b}$ → $\\mathbf{A}\\vec{x}$ - $\\vec{b}$ = 0."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Uploading and file_id's\n",
"First, import the necessary packages:"
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [],
"source": [
"import os\n",
"import numpy as np\n",
"from qci_client import QciClient"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [],
"source": [
"# The following gets your access token from the os envirinment, if configured.\n",
"# It is preferable to configure that way, but you may also specify in code otherwise\n",
"# see the Quick Start on Cloud tutorial at \n",
"# https://quantumcomputinginc.com/learn/tutorials-and-use-cases/quick-start-on-cloud\n",
"# to learn how to set the environment variables\n",
"token = os.environ.get(\"QCI_TOKEN\", None)\n",
"if token is None:\n",
" # environment variables not configured\n",
" api_url = \"https://api.qci-prod.com\"\n",
" token = \"REPLACE WITH YOUR TOKEN\"\n",
" qclient = QciClient(url=api_url, api_token=token)\n",
"else:\n",
" qclient = QciClient()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Formation\n",
"For the equation above, $\\mathbf{A}\\vec{x}$ - $\\vec{b}$ = 0, we will break it down into an objective function and constraints.
\n",
"
\n",
"→ $\\mathbf{A}$ as the objective function, `obj`
\n",
"→ $\\vec{b}$ as the constraints (`b` & `rhs`)"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [],
"source": [
"obj = np.array([[ 0. , -1.5, 0.5],\n",
" [-1.5, 0. , 0. ],\n",
" [ 0.5, 0. , 0. ]])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The constraints take the form and an explicit RHS vector can be represented as \n"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"(array([[1, 0, 1],\n",
" [2, 2, 0]]),\n",
" array([[-1],\n",
" [-2]]))"
]
},
"execution_count": 4,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"b = np.array([[1, 0, 1],\n",
" [2, 2, 0]])\n",
"rhs = -(np.array([[1],\n",
" [2]]))\n",
"b, rhs"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([[ 1, 0, 1, -1],\n",
" [ 2, 2, 0, -2]])"
]
},
"execution_count": 5,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"constraints = np.hstack((b, rhs))\n",
"constraints"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Concatenate your objective function and constraints into two dictionaries: "
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [],
"source": [
"qlcbo_obj = {\n",
" 'file_name': \"smallest_objective.json\",\n",
" 'file_config': {'objective':{\"data\": obj, \"num_variables\": 3}}\n",
"}"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {},
"outputs": [],
"source": [
"qlcbo_constraints = {\n",
" \"file_name\": \"smallest_constraints.json\",\n",
" \"file_config\": {'constraints':{\"data\": constraints,\n",
" \"num_constraints\": 2,\n",
" \"num_variables\": 3}}\n",
"}"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n",
"Now we can upload the various files using the client. Suppose we store the data in a variable data, then we call upload_file to push the data to the server.\n"
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {},
"outputs": [],
"source": [
"response_json = qclient.upload_file(file=qlcbo_constraints)\n",
"file_id_constraints = response_json[\"file_id\"]\n",
"\n",
"response_json = qclient.upload_file(file=qlcbo_obj)\n",
"file_id_obj = response_json[\"file_id\"]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n",
"\n",
"We can extract the file_id for later use. Triggering a job to run requires the file_id to tell the backend which data to use. We cover this step in the Running Section.\n",
"## Running\n",
"Running a job involves two key steps to build parameters for the job:\n",
"1. Building a job body to submit. \n",
"2. Providing a job_type.\n",
"\n",
"### Building the job_body\n",
"The job_body is a dictionary that contains the file_id's and parameter data for running the job. All job bodies must contain the following data fields, which can be leveraged by the user to track jobs. \n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n",
"It is easiest to use `qci.build_job_body()` to construct a job_body."
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {},
"outputs": [],
"source": [
"job_body = qclient.build_job_body(\n",
" job_type=\"sample-constraint\",\n",
" job_params={\"num_samples\": 1, \"alpha\": 2, \"device_type\": \"dirac-1\"},\n",
" constraints_file_id=file_id_constraints,\n",
" objective_file_id=file_id_obj)"
]
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"{'file_id': '664e6d9798263204a3659050',\n",
" 'num_parts': 1,\n",
" 'num_bytes': 373,\n",
" 'file_name': 'smallest_constraints.json',\n",
" 'file_config': {'constraints': {'num_constraints': 2,\n",
" 'num_variables': 3,\n",
" 'data': [{'i': 0, 'j': 0, 'val': 1},\n",
" {'i': 0, 'j': 2, 'val': 1},\n",
" {'i': 0, 'j': 3, 'val': -1},\n",
" {'i': 1, 'j': 0, 'val': 2},\n",
" {'i': 1, 'j': 1, 'val': 2},\n",
" {'i': 1, 'j': 3, 'val': -2}]}}}"
]
},
"execution_count": 10,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"qclient.download_file(file_id=file_id_constraints)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n",
"This returns a job_body with the file_id fields appended to the above dictionary. Each of these file_id's was obtained after uploading the corresponding file in the Uploading section. \n",
"Now we can trigger a job using the following command:\n"
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"2024-05-22 16:11:36 - Dirac allocation balance = 0 s (unmetered)\n",
"2024-05-22 16:11:36 - Job submitted: job_id='664e6d98a3e6a645a5c4d479'\n",
"2024-05-22 16:11:36 - QUEUED\n",
"2024-05-22 16:11:38 - RUNNING\n",
"2024-05-22 16:11:49 - COMPLETED\n",
"2024-05-22 16:11:51 - Dirac allocation balance = 0 s (unmetered)\n"
]
},
{
"data": {
"text/plain": [
"{'job_info': {'job_id': '664e6d98a3e6a645a5c4d479',\n",
" 'job_submission': {'problem_config': {'quadratic_linearly_constrained_binary_optimization': {'constraints_file_id': '664e6d9798263204a3659050',\n",
" 'objective_file_id': '664e6d9798263204a3659052',\n",
" 'alpha': 2,\n",
" 'atol': 1e-10}},\n",
" 'device_config': {'dirac-1': {'num_samples': 1}}},\n",
" 'job_status': {'submitted_at_rfc3339nano': '2024-05-22T22:11:36.179Z',\n",
" 'queued_at_rfc3339nano': '2024-05-22T22:11:36.179Z',\n",
" 'running_at_rfc3339nano': '2024-05-22T22:11:36.677Z',\n",
" 'completed_at_rfc3339nano': '2024-05-22T22:11:46.529Z'},\n",
" 'job_result': {'file_id': '664e6da298263204a3659054', 'device_usage_s': 10}},\n",
" 'status': 'COMPLETED',\n",
" 'results': {'counts': [1],\n",
" 'energies': [-10],\n",
" 'feasibilities': [True],\n",
" 'objective_values': [0],\n",
" 'solutions': [[1, 0, 0]]}}"
]
},
"execution_count": 11,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"job_response = qclient.process_job(job_body=job_body)\n",
"job_response\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Below we show how to query the result object if an error occurs:"
]
},
{
"cell_type": "code",
"execution_count": 12,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'No errors detected'"
]
},
"execution_count": 12,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"def error_status(job_response):\n",
" try:\n",
" if job_response['status'] == \"ERROR\":\n",
" return job_response['status'], job_response['job_info']['results']['error']\n",
" else:\n",
" return \"No errors detected\"\n",
" except KeyError:\n",
" return \"Error: Unable to retrieve error status information from the job response\"\n",
"\n",
"error_status(job_response)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Conclusion\n",
"\n",
"In this tutorial, we have shown how to make use of the quadratic linearly constrained optimization formulation of problems. By combining quadratic objective functions with linear constraints, QLCBOs provide a powerful and versatile setting for formulating problems. These problems act as a workhorse for many of our other examples and prove to be particularly valuable as the problem size increases. If you feel comfortable with the QLCBO formulation and want to go further, a good next step is to see how it works in practice through the tutorials listed in this [module](https://quantumcomputinginc.com/learn/module/understanding-qlcbos). Another alternative would be to work through examples using the unconstrained version [QUBO](https://quantumcomputinginc.com/learn/tutorials-and-use-cases/qubo-on-dirac). Of course, you could also try out some of your own problems."
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.10.12"
}
},
"nbformat": 4,
"nbformat_minor": 4
}