Giter VIP home page Giter VIP logo

qiskit / qiskit Goto Github PK

View Code? Open in Web Editor NEW
4.6K 211.0 2.2K 129.98 MB

Qiskit is an open-source SDK for working with quantum computers at the level of extended quantum circuits, operators, and primitives.

Home Page: https://www.ibm.com/quantum/qiskit

License: Apache License 2.0

Python 94.87% Makefile 0.02% Jupyter Notebook 0.01% C++ 0.04% OpenQASM 1.17% TeX 0.35% Shell 0.03% Pascal 0.02% Rust 3.49%
quantum-computing qiskit sdk quantum-programming-language quantum-circuit quantum python

qiskit's Introduction

Qiskit

License Current Release Extended Support Release Downloads Coverage Status PyPI - Python Version Minimum rustc 1.70 Downloads DOI

Qiskit is an open-source SDK for working with quantum computers at the level of extended quantum circuits, operators, and primitives.

This library is the core component of Qiskit, which contains the building blocks for creating and working with quantum circuits, quantum operators, and primitive functions (sampler and estimator). It also contains a transpiler that supports optimizing quantum circuits and a quantum information toolbox for creating advanced quantum operators.

For more details on how to use Qiskit, refer to the documentation located here:

https://docs.quantum.ibm.com/

Installation

Warning

Do not try to upgrade an existing Qiskit 0.* environment to Qiskit 1.0 in-place. Read more.

We encourage installing Qiskit via pip:

pip install qiskit

Pip will handle all dependencies automatically and you will always install the latest (and well-tested) version.

To install from source, follow the instructions in the documentation.

Create your first quantum program in Qiskit

Now that Qiskit is installed, it's time to begin working with Qiskit. The essential parts of a quantum program are:

  1. Define and build a quantum circuit that represents the quantum state
  2. Define the classical output by measurements or a set of observable operators
  3. Depending on the output, use the primitive function sampler to sample outcomes or the estimator to estimate values.

Create an example quantum circuit using the QuantumCircuit class:

import numpy as np
from qiskit import QuantumCircuit

# 1. A quantum circuit for preparing the quantum state |000> + i |111>
qc_example = QuantumCircuit(3)
qc_example.h(0)          # generate superpostion
qc_example.p(np.pi/2,0)  # add quantum phase
qc_example.cx(0,1)       # 0th-qubit-Controlled-NOT gate on 1st qubit
qc_example.cx(0,2)       # 0th-qubit-Controlled-NOT gate on 2nd qubit

This simple example makes an entangled state known as a GHZ state $(|000\rangle + i|111\rangle)/\sqrt{2}$. It uses the standard quantum gates: Hadamard gate (h), Phase gate (p), and CNOT gate (cx).

Once you've made your first quantum circuit, choose which primitive function you will use. Starting with sampler, we use measure_all(inplace=False) to get a copy of the circuit in which all the qubits are measured:

# 2. Add the classical output in the form of measurement of all qubits
qc_measured = qc_example.measure_all(inplace=False)

# 3. Execute using the Sampler primitive
from qiskit.primitives.sampler import Sampler
sampler = Sampler()
job = sampler.run(qc_measured, shots=1000)
result = job.result()
print(f" > Quasi probability distribution: {result.quasi_dists}")

Running this will give an outcome similar to {0: 0.497, 7: 0.503} which is 000 50% of the time and 111 50% of the time up to statistical fluctuations. To illustrate the power of Estimator, we now use the quantum information toolbox to create the operator $XXY+XYX+YXX-YYY$ and pass it to the run() function, along with our quantum circuit. Note the Estimator requires a circuit without measurement, so we use the qc_example circuit we created earlier.

# 2. Define the observable to be measured 
from qiskit.quantum_info import SparsePauliOp
operator = SparsePauliOp.from_list([("XXY", 1), ("XYX", 1), ("YXX", 1), ("YYY", -1)])

# 3. Execute using the Estimator primitive
from qiskit.primitives import Estimator
estimator = Estimator()
job = estimator.run(qc_example, operator, shots=1000)
result = job.result()
print(f" > Expectation values: {result.values}")

Running this will give the outcome 4. For fun, try to assign a value of +/- 1 to each single-qubit operator X and Y and see if you can achieve this outcome. (Spoiler alert: this is not possible!)

Using the Qiskit-provided qiskit.primitives.Sampler and qiskit.primitives.Estimator will not take you very far. The power of quantum computing cannot be simulated on classical computers and you need to use real quantum hardware to scale to larger quantum circuits. However, running a quantum circuit on hardware requires rewriting them to the basis gates and connectivity of the quantum hardware. The tool that does this is the transpiler and Qiskit includes transpiler passes for synthesis, optimization, mapping, and scheduling. However, it also includes a default compiler which works very well in most examples. The following code will map the example circuit to the basis_gates = ['cz', 'sx', 'rz'] and a linear chain of qubits $0 \rightarrow 1 \rightarrow 2$ with the coupling_map =[[0, 1], [1, 2]].

from qiskit import transpile
qc_transpiled = transpile(qc_example, basis_gates = ['cz', 'sx', 'rz'], coupling_map =[[0, 1], [1, 2]] , optimization_level=3)

Executing your code on real quantum hardware

Qiskit provides an abstraction layer that lets users run quantum circuits on hardware from any vendor that provides a compatible interface. The best way to use Qiskit is with a runtime environment that provides optimized implementations of sampler and estimator for a given hardware platform. This runtime may involve using pre- and post-processing, such as optimized transpiler passes with error suppression, error mitigation, and, eventually, error correction built in. A runtime implements qiskit.primitives.BaseSampler and qiskit.primitives.BaseEstimator interfaces. For example, some packages that provide implementations of a runtime primitive implementation are:

Qiskit also provides a lower-level abstract interface for describing quantum backends. This interface, located in qiskit.providers, defines an abstract BackendV2 class that providers can implement to represent their hardware or simulators to Qiskit. The backend class includes a common interface for executing circuits on the backends; however, in this interface each provider may perform different types of pre- and post-processing and return outcomes that are vendor-defined. Some examples of published provider packages that interface with real hardware are:

You can refer to the documentation of these packages for further instructions on how to get access and use these systems.

Contribution Guidelines

If you'd like to contribute to Qiskit, please take a look at our contribution guidelines. By participating, you are expected to uphold our code of conduct.

We use GitHub issues for tracking requests and bugs. Please join the Qiskit Slack community for discussion, comments, and questions. For questions related to running or using Qiskit, Stack Overflow has a qiskit. For questions on quantum computing with Qiskit, use the qiskit tag in the Quantum Computing Stack Exchange (please, read first the guidelines on how to ask in that forum).

Authors and Citation

Qiskit is the work of many people who contribute to the project at different levels. If you use Qiskit, please cite as per the included BibTeX file.

Changelog and Release Notes

The changelog for a particular release is dynamically generated and gets written to the release page on Github for each release. For example, you can find the page for the 0.46.0 release here:

https://github.com/Qiskit/qiskit/releases/tag/0.46.0

The changelog for the current release can be found in the releases tab: Releases The changelog provides a quick overview of notable changes for a given release.

Additionally, as part of each release, detailed release notes are written to document in detail what has changed as part of a release. This includes any documentation on potential breaking changes on upgrade and new features. See all release notes here.

Acknowledgements

We acknowledge partial support for Qiskit development from the DOE Office of Science National Quantum Information Science Research Centers, Co-design Center for Quantum Advantage (C2QA) under contract number DE-SC0012704.

License

Apache License 2.0

qiskit's People

Contributors

1ucian0 avatar atilag avatar awcross1 avatar chriseclectic avatar cryoris avatar delapuente avatar dependabot[bot] avatar diego-plan9 avatar elept avatar enavarro51 avatar eric-arellano avatar ewinston avatar ikkoham avatar ismaelfaro avatar jakelishman avatar jaygambetta avatar jesusprubio avatar kdk avatar lcapelluto avatar levbishop avatar maddy-tod avatar manoelmarques avatar mtreinish avatar nkanazawa1989 avatar nonhermitian avatar qiskit-bot avatar sooluthomas avatar t-imamichi avatar taalexander avatar woodsp-ibm avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

qiskit's Issues

"math domain error" in mapping

Current Behavior

The attached fuzz_reccztqq.txt triggers a ValueError: math domain error exception when executed with the mapping {0: [2], 1: [2], 2: [3], 3: []}:

from qiskit import QuantumProgram
qp = QuantumProgram()
qp.load_qasm_file("fuzz_reccztqq.txt", name='test')
qp.execute(["test"], backend="local_qasm_simulator", coupling_map={0: [2], 1: [2], 2: [3], 3: []})

Expected Behavior

It is my understanding that the program should execute just like as when there is no map restriction:

from qiskit import QuantumProgram
qp = QuantumProgram()
qp.load_qasm_file("fuzz_reccztqq.txt", name='test')
qp.execute(["test"], backend="local_qasm_simulator", coupling_map=None)

The attached example was generated by a fuzzer. It could be the current behavior is the expected. My apologies in that case...

Can't find eval_hamiltonian in optimization.py

There used to be a function eval_hamiltonian in qiskit.tools.apps.optimization.py that seems to have gone missing. Ditto for group_paulis.

I did a search for them and I can't find them anywhere is QISKit. Were they replaced?

Expected Behavior

I should be able to import the function such as
from qiskit.tools.apps.optimization import eval_hamiltonian

Current Behavior

ImportError: cannot import name 'eval_hamiltonian'

Possible Solution

Identify where those functions went.

Steps to Reproduce (for bugs)

from qiskit.tools.apps.optimization import eval_hamiltonian

Context

Trying to run the Quantum Chemistry tutorial

Your Environment

  • Environment name and version (e.g. Python 3.6): Python 3.6
  • Operating System and version: Ubuntu 16.04

Bug in mapping?

Measurement results differ in compiling with/without coupling_map.

Expected Behavior

With this QASM (coupling_map=None), expected measurement results are {'1001', '0001'}

OPENQASM 2.0;
include "qelib1.inc";
qreg q[4];
creg c[4];
// -X-.-----
// -Y-+-S-.-
// -Z-.-T-+-
// ---+-H---
x q[0];
y q[1];
z q[2];
cx q[0], q[1];
cx q[2], q[3];
s q[1];
t q[2];
h q[3];
cx q[1], q[2];
measure q[0] -> c[0];
measure q[1] -> c[1];
measure q[2] -> c[2];
measure q[3] -> c[3];

Current Behavior

{'0000', '1000'} are obtained with coupling_map = {0: [2], 1: [2], 2: [3], 3: []}

Steps to Reproduce (for bugs)

        qp = QuantumProgram()
        qp.load_qasm_file('qasm_above.qasm', name='test2')
        coupling_map = {0: [2], 1: [2], 2: [3], 3: []}
        result1 = qp.execute(["test2"], backend="local_qasm_simulator", coupling_map=coupling_map)
        print(result1.get_counts("test2"))
        result2 = qp.execute(["test2"], backend="local_qasm_simulator", coupling_map=None)
        print(result2.get_counts("test2"))

multiply Paulis not working

Expected Behavior

Multiply Paulis is supposed to be supported in pauli.py

Current Behavior

when testing it throws a TypeError.
TypeError: unsupported operand type(s) for %: 'list' and 'int'

Steps to Reproduce (for bugs)

from qiskit.tools.qi.pauli import Pauli
pauli_1 = Pauli([1,0,0],[0,0,0])
pauli_2 = Pauli([0,1,0],[0,0,0])
mult_pauli = pauli_1*pauli_2

Error when register name starts with "qreg" or "creg"

I found this bug :
when creating a quantum register with create_quantum_register or create_classical_register, if one gives a name starting by "qreg" or "creg" then subsequent execution of a program using this register raises an error.
Here is an example code to reproduce the error :

from qiskit import QuantumProgram
import Qconfig

qprogram = QuantumProgram()
qprogram.set_api(Qconfig.APItoken, Qconfig.config["url"])

qtoto = qprogram.create_quantum_register("qregbliblablu",5)
ctiti = qprogram.create_classical_register("ctutu",5)
qcircuit= qprogram.create_circuit("mycircuit",[qtoto],[ctiti])

qcircuit.h(qtoto[0])
qcircuit.measure(qtoto[0],ctiti[0])

qprogram.execute(["mycircuit"], "ibmqx_qasm_simulator", shots=1000, max_credits=5, wait=10, timeout=240)

load/save Results

We need to allow to store and load the Result like a part of the save your Quantum Program

Expected Behavior

Every time that you use the QuantumProgram.save() and QuantumProgram.load() we need to store and load the executions results (from the offline simulator and online simulators or real chips), as part of the our QP file.

Current Behavior

Currently only save and load the Program but not the results.

Your Environment

  • Version used: QISKIT 0.3
  • Environment name and version (e.g. Python 3.6.1):
  • Operating System and version: OSX&Windows&Linux

Make the linter happier!

Welcome contributor!

We are evolving the SDK at near speed of light! (almost), so, you know.. sometimes we forget about our Linter friend.
We want to fix this! and we think this is a good opportunity for newcomers to have first-soft-contact with the code and help us out.
Are you willing to help? Seriously!? ... Thank you!!
I'd recommend executing this to start with (brace yourselves!):

make lint

... yeah, we know... overwhelming :(
Of course, you don't have to fix them all, we would be extremely grateful if you take care of a bunch of them... or just one!

UPDATE
As there are many people who wants to contribute here, let's sync this way:
1st - Read in the comments which files are already taken.
2nd - Pick the files you want to fix and write a comment so everybody knows in which files you are working on.

Notes

  • If you want to take this bug, let us know and we will assign you to it.
  • You can open a PR to "master" branch with the word: "WIP" (Work In Progress) in front of the description, so we will know that you haven't finished and we can make parcial reviewings. We will eliminate the WIP prefix once the PR is ready to be merged.
  • Make sure all tests pass! :)

"make profile" fails because of a parsing error in test_qasm_python_simulator.py

Running make profile outputs:

======================================================================
ERROR: profile_nqubit_speed_constant_depth (test.python.test_qasm_python_simulator.LocalQasmSimulatorTest)
simulation time vs the number of qubits
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/jgomez/ibm/quantum/qiskit-sdk-py/test/python/test_qasm_python_simulator.py", line 342, in profile_nqubit_speed_constant_depth
    qp.run()
TypeError: run() missing 1 required positional argument: 'qobj'

======================================================================
ERROR: profile_nqubit_speed_grow_depth (test.python.test_qasm_python_simulator.LocalQasmSimulatorTest)
simulation time vs the number of qubits
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/jgomez/ibm/quantum/qiskit-sdk-py/test/python/test_qasm_python_simulator.py", line 267, in profile_nqubit_speed_grow_depth
    qp.run()
TypeError: run() missing 1 required positional argument: 'qobj'

----------------------------------------------------------------------

Steps to Reproduce (for bugs)

  1. run: make profile

Your Environment

  • Version used: master (r0.3)
  • Environment name and version (e.g. Python 3.6.1): Python3.5/3.6
  • Operating System and version: Linux (but Mac and Windows are affected as well)

Make random context explicity local for every circuit run.

Our concurrency model saves us from having two circuits running at the same time, interfere each other when setting up the random context:

if circuit['config']['seed'] is None:
    random.seed(random.getrandbits(32))
else:
    random.seed(circuit['config']['seed'])

... because we are using ProcessPoolExecutor, hence we are using processes for running every circuit in parallel. But it's a poor design to trust in runtime implementation for this to work, so we want to fix this situation.

Newcomers
As this is not a critical bug, and it has a very simple solution, I think is a good opportunity for people who wants to get their head around the contributing workflow, to take this issue and fix it.

Expected Behavior

Circuit random context should not change if another circuit is running at the same time.

Possible Solution

Don't want to give too many clues for people who want to give a try, but this could be a possible solution:

local_random = random.Random()

... we would be more than glad if another elegant and simple solution comes up :)

The point here is to make sure that random numbers generation on every circuit do not interfere each other when multiple circuits are running in parallel.

Your Environment

  • Version used: qiskit 0.4 (master) ... qiskit 0.3.x (stable) is not affected.
  • Environment name and version (e.g. Python 3.6.1): Python 3.5 and 3.6

Only one entry point for external package dependencies

We have actually two places where we define our external package dependencies:

requirements.txt
setup.py

The requirements.txt is used by the make env target to install the dependencies into the conda virutal environment, and setup.py is used to create a distributable package meant to be used via pip.

Ok, we want to fix this situation. There should be only one entry point, so if a new dependency is removed/added we don't have to edit both files.

Newcomers
We want to keep requirements.txt file as the only entry point, so something must be changed on setup.py to use this file. Would you dare to change it? How?... if you are confident about a possible solution, let's jump right into a PR and I'll review it. Do you have many possible solutions in mind? ... Ok, let's discuss in this thread and see what's the best fit!.
Extra point! => if you make it work on Linux, Mac and Windows :)

Your Environment

  • Version used: 0.4 (development)
  • Environment name and version (e.g. Python 3.6.1): Python 3.5 & 3.6
  • Operating System and version: Linux, Mac, Windows.

Better offline support.

We should allow the usage of the SDK in offline scenarios. This will restrict the user to deal with local simulators only. If the user tries to access some online feature, we will throw a controlled exception.

Current Behavior

If there's no Internet connection, the QuantumProgram class will throw and exit.

Steps to Reproduce (for bugs)

  1. Switch off networking
  2. Run your program (which highly probable uses QuantumProgram class)
  3. Program stops because of connection related exceptions.

Your Environment

  • Version used: 0.3.4
  • Environment name and version (e.g. Python 3.6.1): All supported versions
  • Operating System and version: All supported versions

Possible implementation for cont_gates according to Barenco

controlledU.tar.gz
After some feature list discussion on the community forum about implementing a controlled gate module for any two-dimensional gate according to Barenco, I have finished the first test python files. I use the projectQ package and did a run with a controlled gate test.py, and it worked for the X gate.
Next step for me is to produce an output file in IBM QASM2 format.

request backend by type

Implement function to request backend by type.

Expected Behavior

When a backend name changes, as happens for the real devices, this can break code which specifically requests the named backend. If instead there was a method to request a backend by specifying restraints this could avoid breaking code. This might mean requesting a device with a minimum number of qubits but could also be expanded to include other restraints e.g. quantum volume, simulation type, etc.

Current Behavior

Possible Solution

Currently all the backends return "configuration" dictionary. Perhaps this could be used for the filter.

Steps to Reproduce (for bugs)

Context

Your Environment

  • Version used:
  • Environment name and version (e.g. Python 3.6.1):
  • Operating System and version:

Typo in tutorial could lead to installation problems

In tutorial4developer.ipynb the lines

git clone https://github.ibm.com/IBMQuantum/qiskit-sdk-py-dev
cd qiskit-sdk-py-dev

require a login to execute. I believe they should instead be

git clone https://github.com/IBM/qiskit-sdk-py
cd qiskit-sdk-py

Jobs timeouts are wrongly managed.

Timeouts are not working as expected.

Expected Behavior

When you set a timeout in QuantumProgram.execute(timeout=<value>) or .run(timeout=<value>) we want this value to be the actual timeout (in secs).

Current Behavior

Values passed are not being properly set, so the default 120 secs timeout is always being used.

Steps to Reproduce (for bugs)

  1. Call QuantumProgram.execute(timeout=0.01) surrounded by try: ... except QSIKitError:
  2. The method call should timeout and entering the except block, but it's not.

Your Environment

  • Version used: 0.4.x (0.3 is not affected)
  • Environment name and version (e.g. Python 3.6.1): 3.5 & 3.6
  • Operating System and version: Linux, Mac and Windows.

Better logging

Welcome contributors!

So far, we've been using a flag called "silent" (you can search for it into the sources), that if set to true, will cause some information to be printed out to the standard output.
We want to change it!
So if you are willing to contribute to this amazing project (I know you are!), I'd suggest you to start with something simple like this issue.
We want to change all the "silent" flag behavior with a more robust and standard logging solution based in the python logging facility. So basically these are the tasks we need to address:

  • Incorporate standard python logging module

  • Create a logging config file with decent default settings:

    • INFO level
    • Console output
    • Set "disable_exisiting_loggers: false"
    • format: "%(asctime)s : %(name)s : %(levelname)s : %(message)s"
  • Loggers should be at module level and use the __name__ attribute:

    • logger = logging.getLogger(__name__)
  • Remove "silent" flag everywhere and replace the print() statements with logger.debug() (we don't want to show messages by default)

Suggestions are welcome! :)

Notes

  • If you want to take this bug, let us know and we will assign you to it.
  • You can open a PR to "master" branch with the word: "WIP" (Work In Progress) in front of the description, so we will know that you haven't finished and we can make parcial reviewings. We will eliminate the WIP prefix once the PR is ready to be merged.
  • Make sure all tests pass! :)

Current Behavior

We are using the "silent" variable to print out information via standard output in just some modules. We want to remove them all and use a common logging system.

mapper does not remove u1(2 * pi)

As @decodoku mentions in #157, mapper leaves two consecutive H gates as u1(2 * pi).
I think this is closely related to #158

Expected Behavior

Identify gates equivalent with id e.g. u1(2 * pi), and remove it from the circuit

Possible Solution

Improve mapper.optimize_1q_gates?

Steps to Reproduce (for bugs)

See #157
Run

from qiskit import QuantumProgram
import Qconfig

qp = QuantumProgram()
qp.set_api(Qconfig.APItoken, Qconfig.config["url"])

qr = qp.create_quantum_register('qr',2)
cr = qp.create_classical_register('cr',2)
qc = qp.create_circuit('Bell',[qr],[cr])
qc.h(qr[0])
qc.cx(qr[1], qr[0])
qc.cx(qr[1], qr[0])
qc.cx(qr[1], qr[0])
qc.measure(qr[0], cr[0])
qc.measure(qr[1], cr[1])

backend = 'ibmqx4'
cmap = qp.get_backend_configuration(backend)['coupling_map']
qobj = qp.compile(["Bell"], backend=backend, coupling_map=cmap)
print(qp.get_compiled_qasm(qobj,"Bell"))

Output will be:

OPENQASM 2.0;
include "qelib1.inc";
qreg q[2];
creg cr[2];
u1(6.283185307179586) q[1];
u2(0.0,3.141592653589793) q[0];
cx q[1],q[0];
u1(6.283185307179586) q[0];
u1(6.283185307179586) q[1];
cx q[1],q[0];
u1(6.283185307179586) q[0];
u1(6.283185307179586) q[1];
cx q[1],q[0];
u2(0.0,3.141592653589793) q[0];
measure q[0] -> cr[1];
u2(0.0,3.141592653589793) q[1];
measure q[1] -> cr[0];

Unexpected result qasm simulator with coupling map (stable)

I believe that I found a bug at stable (see 2 below). I have two enhancement suggestions (see 1 and 3).

Expected Behavior

Expected result
'{'1000': 50}'

Current Behavior

Result qasm simulator without coupling map and initial layout
{'1000': 50}

Result qasm simulator with coupling map and initial layout
{'1000': 25, '0000': 25}

Result ibmqx5
{"error":{"status":400,"message":"Error parsing QASM. Error parsing qasm number 0. Gates after a measure are blocked","code":"QASM_NOT_VALID"}}

Possible Solution

Steps to Reproduce (for bugs)

Attached file

Context

  1. In [arXiv:quant-ph/0012100] a probabilistic quantum memory is defined. Given a memory $|m\rangle = \frac{1}{\sqrt{k}} |p_k\rangle$ and an input $|i\rangle$ the memory outputs 0 with probability $p(0) = \frac{1}{k} cos^2(\frac{\pi}{2n} d_H(i,p_k))$ and 1 with probability $1 โ€“ p0$.

After see #152, I am working on the implementation of the retrieval algorithm of [arXiv:quant-ph/0012100].

Is this a viable enhancement?

  1. Different behavior when I compile with or without coupling_map. Error when I run with backend ibmqx5

I got strange results when I finished the implementation (attached file). With memory |000\rangle and input |111\rangle I obtained different results using qasm simulator without coupling map and qasm simulator with coupling map.

A running example.
Expected result
'{'1000': 50}'

Result qasm simulator without coupling map and initial layout
{'1000': 50}

Result qasm simulator with coupling map and initial layout
{'1000': 25, '0000': 25}

Result ibmqx5
{"error":{"status":400,"message":"Error parsing QASM. Error parsing qasm number 0. Gates after a measure are blocked","code":"QASM_NOT_VALID"}}

  1. Initial layout
    I compile without an initial_layout. After a compilation, I get the final layout (I didn't verify the generated layout) and use as initial layout in the next shots. In some executions the mapper failed. I believe that the initial layout is not being verified. Could the mapper verify the initial layout?

some logs

/Library/Frameworks/Python.framework/Versions/3.6/bin/python3.6 /Users/adeniltonsilva/Documents/GitHub/qiskit-sdk-py/probabilistic_memory_ibmqx.py
Expected result
'{'1000': 50}'
Result qasm simulator without coupling map and initial layout
{'1000': 50}
pre-mapping properties: {'size': 51, 'depth': 23, 'width': 7, 'bits': 4, 'factors': 1, 'operations': {'u2': 2, 'u1': 12, 'u3': 21, 'cx': 12, 'measure': 4}}
initial layout: {('p', 0): ('q', 1), ('p', 1): ('q', 0), ('p', 2): ('q', 2), ('m', 0): ('q', 3), ('m', 1): ('q', 4), ('m', 2): ('q', 14), ('c', 0): ('q', 5)}
final layout: {('p', 0): ('q', 1), ('p', 1): ('q', 0), ('p', 2): ('q', 2), ('m', 0): ('q', 3), ('m', 1): ('q', 4), ('m', 2): ('q', 14), ('c', 0): ('q', 5)}
post-mapping properties: {'size': 155, 'depth': 71, 'width': 15, 'bits': 4, 'factors': 9, 'operations': {'u1': 9, 'cx': 60, 'u2': 78, 'u3': 4, 'measure': 4}}
running on backend: local_qasm_simulator
Result qasm simulator with coupling map and initial layout
{'1000': 25, '0000': 25}
pre-mapping properties: {'size': 51, 'depth': 23, 'width': 7, 'bits': 4, 'factors': 1, 'operations': {'u2': 2, 'u1': 12, 'u3': 21, 'cx': 12, 'measure': 4}}
initial layout: {('p', 0): ('q', 1), ('p', 1): ('q', 0), ('p', 2): ('q', 2), ('m', 0): ('q', 3), ('m', 1): ('q', 4), ('m', 2): ('q', 14), ('c', 0): ('q', 5)}
Traceback (most recent call last):
File "/Users/adeniltonsilva/Documents/GitHub/qiskit-sdk-py/probabilistic_memory_ibmqx.py", line 129, in
timeout=240, silent=False)
File "/Users/adeniltonsilva/Documents/GitHub/qiskit-sdk-py/qiskit/_quantumprogram.py", line 1184, in execute
max_credits=max_credits, seed=seed)
File "/Users/adeniltonsilva/Documents/GitHub/qiskit-sdk-py/qiskit/_quantumprogram.py", line 854, in compile
dag_circuit, coupling, initial_layout, trials=20, verbose=False)
File "/Users/adeniltonsilva/Documents/GitHub/qiskit-sdk-py/qiskit/mapper/_mapping.py", line 425, in swap_mapper
aliases=layout))
qiskit.mapper._mappererror.MapperError: 'swap_mapper failed: layer 17, sublayer 1, "cx q[0],q[14];\n"'

Process finished with exit code 1

/Library/Frameworks/Python.framework/Versions/3.6/bin/python3.6 /Users/adeniltonsilva/Documents/GitHub/qiskit-sdk-py/probabilistic_memory_ibmqx.py
Expected result
'{'1000': 50}'
Result qasm simulator without coupling map and initial layout
{'1000': 50}
pre-mapping properties: {'size': 51, 'depth': 23, 'width': 7, 'bits': 4, 'factors': 1, 'operations': {'u2': 2, 'u1': 12, 'u3': 21, 'cx': 12, 'measure': 4}}
initial layout: {('p', 0): ('q', 1), ('p', 1): ('q', 0), ('p', 2): ('q', 2), ('m', 0): ('q', 3), ('m', 1): ('q', 4), ('m', 2): ('q', 14), ('c', 0): ('q', 5)}
Traceback (most recent call last):
File "/Users/adeniltonsilva/Documents/GitHub/qiskit-sdk-py/probabilistic_memory_ibmqx.py", line 121, in
timeout=240, silent=False)
File "/Users/adeniltonsilva/Documents/GitHub/qiskit-sdk-py/qiskit/_quantumprogram.py", line 1184, in execute
max_credits=max_credits, seed=seed)
File "/Users/adeniltonsilva/Documents/GitHub/qiskit-sdk-py/qiskit/_quantumprogram.py", line 854, in compile
dag_circuit, coupling, initial_layout, trials=20, verbose=False)
File "/Users/adeniltonsilva/Documents/GitHub/qiskit-sdk-py/qiskit/mapper/_mapping.py", line 425, in swap_mapper
aliases=layout))
qiskit.mapper._mappererror.MapperError: 'swap_mapper failed: layer 1, sublayer 3, "cx q[0],q[14];\n"'

Process finished with exit code 1

Result ibmqx5
/Library/Frameworks/Python.framework/Versions/3.6/bin/python3.6 /Users/adeniltonsilva/Documents/GitHub/qiskit-sdk-py/probabilistic_memory_ibmqx.py
pre-mapping properties: {'size': 51, 'depth': 23, 'width': 9, 'bits': 4, 'factors': 3, 'operations': {'u2': 2, 'u1': 12, 'u3': 21, 'cx': 12, 'measure': 4}}
initial layout: {('p', 0): ('q', 1), ('p', 1): ('q', 0), ('p', 2): ('q', 2), ('m', 0): ('q', 3), ('m', 1): ('q', 4), ('m', 2): ('q', 14), ('u', 0): ('q', 5), ('u', 1): ('q', 6), ('c', 0): ('q', 7)}
final layout: {('p', 0): ('q', 1), ('p', 1): ('q', 0), ('p', 2): ('q', 2), ('m', 0): ('q', 3), ('m', 1): ('q', 4), ('m', 2): ('q', 14), ('u', 0): ('q', 5), ('u', 1): ('q', 6), ('c', 0): ('q', 7)}
post-mapping properties: {'size': 205, 'depth': 90, 'width': 15, 'bits': 4, 'factors': 7, 'operations': {'u1': 12, 'cx': 84, 'u2': 105, 'measure': 4}}
running on backend: ibmqx5
WARNING:IBMQuantumExperience.IBMQuantumExperience:Got a 400 code response to https://quantumexperience.ng.bluemix.net/api/Jobs?access_token=HCBtEwhZZBdQNHpxlHlO9yCSwrxwU0KHAdlcVQzwiYfnKKmmA0dwd7m4SiqAvVaT: {"error":{"status":400,"message":"Error parsing QASM. Error parsing qasm number 0. Gates after a measure are blocked","code":"QASM_NOT_VALID"}}
WARNING:IBMQuantumExperience.IBMQuantumExperience:Got a 400 code response to https://quantumexperience.ng.bluemix.net/api/Jobs?access_token=HCBtEwhZZBdQNHpxlHlO9yCSwrxwU0KHAdlcVQzwiYfnKKmmA0dwd7m4SiqAvVaT: {"error":{"status":400,"message":"Error parsing QASM. Error parsing qasm number 0. Gates after a measure are blocked","code":"QASM_NOT_VALID"}}
WARNING:IBMQuantumExperience.IBMQuantumExperience:Got a 400 code response to https://quantumexperience.ng.bluemix.net/api/Jobs?access_token=HCBtEwhZZBdQNHpxlHlO9yCSwrxwU0KHAdlcVQzwiYfnKKmmA0dwd7m4SiqAvVaT: {"error":{"status":400,"message":"Error parsing QASM. Error parsing qasm number 0. Gates after a measure are blocked","code":"QASM_NOT_VALID"}}
WARNING:IBMQuantumExperience.IBMQuantumExperience:Got a 400 code response to https://quantumexperience.ng.bluemix.net/api/Jobs?access_token=HCBtEwhZZBdQNHpxlHlO9yCSwrxwU0KHAdlcVQzwiYfnKKmmA0dwd7m4SiqAvVaT: {"error":{"status":400,"message":"Error parsing QASM. Error parsing qasm number 0. Gates after a measure are blocked","code":"QASM_NOT_VALID"}}
WARNING:IBMQuantumExperience.IBMQuantumExperience:Got a 400 code response to https://quantumexperience.ng.bluemix.net/api/Jobs?access_token=HCBtEwhZZBdQNHpxlHlO9yCSwrxwU0KHAdlcVQzwiYfnKKmmA0dwd7m4SiqAvVaT: {"error":{"status":400,"message":"Error parsing QASM. Error parsing qasm number 0. Gates after a measure are blocked","code":"QASM_NOT_VALID"}}
Traceback (most recent call last):
File "/Users/adeniltonsilva/Documents/GitHub/qiskit-sdk-py/probabilistic_memory_ibmqx.py", line 206, in
timeout=240, silent=False)
File "/Users/adeniltonsilva/Documents/GitHub/qiskit-sdk-py/qiskit/_quantumprogram.py", line 1185, in execute
result = self.run(qobj, wait=wait, timeout=timeout, silent=silent)
File "/Users/adeniltonsilva/Documents/GitHub/qiskit-sdk-py/qiskit/_quantumprogram.py", line 1030, in run
raise ResultError(output['error'])
qiskit._quantumprogram.ResultError: 'Error parsing QASM. Error parsing qasm number 0. Gates after a measure are blocked'

Process finished with exit code 1

Your Environment

  • Version used: stable
  • Environment name and version (e.g. Python 3.6.1):
  • Operating System and version: macOs 10.13.1

tools module import failure

The second box in the tutorial notebook "quantum_state_tomography_bell_states" doesn't run successfully.

Expected Behavior

I expect that box of code to silently import some modules.

Current Behavior


ModuleNotFoundError Traceback (most recent call last)
in ()
1 # import tomography libary
----> 2 import tools.qcvv.tomography as tomo
3
4 # useful additional packages
5 from tools.visualization import plot_state, plot_histogram

ModuleNotFoundError: No module named 'tools'

Possible Solution

Change that line to this and it works:

from qiskit.tools.qcvv import tomography as tomo

Steps to Reproduce (for bugs)

N/A

Context

N/A

Your Environment

  • Version used: qiskit 0.3.5
  • Environment name and version (e.g. Python 3.6.1): Python 3.6.2-0 Anaconda3
  • Operating System and version: Win 10 64bit

Support for more virtual environments

Another topic for discussion thanks to Andreas Fuhrer contribution.
Currently, we do support Anaconda/Conda virtual environment for various platforms (Linux, Mac and Windows). We encourage the use of Anaconda because in some platforms, it comes with a preinstalled version of some our dependencies, more notably numpy, especially on Windows.
I was just wondering if there could be users who want/need to use other virtual environments like virutalenv or virtualenvwrapper, we have to make sure that those new virtual envs work in all supported platforms (thinking mostly about Windows and numpy).
This support could be included in the Makefile's "env" target.

Temporary file /tmp/parsetab.py

I think when parsing qiskit writes a temporary file /tmp/parsetab.py . This poses a problem if two users use qiskit on the same machine. The temporary file should be unique to each user.

Expected Behavior

Temporary file should be unique for each user.

Current Behavior

Temporary file is not unique for each user which leads to write conflicts.

Possible Solution

Add user name to the parsetab file.

Steps to Reproduce (for bugs)

ls -l /tmp/parsetab.py

Makefile

Executing make env-dev after make env does not work, because the conda environment QISKITenv exists and cannot be recreated.

Running on down or non-existent backend

Currently, when running on a backend which is down the job submits but times out; furthermore, if the backend does not exist at all, the program throws an uncaught error and stops. It would be nice to have the API relay information about nodes which are down, and to have the SDK use that to detect if a job is submitted to a down or non-existent backend. This could easily be addressed by adding a check into qiskit/_jobprocessor.py here:

    def submit(self, silent=True):
       ...
        for q_job in self.q_jobs:
            if q_job.backend in self._local_backends:
                future = executor.submit(run_local_simulator,
                                         q_job.qobj)
            elif self.online and q_job.backend in self._online_backends:
                future = executor.submit(run_remote_backend,
                                         q_job.qobj,
                                         self._api)

            #Check for down/non-existent backend?

            future.silent = silent

Particularly given that, at the moment, credits do not regenerate after a timed out job, it would be great especially to know if a node is down. I found this error when trying to run on the new ibmqx5 backend, which I do not believe is returned by the API as available.

Here's the full error text

Traceback (most recent call last):
File "asdf.py", line 15, in
result = Q_program.execute(["superposition"], backend='ibmqx5', shots=1024)
File "/Users/sabreitweiser/qiskit-sdk-py/qiskit/_quantumprogram.py", line 1144, in execute
result = self.run(qobj, wait=wait, timeout=timeout, silent=silent)
File "/Users/sabreitweiser/qiskit-sdk-py/qiskit/_quantumprogram.py", line 965, in run
self._run_internal([qobj], wait, timeout, silent)
File "/Users/sabreitweiser/qiskit-sdk-py/qiskit/_quantumprogram.py", line 1055, in _run_internal
jp.submit()
File "/Users/sabreitweiser/qiskit-sdk-py/qiskit/_jobprocessor.py", line 359, in submit
future.silent = silent
UnboundLocalError: local variable 'future' referenced before assignment

And the minimal program to reproduce (which is just a slightly modified version of the README example)

import sys
sys.path.append('/Users/sabreitweiser/qiskit-sdk-py/')
from qiskit import QuantumProgram
import Qconfig

Q_program = QuantumProgram()
QX_TOKEN = Qconfig.APItoken
QX_URL = "https://quantumexperience.ng.bluemix.net/api"
Q_program.set_api(QX_TOKEN, QX_URL)
qr = Q_program.create_quantum_register("qr", 2)
cr = Q_program.create_classical_register("cr", 2)
qc = Q_program.create_circuit("superposition", [qr], [cr])
qc.h(qr[0])
qc.measure(qr, cr)
result = Q_program.execute(["superposition"], backend='ibmqx5', shots=1024)
print(result)
print(result.get_data("superposition"))

Qconfig.py.default hard to read on Windows

it has a CRLF issuse so that it's all one long line if you view it on Windows in Notepad.

Also, your token needs to have Quotes around it after you paste it in. Strangely, I don't recall running into that problem when I set it up earlier on Linux

KeyError: 'result' on execution

I received the following error

Traceback (most recent call last):
 ..........
  File "_quantumprogram.py", line 634, in execute
    output = self.run(wait, timeout)
  File "_quantumprogram.py", line 539, in run
    self.__quantum_program["circuits"][name]["execution"][backend]["result"] = job_result["qasms"][index]["result"]
KeyError: 'result'

Process finished with exit code 1

After having a look at line 539 and at the job_result object returned by the IBMQuantumExperience I noticed that there is no key called "result". The returned info from the execution is in the field "data"(?) I used the online device "ibmqx_qasm_simulator".

The following edits helped. Are these edits ok?

In _quantumprogram.py method get_counts()
return self.__quantum_program["circuits"][name]['execution'][device]['data']['counts']

In _quantumprogram.py method run() @ line 539
self.__quantum_program["circuits"][name]["execution"][backend]["data"] = job_result["qasms"][index]["data"]

Enhance contributing guide

The contributing guide should include examples and a better description of the workflow expected from contributions. Our branch model, release cycle, etc.

ImportError: cannot import name 'basicplotter'

In the tutorial4developer, when I run the following cell:

import sys
sys.path.append("")
from qiskit import QuantumProgram
import Qconfig

I have an "ImportError: cannot import name 'basicplotter'" with the following detail:

ImportError Traceback (most recent call last)
in ()
2 sys.path.append("") # solve the relative dependencies if you clone QISKit from the Git repo and use like a global.
3 print (sys.path)
----> 4 from qiskit import QuantumProgram
5 import Qconfig

~/py/qiskit-sdk-py/qiskit/init.py in ()
8 from ._qiskitexception import QISKitException
9 import qiskit.extensions.standard
---> 10 from ._quantumprogram import QuantumProgram

~/py/qiskit-sdk-py/qiskit/_quantumprogram.py in ()
28 # use the external IBMQuantumExperience Library
29 from IBMQuantumExperience.IBMQuantumExperience import IBMQuantumExperience
---> 30 from . import basicplotter
31
32 # Stable Modules

ImportError: cannot import name 'basicplotter'

Cannot build qiskit: package directory 'qiskit/simulators' does not exist

Hello,

I'm pretty new to qiskit and I may have misunderstood the issue, but I cannot build the package due to a missing package folder: simulators

$ python setup.py build
running build
running build_py
error: package directory 'qiskit/simulators' does not exist

I suppose that's due to the new backends interface implementation, so maybe setup.py should be updated to reflect the change, here: https://github.com/QISKit/qiskit-sdk-py/blob/master/setup.py#L12

  • Version used: 0.4.0
  • Environment name and version: Python 3.6.2
  • Operating System and version: Linux 4.10.0-37-generic

Better support for Windows

Nowadays, the SDK is entirely based on Python so multi-platform might be supported as default, Windows included.

Expected Behavior

We should be able to run and pass all tests on Windows, as well as the Jupyter notebook tutorials.

Current Behavior

Right now, there's no way to run the Makefile targets without installing a Cygwin-like software.

Possible Solution

We are going to craft a Make.bat for supporting all common targets:

Make.bat run
Make.bat test
Make.bat profile
Make.bat doc
Make.bat clean

Error in evaluating Pauli-list style Hamiltonian

tools.optimization.eval_hamiltonian() fails by error if hamiltonian is given as pauli list.

Possible Solution

I found an obvious invalid source format, so I'll fix it.

Steps to Reproduce (for bugs)

  1. Open qiskit-tutorial/4_application/quantum_chemistry.ipynb (latest stable branch) with qiskit-sdk-py (latest stable branch)
  2. Just before the first definition of cost_function(), insert H = pauli_list
  3. Run the notebook
    -> AttributeError: 'dict' object has no attribute 'conjugate' at line 344

Context

Trying to understand tutorial more by running it with slightly modified parameters

Bug in cu3 implementation

cu3(pi, 0, pi) gate should work as controlled X gate, but it is not.

Expected Behavior

cx: (1, 0) ---> (0, 1)
cu3(pi, 0, pi) : (1, 0) ---> (0, 1)

Current Behavior

cx: (1, 0) ---> (0, 1)
cu3(pi, 0, pi) : (1, 0) ---> (0, -i)

Steps to Reproduce (for bugs)

import numpy as np

sys.path.append("../qiskit-sdk-py/")

from qiskit import QuantumProgram
import Qconfig

np.set_printoptions(precision=2)

Q_program = QuantumProgram()
n = 2
q = Q_program.create_quantum_register('q', n)
c = Q_program.create_classical_register('c', n)
  
state = Q_program.create_circuit('bug', [q], [c])

state.x(q[0])
state.cx(q[0], q[1])

state.measure(q[1], c[1])

backend = 'local_qasm_simulator'
result = Q_program.execute(['bug'], backend=backend, shots=1, silent = True)
print("Controlled X gate:")
print(result.get_data('bug')['quantum_state'])

print("")


Q_program = QuantumProgram()
n = 2
q = Q_program.create_quantum_register('q', n)
c = Q_program.create_classical_register('c', n)
  
state = Q_program.create_circuit('bug', [q], [c])

state.x(q[0])
state.cu3(np.pi, 0.0, np.pi, q[0], q[1])

state.measure(q[1], c[1])

backend = 'local_qasm_simulator'
result = Q_program.execute(['bug'], backend=backend, shots=1, silent = True)
print("CU3(pi, 0, pi) gate:")
print(result.get_data('bug')['quantum_state'])

Above code prints out

Controlled X gate:
[ 0.+0.j  0.+0.j  0.+0.j  1.+0.j]

CU3(pi, 0, pi) gate:
[  0.00e+00+0.j   0.00e+00+0.j   0.00e+00+0.j   6.12e-17-1.j]

Your Environment

  • Version used: 0.3.5
  • Environment name and version (e.g. Python 3.6.1): Python 3.6.2
  • Operating System and version: OSX

parsetab.py still used?

A few parts of the code mention parsetab.py, which seems to be auto generated.

I ran into an issue where I installed qiskit using pip3 on an admin account and then switched to a non-admin account for using the library. When running QuantumProgram.execute I get the following warning,

WARNING: Couldn't create 'parsetab'. [Errno 13] Permission denied: '/usr/local/lib/python3.6/site-packages/qiskit/qasm/parsetab.py'
WARNING: Couldn't create 'parsetab'. [Errno 13] Permission denied: '/usr/local/lib/python3.6/site-packages/qiskit/qasm/parsetab.py'

logging system is needed?

There is room for improvement in the way qiskit prints debugging info.
In the current situation some API calls have a silent argument (eg. QuantumProgram.compile ) and some other calls have a verbose argument (eg. _mapping.swap_mapper), with opposite meaning.

Debugging is already painful enough :) A better logging system would also make easier to get debug infor for bug reports. Something like logging is probably the way to go.

Evaluate linter alternatives to pylint.

Following up conversation from PR #147 I would love to have a little discussion about what other linter alternatives we could integrate within the SDK.
I think there's an agreement to not integrating with multiple linter tools, so lets choose one.
We are using pylint from the beginning and I guess that the main reason is because it's considered a standard de facto, but we are having a bad time going full free of warnings and there's a lot of false positives, which I guess is something we can afford... but, it's kind of annoying.
My question for the real experts (@diego-plan9 @cclauss), is there anything we can do with flake8 that we can't do (or it's too cumbersome) with pylint?

Behavior of the instruction "measure q[i] -> q[j];"

The QASM instruction "measure q[k1] -> q[k2];" with k1 and k2 different integers is not done properly on the real device (when called via run_job).
It behaves as if it were "measure q[k1] -> q[k1];" whatever k2 is.

Classical bit string in strange format for real device.

I have a three bit classical register and receive a 5 bit string as output. This always seems to include two bit that are always 0, but they aren't always in the same place. I cannot determine the logic behind it.

I think it related to, but not exactly the same as, this issue
#2

More info can be found in my post to the QX community
https://quantumexperience.ng.bluemix.net/qstage/#/community/question?questionId=3fde5ace6866eb41eba24fae2ce4dce3

Link to QISKit tutorials in some way.

After reviewing a contribution from a colleague (thanks Andreas!) I saw something that will love to discuss here - QISKit Tutorials are strongly related to the SDK, so I was thinking that maybe we could provide a way to include or link QISKit tutorials repository into the SDK. I guess that this could make things easier for someone who wants to work in the tutorials using QISKit development (master) branch . What do you think team?

I'd propose any of these approaches:

  • As a submodule linked to a "tutorials" directory onto root dir.
  • Creating a Makefile target that will clone the repository onto root dir.

Calibration data

In older versions of the API, the returned result of a past experiment contained information about the device calibration at the moment that the experiment was performed. This seems to be missing from this version. The functions to get data about device calibration seem to work only with the most recent calibration data.
It is useful to have a way to check the device calibration at some specific time in the past, especially at the time when a particular experiment was run.
Why is that feature missing (or at least not as easily accessible as in previous versions)?

Type error in result.get_counts() and get_data()

I've run a couple of circuits on the 'ibmqx5' backend but realised that the optimisation of the circuit is probably making it give out the wrong amplitudes. I've attempted to fix this by adding a few barriers and ran it again but (3 times in a row) an error message came up and I narrowed it down to being solely due to the get_counts() method. Here's the error message:

Traceback (most recent call last):
File "mbqc-simulation.py", line 232, in
plot_histogram(result.get_counts('MBQC'))
File "/Users/TheProtonCat/anaconda/lib/python3.5/site-packages/qiskit/_quantumprogram.py", line 1300, in get_counts
return self.get_data(name)['counts']
File "/Users/TheProtonCat/anaconda/lib/python3.5/site-packages/qiskit/_quantumprogram.py", line 1282, in get_data
return self.__result['result'][index]["data"]
TypeError: string indices must be integers

Since the method worked fine before I wonder if it might be the barriers that are inducing the error. I need to run this simulation for a project so any quick fix would be very much appreciated! (note that the method fails when I use it in different ways, like extracting my own values, not just when trying to plot the histogram).

Note: the get_data() method seems to fail for the same reason:

Traceback (most recent call last):
File "mbqc-simulation.py", line 194, in
counts = result.get_data('MBQC')
File "/Users/TheProtonCat/anaconda/lib/python3.5/site-packages/qiskit/_quantumprogram.py", line 1282, in get_data
return self.__result['result'][index]["data"]
TypeError: string indices must be integers

Convex optimisation with SDP

I have been informed (by Chris Wood) that my use of SDP in solving the convex optimisation problems that crop up in tomography may be a valuable contribution to the IBM SDK. As things currently stand the relevant section of my codebase is loosely structured as the following.

  • Input circuit to perform tomography on and which subsystems to reconstruct.
  • Generate relevant permutations of preparation states and measurement permutations and add to
    circuit.
  • Add permuted circuits to locally kept HDF5 file (the 'archive' - stores all my experiments and related
    analysis).
  • Upload circuits as batch jobs and store execution IDs in archive for later retrieval.
  • Retrieve completed circuits and perform state tomography using measurement statistics via the
    Matlab CVX optimisation library and the python/Matlab bridge
  • Perform process tomography with CVX and store the process matrix in archive.
  • Compute both the Kraus operators and the Choi matrix for the computed CP map. Store in archive.

Does any of that functionality sound useful?

_quantumprogram.py syntax error in Python 3.4 due to dictionary merging

_quantumprogram.py generates a syntax error with Python 3.4 due to dictionary merging that is not supported in python 3.4. See this topic:
https://stackoverflow.com/questions/38987/how-to-merge-two-dictionaries-in-a-single-expression

Here is the error message:

File "../../qiskit-sdk-py/qiskit/_quantumprogram.py", line 1002
"config": {**job["config"], **qobj["config"]}})
^
SyntaxError: invalid syntax

From dtmcclure:
Based on the stackoverflow discussion referenced above, it seems like the for loop at that point in _quantumprogram should be replaced with the version below in order to make this code work for any version of Python 3.

     for job in qobj["circuits"]:
        fullconfig = job["config"].copy()
        fullconfig.update(qobj["config"])
        jobs.append({"compiled_circuit": job["compiled_circuit"],
                     "config": fullconfig})

the AST nodes are not always nodes

Expected Behavior

When parsing QASM, an AST is obtained where the nodes and their children are Node objects:

import qiskit.qasm as Qasm

def f(node):
   for child in node.children:
       f(child)

qasm = Qasm.Qasm(QASM_FILE_PATH)
f(qasm.parse())

It would be expected to call a recursive function f over that tree, expecting nodes of the Node type.

Current Behavior

When parsing a binary operation qiskit.qasm._node._binaryop.BinaryOp, (such as 3.141592653589793/2 from qelib1.inc) the node.children has three elements:

0 = {str} '/'
1 = {Real} <qiskit.qasm._node._real.Real>
2 = {Int} <qiskit.qasm._node._intnode.Int>

The item 0 should from a Node subclass, not a str.

Cancellation of CNOTs required backend info

Compilation does not cancel two sequential and identical CNOTs (i.e. using the identity cx^2 = 1) unless coupling map information is supplied as a kwarg. Since such cancellation has no dependence on device, this seems like an oversight.

A related issue as that the coupling map kwarg arguably should default to the coupling map of the backend when this is supplied as a kwarg.

Until this is fixed, there is a workaround of course: just give the coupling map! (Edit: or maybe not, see additional comment below)

More details can be found here.

basis_gates not being passed to JSON unroller

Currently there the basis_gates argument of the compile function is ignored when compiling circuits to JSON. This fix simply passes the value of basis gates to the dag2json compiler so that the JSON can be compiled in a user specified set of basis_gates as intended.

Expected Behavior

When you run QuantumProgram.compile('circuit', basis_gates='a,b,c,d') the resulting qobj should compile using the basis gates a,b,c,d.

Current Behavior

When you run QuantumProgram.compile('circuit', basis_gates='a,b,c,d') the JSON unroller is always passed basis_gates='u1,u2,u3,cx,id instead.

Possible Solution

Will add pull request to fix this by adding basis_gates argument to the dag2json function in _openquantumcompiler.py.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.