{ "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. 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 quantum 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 Optimisation](https://quantumcomputinginc.com/learn/tutorials-and-use-cases/portfolio-optimization-equal-weights-dirac1)\n", "* [Quadratic Assignment Problem](https://quantumcomputinginc.com/learn/tutorials-and-use-cases/qap-tutorial)\n", "* [Feature Selection](https://quantumcomputinginc.com/learn/tutorials-and-use-cases/select-features-tutorial)\n", "* [Travelling Salesperson](https://quantumcomputinginc.com/learn/tutorials-and-use-cases/tsp-tutorial)\n", "* [Set Partitioning](https://quantumcomputinginc.com/learn/tutorials-and-use-cases/set-partition-tutorial) (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. \n", "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 numpy as np\n", "from qci_client import QciClient" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [], "source": [ "token = \"your_token\"\n", "api_url = \"https://api.qci-prod.com\"\n", "qclient = QciClient(api_token=token, url=api_url)" ] }, { "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": 7, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "array([[ 1, 0, 1, -1],\n", " [ 2, 2, 0, -2]])" ] }, "execution_count": 7, "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": 5, "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": 8, "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": 10, "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": null, "metadata": {}, "outputs": [], "source": [ "job_body = qclient.build_job_body(\n", " job_type=\"sample-constraint\",\n", " job_params={\"num_samples\": 40, \"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": 13, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'file_id': '662fb18e98263204a365421a',\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": 13, "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": 15, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "2024-04-29 15:42:24 - Dirac allocation balance = 0 s (unmetered)\n", "2024-04-29 15:42:24 - Job submitted: job_id='662fb1d0e15a79bd9d02c48e'\n", "2024-04-29 15:42:25 - QUEUED\n", "2024-04-29 15:42:27 - RUNNING\n", "2024-04-29 15:52:37 - COMPLETED\n", "2024-04-29 15:52:40 - Dirac allocation balance = 0 s (unmetered)\n" ] }, { "data": { "text/plain": [ "{'job_info': {'job_id': '662fb1d0e15a79bd9d02c48e',\n", " 'job_submission': {'problem_config': {'quadratic_linearly_constrained_binary_optimization': {'constraints_file_id': '662fb18e98263204a365421a',\n", " 'objective_file_id': '662fb18f98263204a365421c',\n", " 'alpha': 2,\n", " 'atol': 1e-10}},\n", " 'device_config': {'dirac-1': {'num_samples': 40}}},\n", " 'job_status': {'submitted_at_rfc3339nano': '2024-04-29T14:42:24.965Z',\n", " 'queued_at_rfc3339nano': '2024-04-29T14:42:24.965Z',\n", " 'running_at_rfc3339nano': '2024-04-29T14:42:25.491Z',\n", " 'completed_at_rfc3339nano': '2024-04-29T14:52:37.443Z'},\n", " 'job_result': {'file_id': '662fb43598263204a365423e', 'device_usage_s': 79}},\n", " 'status': 'COMPLETED',\n", " 'results': {'counts': [21, 19],\n", " 'energies': [-10, -10],\n", " 'feasibilities': [True, True],\n", " 'objective_values': [0, 0],\n", " 'solutions': [[0, 1, 1], [1, 0, 0]]}}" ] }, "execution_count": 15, "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": 13, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'No errors detected'" ] }, "execution_count": 13, "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 lesson, 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 and use cases listed at the beginning of this tutorial." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "testing", "language": "python", "name": "testing" }, "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.12.3" } }, "nbformat": 4, "nbformat_minor": 4 }