I want to run a quantum computer with Python

Introduction

News with Google demonstrated quantum transcendence came out, and recently there was a lot of talk about quantum computers, so I was looking into it lightly. However, there was a method that anyone could try and run a quantum computer (which will be described later, but the quantum annealing method is different from the method that Google is developing). So I summarized it here. Since I am not an expert in this area, there may be some mistakes in the explanation. Please note that point.

reference

In understanding the quantum computer and actually operating the quantum computer, I referred to the following.

-World changed by quantum computer Masanobu Terabe (Author), Masayuki Ozeki (Author) Publisher; Ohmsha -D-wave Leap (Register here to run a quantum computer) -Ocean Software Documentation (Python library for running quantum computers)

What is a quantum computer

About the explanation of the quantum computer Because the explanation that appeared in the Nikkei newspaper was complete and easy to understand First of all, I will quote it as it is.

▼ Quantum computer A computer that applies the physical law "quantum mechanics" that holds in the microscopic world, such as the atoms and electrons that make up matter. Conventional computers represent and calculate information in units of "0" and "1" bits, but a huge amount of calculation is required depending on how 0s and 1s are arranged. Quantum computers, on the other hand, calculate using a special state called "superposition," which is both 0 and 1. By applying this principle, it is expected that calculations that were difficult in the past can be performed in a short time.

In a quantum computer, the existence of qubits that can have a state of superposition of ** 0 and 1 ** is very important, and using this, the best combination from all combinations can be instantly selected. It is said that the machine that can be found is a quantum computer.

There are two types of quantum computers currently under development.

method Overview Development vendor
Quantum annealing method A method specialized for task processing of combination optimization D-wave Systems etc.
Quantum gate method A general-purpose method that can calculate anything like a conventional computer Google,IBM etc.

Currently, companies are conducting demonstration experiments on quantum annealing machines. In 2011, a company called D-wave Systems in Canada started commercial sales of quantum annealing machines, and various companies are conducting demonstration experiments.

For Japanese companies, [Recruit Communications applies quantum computer to advertising optimization](http://dwavejapan.com/recruit-communications-d-wave-collaborate-apply-quantum-computing-marketing-advertising-communications- It seems that we are conducting research and development aiming at optimization /).

This time, Python runs on D-wave Systems' quantum annealing machine. ** As of November 2019, anyone can run a quantum annealing machine for free for 1 minute just by registering. ** **

Preparation

Ready to run a quantum computer

First, register as a user from the here site. You can register by simply entering your name, email address, and occupational information, and you do not need credit card information.

スクリーンショット 2019-11-09 9.44.21.png

When you log in, you will first see a screen like this at the top. On the far left, various explanation movies explain what this quantum annealing machine can do. You can see a demo of the quantum computer in the middle, but be aware that it will consume time from the one minute of the trial. On the far right is an explanation of how to run a quantum annealing machine in the Python library.

スクリーンショット 2019-11-04 18.33.11.png

If you scroll, you will also see a dashboard like this. Here you can see how long you can run the quantum computer.

スクリーンショット 2019-11-04 18.33.30.png

If you use it, the time will be reduced like this.

スクリーンショット 2019-11-09 9.53.24.png

Python library preparation

Although it is a library, it can be installed normally with pip. However, in the environment I always use, for some reason errors occurred frequently during installation, so I started the container from the image for machine learning with Docker and installed it there.

pip install dwave-ocean-sdk

After this installation is complete, execute the following command.

dwave config create

Then, the following will be displayed in order from the top, but basically you just press Enter and Please enter your API token in the "Authentication token" field. You can copy your API token from the top of My Page.

Confirm configuration file path [/home/jane/.config/dwave/dwave.conf]:
Profile (create new) [prod]:
API endpoint URL [skip]:
Authentication token [skip]:Describe your API token
Default client class (qpu or sw) [qpu]:
Default solver [skip]:
Configuration saved.

Preparations are complete here. Execute the following command to confirm that the connection is successful.

dwave ping

If it looks like this, it's OK.

Using endpoint: https://my.dwavesys.url/
Using solver: My_DWAVE_2000Q

Wall clock time:
 * Solver definition fetch: 2007.239 ms
 * Problem submit and results fetch: 1033.931 ms
 * Total: 3041.171 ms

QPU timing:
 * total_real_time = 10493 us
 * anneal_time_per_run = 20 us
 * post_processing_overhead_time = 128 us
 * qpu_anneal_time_per_sample = 20 us

Solve tasks with a quantum computer

Now, let's actually solve the task using a quantum computer.

Tasks to solve with a quantum computer

This time, it is prepared as API reference sample problem, We will solve the scheduling task with constraints.

problem

The following rules are stipulated as conditions for holding MTG. We will try to comprehensively extract the conditions under which MTG can be held without violating this rule. ** Rules ** --You must attend MTG directly on time and when you are in the office (no conference calls) --Must participate in MTG held on time (compulsory participation) --MTG outside the scheduled time must be held by telephone conference --Non-time MTG must not exceed 30 minutes

Solve the task

Problem conversion

First, convert 0 and 1 so that the above conditions can be read by the computer.

--When time is 1, it is" within time ". When it is 0, it is" outside time ". --When location is 1, it is" inside the office ". When it is 0, it is" outside the office ". --When length is 1," MTG time is 30 minutes or less "When 0," MTG time is 30 minutes or more " --When mandatory is 1," forced participation "when 0," voluntary participation "

Now, let's create a function that drops the above 0,1 conversion for the rule.

def scheduling(time, location, length, mandatory):
    if time:                                 #On time
        return (location and mandatory)      #Compulsory participation in the office
    else:                                    #Non-scheduled
        return ((not location) and length)   #Conference call less than 30 minutes

Constraints are created from this function using the library.

import dwavebinarycsp
csp = dwavebinarycsp.ConstraintSatisfactionProblem(dwavebinarycsp.BINARY)
csp.add_constraint(scheduling, ['time', 'location', 'length', 'mandatory'])

Furthermore, this is converted into a format called an aging model (quadratic form minimization problem). ** It is essential to convert the problem to this format in order for the quantum computer to solve the problem **. Although it is min_classical_gap specified by the following argument, it is not specified in the official sample code. If you keep the default, it will not work, I specified it here, but I could not find the cause even after investigating ... I would appreciate it if anyone could tell me.

bqm = dwavebinarycsp.stitch(csp, min_classical_gap=2.1)
print(bqm)
BinaryQuadraticModel({'a': -1.0, 'aux0': -2.0, 'aux1': 0.0, 'b': 2.0, 'c': 1.0, 'aux2': -1.0}, {('aux0', 'a'): 1.0, ('aux1', 'a'): 1.0, ('aux1', 'aux0'): -1.0, ('b', 'a'): -1.0, ('b', 'aux0'): -1.0, ('b', 'aux1'): -1.0, ('c', 'a'): 0.0, ('c', 'aux0'): -1.0, ('c', 'aux1'): -1.0, ('c', 'b'): 1.0, ('aux2', 'a'): 1.0, ('b', 'aux2'): -1.0, ('c', 'aux2'): 1.0}, 0.0, Vartype.SPIN)

The above output corresponds to this mathematically. \sum_i^N q_ix_i + \sum_{i

Let the quantum computer solve the problem

from dwave.system.samplers import DWaveSampler
from dwave.system.composites import EmbeddingComposite
sampler = EmbeddingComposite(DWaveSampler(endpoint='https://cloud.dwavesys.com/sapi', token='Describe your API token', solver='DW_2000Q_2_1'))

Request sampling from the quantum computer. Since the sampled results are stochastic, requesting many samples instead of one will call multiple "optimal" solutions and prevent you from settling on non-optimal solutions. The following requests 5000 samples as arguments.

response = sampler.sample(bqm, num_reads=5000)
#The solution with the smallest energy value is the optimal solution
min_energy = next(response.data(['energy']))

Let's take a look at the sampling results.

total = 0
for sample, energy, occurrences in response.data(['sample', 'energy', 'num_occurrences']):
    total = total + occurrences 
    if energy == min_energy:
        time = 'On time' if sample['time'] else 'Non-scheduled'
        location = 'office' if sample['location'] else 'Conference call'
        length = '30 minutes or less' if sample['length'] else 'Longer than 30 minutes'
        mandatory = 'Compulsory participation' if sample['mandatory'] else 'Voluntary participation'
        sub = str(sample['mandatory'])
#         print("{}: During {} at {}, you can schedule a {} meeting that is {}::{}".format(occurrences, time, location, length, mandatory, sub))
        print(" {}Is{}so,{}MTG{}It can be held at.".format(time, location, length, mandatory))
After regular hours, you can hold a conference call and hold an MTG of 30 minutes or less with voluntary participation.
You can hold an MTG of 30 minutes or less by compulsory participation in the office during the scheduled time.
You can hold an MTG longer than 30 minutes by compulsory participation in the office during the scheduled time.
You can hold an MTG longer than 30 minutes by compulsory participation in the office during the scheduled time.
You can hold an MTG longer than 30 minutes by compulsory participation in the office during the scheduled time.
It is possible to hold an MTG of 30 minutes or less by compulsory participation by telephone conference outside the regular hours.
You can hold an MTG longer than 30 minutes by compulsory participation in the office during the scheduled time.

There are multiple overlapping solutions, but all of them have been able to extract solutions that satisfy the constraints.

Next I tried running a quantum computer for the time being, but there were a lot of things I didn't understand, such as the QUBO matrix and the aging model, so I would like to study if I have time. Also, this time the amount of data carried out in the test was small, and since this quantum computer itself was connected in the cloud, I could not really feel the calculation speed of the topic. I think this area is an area that is advancing day by day, so I would like to follow it properly.

Recommended Posts

I want to run a quantum computer with Python
I want to make a game with Python
I want to work with a robot in python.
I want to debug with Python
I want to build a Python environment
I want to analyze logs with Python
I want to use a wildcard that I want to shell with Python remove
I want to do a full text search with elasticsearch + python
[Introduction] I want to make a Mastodon Bot with Python! 【Beginners】
I want to create a window in Python
I want to use Temporary Directory with Python2
#Unresolved I want to compile gobject-introspection with Python3
I want to solve APG4b with Python (Chapter 2)
I want to embed a variable in a Python string
I want to easily implement a timeout in python
I want to iterate a Python generator many times
I want DQN Puniki to hit a home run
I want to generate a UUID quickly (memorandum) ~ Python ~
I want to transition with a button in flask
I want to climb a mountain with reinforcement learning
I tried to draw a route map with Python
I want to write in Python! (2) Let's write a test
I want to randomly sample a file in Python
I want to inherit to the back with python dataclass
From buying a computer to running a program with python
I want to split a character string with hiragana
[Python] I want to make a nested list a tuple
I tried to automatically generate a password with Python3
I want to AWS Lambda with Python on Mac!
I want to manually create a legend with matplotlib
[ML Ops] I want to do multi-project with Python
I want to bind a local variable with lambda
I made a fortune with Python.
I want to do ○○ with Pandas
I made a daemon with Python
I want to be able to analyze data with Python (Part 3)
I want to specify another version of Python with pyvenv
I want to be able to analyze data with Python (Part 1)
I made a package to filter time series with python
I wrote a program quickly to study DI with Python ①
I want to make a blog editor with django admin
I want to start a jupyter environment with one command
I want to start a lot of processes from python
I want to make a click macro with pyautogui (desire)
I want to be able to analyze data with Python (Part 4)
I want to be able to analyze data with Python (Part 2)
I want to make a click macro with pyautogui (outlook)
[Python] I want to use the -h option with argparse
I want to use a virtual environment with jupyter notebook!
I want to install a package from requirements.txt with poetry
[Visualization] I want to draw a beautiful graph with Plotly
I want to be able to run Python in VS Code
I want to make input () a nice complement in python
[Python] I want to use only index when looping a list with a for statement
I want to tell people who want to import from a higher directory with Python direnv
[Mac] I want to make a simple HTTP server that runs CGI with Python
[5th] I tried to make a certain authenticator-like tool with python
I want to detect objects with OpenCV
I made a library to easily read config files with Python
I want to know the weather with LINE bot feat.Heroku + Python
I want to monitor UNIQLO + J page updates [Scraping with python]