Welcome to Madness . Quantum Computing and it’s application in Retail with a use case.

Prag Tyagi
towardsdataanalytics
15 min readSep 16, 2021

Quantum Computing : A word which looks very attractive and kind of Jazzy to be frank . It is a field which is in very nascent stages of adoption across industry but carries a potential with no boundaries . With the explosion of growth in data in all walks of life , it has become imperative to run through the same via analytics use case . With that perspective in mind with such humongous use cases coming up in future it will be difficult for current tools and platforms to catch up on this front and provide the required computational resources . So what is the answer . Quantum is . It’s a whole new realm in itself . Now enough of description let’s get onto some serious business .

What is Quantum Computing ?

Quantum Computing is the process in which we perform computations on Quantum Computer. So to understand what it is underneath and how it performs complex computations so easily we first need to understand what is a Quantum Computer and what differentiates it from rest of the computing systems currently available .

Classical computers works on bits weather it’s your local computer or cloud compute resource . When we talk about bits it’s either ‘0’ or ‘1’ . Internally any operation you perform on your computer gets converted into these 2 states . Now this phenomenon indicates 2 pointers . One is that either any of your state can be’0’ or it can be ‘1’ but can’t exist in a state where it can be anything till the point you arrive at the final solution. Second this makes things to run in an orderly sequence no matter what parallelization you intend to implement on the application layer . But that’s not the case with Quantum computers . It is this basic difference on molecular level that differentiates Quantum Computers .

Molecular difference: Quantum Computer works on Qubit . Now this a revolutionary concept . A qubit (or quantum bit) is the quantum mechanical analogue of a classical bit. In classical computing the information is encoded in bits, where each bit can have the value zero or one. In quantum computing the information is encoded in qubits. A qubit is a two-level quantum system where the two basis qubit states are usually written as ∣0⟩ and |1⟩ . A qubit can be in state ∣0⟩,|1⟩ or (unlike a classical bit) in a linear combination of both states. The name of this phenomenon is superposition.

Superposition : One of the properties that sets a qubit apart from a classical bit is that it can be in superposition. Superposition is one of the fundamental principles of quantum mechanics. In classical physics, a wave describing a musical tone can be seen as several waves with different frequencies that are added together, superposed. Similarly, a quantum state in superposition can be seen as a linear combination of other distinct quantum states. This quantum state in superposition forms a new valid quantum state.

A typical example visualizing superposition is the double-slit experiment. This experiment is explained in the following images . First 2 images are showing the movement of a classical particle where as the last one showing the movement of a quantum particle.

A Classical particle going in 1 particular upward direction .
A Classical particle going in 1 particular downward direction .
Quantum particle passing through the slit in a form of path

Qubits can be in a superposition of both the basis states ∣0⟩ and ∣1⟩. When a qubit is measured (to be more precise: only observables can be measured), the qubit will collapse to one of its eigenstates and the measured value will reflect that state. For example, when a qubit is in a superposition state of equal weights, a measurement will make it collapse to one of its two basis states ∣0⟩ and |1⟩ with an equal probability of 50%. ∣0⟩is the state that when measured, and therefore collapsed, will always give the result 0. Similarly, |1⟩ will always convert to 1.A quantum computer consisting of n qubits can exist in a superposition of 2^n states.

Confused ? Does this make any sense to you guys ? Believe me , even I was having the same expression you all are having when I started with this . So let me make this simple for you from computation understanding side .

A classical computer will work on bits . So for any operation it will have only 1 state at any point of time . Either 1 or 0 .

A quantum computer will maintain a continuous state of both 1 and 0 till a solution is achieved . For ex a 2 qubit quantum computer will have 2² = 4 states at any point of time as compared to 1 state being possessed by a classical computer . That’s a 300% faster potential . Imagine if you get a 2⁵² qubit quantum system like Google, what computation power we are taking about here .

Entanglement : One of the other counter-intuitive phenomena in quantum physics is entanglement. A pair or group of particles is entangled when the quantum state of each particle cannot be described independently of the quantum state of the other particle(s). The quantum state of the system as a whole can be described; it is in a definite state, although the parts of the system are not.When two qubits are entangled there exists a special connection between them. The entanglement will become clear from the results of measurements. The outcome of the measurements on the individual qubits could be 0 or 1. However, the outcome of the measurement on one qubit will always be correlated to the measurement on the other qubit. This is always the case, even if the particles are separated from each other by a large distance.

For example, two particles are created in such a way that the total spin of the system is zero. If the spin of one of the particles is measured on a certain axis and found to be counterclockwise, then it is guaranteed that a measurement of the spin of the other particle (along the same axis) will show the spin to be clockwise. This seems strange, because it appears that one of the entangled particles “feels” that a measurement is performed on the other entangled particle and “knows” what the outcome should be, but this is not the case. This happens, without any information exchange between the entangled particles. They could even be billions of miles away from each other and this entanglement would still be present.

A common misunderstanding is that entanglement could be used to instantaneously send information from one point to another. This is not possible because although it is possible to know the state of the other particle when measuring one, the measurement results of the individual particles are random. There is no way to predetermine the individual result, therefore it is not possible to send a message in this way.

Layman Explanation :- If you are not able to get the meaning of this concept from above description then let’s put it in more simpler words .Let’s say you have 2 boxes on a table . Both the boxes are exactly same in appearance and dimensions . Now you know that one box is having apple and other one is having banana in it . Let’s place both of them on table . If you open one box and find out that is containing apple and then you need not to open another box as you already know that other box would be having banana . But what you observed here is known as entanglement. Knowing the state of one object make you aware about the state of the associated object .

Quantum annealing : It is a process for finding the global minimum of a given objective function over a given set of candidate solutions (candidate states), by a process using quantum fluctuations (in other words, a meta-procedure for finding a procedure that finds an absolute minimum size/length/cost/distance from within a possibly very large, but nonetheless finite set of possible solutions using quantum fluctuation-based computation instead of classical computation). Quantum annealing is used mainly for problems where the search space is discrete (optimization problems) with many local minima such as finding the ground state of a spin glass or the traveling salesman problem.

Power of Quantum

The fact that qubits can be entangled, makes a quantum computer more powerful than a classical computer. With the information stored in superposition, some problems can be solved exponentially faster.

Question : How to Code

Now the main question which strikes your mind is that how to code your problem using Quantum Computer . Well I will delve details here from a coder perspective and not as a physics professor . In many blogs you might have seen people showcasing scary Quantum spheres and Gates and circuits .Those are also essential to understand but some people get confused midway that they are evaluating computing or studying physics. There are some basic steps you need to take to formulate your problem as Quantum computer takes input in a specific format and provide results not in a traditional manner but in the form of an optimized pattern which you need to decipher and arrive at the final conclusion .

First, we prepare the superposition. Then we encode the problem information into the superposition and manipulate it in a high dimensional space. Finally, we apply interference to consolidate the superposition into fewer outcomes.

Steps to formulate a problem .

There are multiple vendors which provides services of Quantum Computer . Each vendor provides their own SDK to assist in implementation of a problem in the form of Code . For Ex : Dwave provides Ocean SDK , IBM provides Qiskit and the list goes on . Although the computation duration provided by these vendors for free is small but enough for you to extract one or two good use cases . In our problem statement we are going to use Dwave’s Ocean SDK and the free Computation service they provide .

How a D-Wave System Solves Problems

For quantum computing, as for classical, solving a problem requires that it be formulated in a way the computer and its software understand.

For example, if you want your laptop to calculate the area of a $1 coin, you might express the problem as an equation, A = pi *r² , that you program as math.pi*13.245**2 in your Python CLI. For a laptop with Python software, this formulation—a particular string of alphanumeric symbols—causes the manipulation of bits in a CPU and memory chips that produces the correct result.

The D-Wave system uses a quantum processing unit (QPU) to solve a binary quadratic model (BQM) : given N variables x1,….x(n),where each variable x(i) can have binary values 0 or 1,the system finds assignments of values that minimize

where q(i) and q(i,j) are configurable (linear and quadratic) coefficients. To formulate a problem for the D-Wave system is to program q(i) and q(i,j) so that assignments of x(1) ,….,x(N) also represent solutions to the problem.

The “native” forms of BQM programmed into a D-Wave system are the Ising model traditionally used in statistical mechanics and its computer-science equivalent, shown here, the QUBO.

Ocean software can abstract away much of the mathematics and programming for some types of problems. At its heart is a binary quadratic model (BQM) class that together with other Ocean tools helps formulate various optimization problems. It provides an API to binary quadratic samplers(the component used to minimize a BQM and therefore solve the original problem), such as the D-Wave system, Leap’s hybrid quantum-classical solvers,and classical algorithms you can run on your computer

At a higher level of abstraction, it also provides a discrete quadratic model (DQM) class that can be used, for example, by the hybrid DQM samplers offered by Leap.

Please find below this problem-solving procedure in two steps (plus a third that may benefit some problems)

i)Formulate Your Problem for a Quantum Computer

ii)Sample the BQM on a Solver.

iii)Improve the Solutions, if needed, using advanced features.

Solution steps: (1) a problem known in “problem space” (a circuit of Boolean gates, a graph, a network, etc) is formulated as a BQM, mathematically or using Ocean functionality and (2) the BQM is sampled for solutions.

Retail Use Case : Mark Down Optimization

Let’s say I own a chain of fashion outlets across country . Currently I have a network of 10,000 stores . In each store I have 100 product category . Under each product category I have further 100 sub product category . Under each sub-product category I have 100 products . Now I have to launch a seasonal sale in my stores . What discount percentage I can offer on each of my product to maximize my sales , increase my sell through and also it should not create a pressure on my margin and profitability . And my discount range is [0,10,20,30] percentage

Now if we look at this problem statement from the perspective where we need to offer discount on each product from a range of discount percentage that turns this problem into 10000 * 100 * 100 * 4 = 400000000 combinations for each product . This is way more to handle by traditional computing resources . Now let’s formulate our problem and data set .

One more point to consider is that Quantum computer doesn’t give insights like other traditional computing solutions . You need to design your BQM model first and then place that into Quantum Solvers matrix . Then it will provide insights in the form of energy states and we need to pick the most optimized least energy state .

Sample Data set just for Demo

Let’s install Dwave system libraries first

Now let’s install Ocean SDK

To solve a problem on D-Wave solvers you formulate the problem as an objective function, usually in Ising or QUBO format. Low energy states of the objective function represent good solutions to the problem. Because you can represent the objective function as a graph, you can map it to the QPU linear coefficients to qubit biases and quadratic coefficients to coupler strengths. The QPU uses quantum annealing to seek the minimum of the resulting energy landscape, which corresponds to the solution of your problem.

Layman Explanation :- Import Dwave solver . Formulate your problem into a form of multi dimensional Binary Quadratic model matrix . Feed this matrix into DWave solvers . You will get result in the form of 1 or 0 towards energy state . To which ever discount code you get minimum energy state , bingo that’s your optimized discount percentage .

dwave-neal will be used to implement quantum annealing .

To configure solver access you can use the dwave config command.

Now let’s import all the libraries .

We need to access D-Wave’s Solver API (SAPI) . It provides access to solvers, remote compute resources for solving problems such as a D-Wave system or Leap‘s quantum-classical hybrid solvers. The requisite information for problem submission through SAPI includes:

1.API endpoint URL

A URL to the remote resources. By default, https://cloud.dwavesys.com/sapi is used to connect to resources provided by D-Wave’s Leap quantum cloud service, including D-Wave quantum computers.

2.API Token

An authentication token used to authenticate the client session when you connect to the remote environment. Because tokens provide authentication, user names and passwords are not required in your code.

3.Solver

A D-Wave resource to be used to solve your submitted problems; for example, a hybrid solver or a D-Wave 2000Q quantum computer.

You can find all the above information when you log in to your D-Wave account. For Leap users, select the Dashboard tab; for on-premises (Qubist) users, select the Solver API tab and the API Tokens menu item under your user name.

You save your SAPI configuration (URL, API token, etc) in a D-Wave Cloud Client configuration file that Ocean tools use unless overridden explicitly or with environment variables. Your configuration file can include one or more solvers.

To create API token go to this link : https://cloud.dwavesys.com/sapiand create your account . There It will provide you for an API token .

run the dwave sample --random-problem command to submit a random problem to a remote solver to test weather your solver is running or not .

you can query solvers available for a SAPI URL and API token using dwave-cloud-client get_solvers() function. For example, the code below queries available solvers for your default SAPI URL and a specified token.

>>> from dwave.cloud import Client
>>> client = Client.from_config(token='ABC-123456789123456789123456789')
>>> client.get_solvers()
[Solver(id='2000Q_ONLINE_SOLVER1'),
UnstructuredSolver(id='hybrid_binary_quadratic_model_version2')]
Find solvers for your default SAPI URL and a specified token

Now we have to specify a solver programmatically which our DWave system will pick to run our BQM model .

Specifying solver

Now in the above screenshot we have taken solver with the least average load since it is a POC . But there is another way where you can select a more high performing solver .

sampler = DWaveSampler(solver=dict(order_by='-properties.max_anneal_schedule_points'))

Now it’s time to bring in the data set . Let’s summon some pandas here.

Now let’s extract unique values for features of week , product and discount range .

Extracting unique features

Now let’s fine tune our data set .

Now let’s create the final dictionary of our results and create sample and energy global variable . Our final destination parameters .

Now let’s import some libraries .

minorminer : It is a library of tools for finding graph minor embedding, developed to embed Ising problems onto quantum annealers (QA).

itertools:Python’s Itertool is a module that provides various functions that work on iterators to produce complex iterators. This module works as a fast, memory-efficient tool that is used either by themselves or in combination to form iterator algebra . Since we will be dealing in multi dimension matrix this library would be very useful.

dimod : It is a shared API for samplers. It provides classes for quadratic models

networkx : It is a Python package for the creation, manipulation, and study of the structure, dynamics, and functions of complex networks.

FixedEmbeddingComposite : Converts the QUBO into a BinaryQuadraticModel and then calls sample()

DWaveCliqueSampler : A sampler for solving clique binary quadratic models on the D-Wave system.

Solver limit : No of times Annealing iteration will happen.

Now we will follow following steps .

i)Iterate through demand week over week

ii)2D Matrix creation of Qubo . Row will be product and column will be discount

iii)Filling the matrix with random values for normal distribution between -1 and 1

iv)Filling matrix with final value

v)Fetching column range for each iteration

vi)Final pivot with Discount vs product comparison

vii)Implement cannibalization with dummy values and other factors

viii)Assign weight for all metrics

ix)Create dictionary and feed into Qubo matrix

x)Forming topology

xi)Creating binary quadratic model

xiii)Finding sample with lowest energy

Now let’s take sample and iterate through the final energy states .

Final Results :

For product one recommended energy states are for Discount percentage 0, 20 and 30 . Now among these least energy state is the most optimized one which is 0 % . So even if we don’t offer any discount on P1 we will get good sales

For product 2 we have only one positive energy state for 10% discount range which means that if we offer discount 10% discount on P2 then we will see increase in sales and profit along with optimized margins.

Same trend will continue for all millions of product in your portfolio . All this operation finished in 1/10000 part of second for me . So imagine how fast Quantum computer takes us into solving complex problem .

I hope your not bored . Let’s stop this use case here . But more is in store . Stay tuned for further blogs on this .

--

--

Prag Tyagi
towardsdataanalytics

Senior leader and a technologist having 14+ years of experience in Data Analytics. Passionate to share new concepts and learning in Data Analytics domain.